progon-agent 1.5.1 → 1.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +288 -29
- package/dist/supervisor/cli.js +315 -50
- package/extension-bundle.json +3 -3
- package/extension-dist/background/background.js +142 -119
- package/extension-dist/card/card.css +1 -1
- package/extension-dist/card/card.html +11 -10
- package/extension-dist/card/card.js +3 -3
- package/extension-dist/chunks/shared--PKAvBPy.js +1 -0
- package/extension-dist/chunks/shared-0jT00uC5.js +317 -0
- package/extension-dist/chunks/shared-8TdX8bnw.js +1 -0
- package/extension-dist/chunks/shared-BBwL-FWr.js +8 -0
- package/extension-dist/chunks/shared-BECVQaqd.js +1 -0
- package/extension-dist/chunks/shared-BGvIl9us.js +1 -0
- package/extension-dist/chunks/shared-BYkDbcM2.js +372 -0
- package/extension-dist/chunks/shared-BdaUsVif.css +1 -0
- package/extension-dist/chunks/shared-CDlAJRnF.js +117 -0
- package/extension-dist/chunks/shared-CQ5Ygj2p.js +1 -0
- package/extension-dist/chunks/shared-CnMBv8Ku.js +1 -0
- package/extension-dist/chunks/shared-CyNKhHOY.js +1 -0
- package/extension-dist/chunks/shared-D3X5MuUz.js +1 -0
- package/extension-dist/chunks/shared-D7GfVHk0.js +129 -0
- package/extension-dist/chunks/shared-QityJbuK.css +1 -0
- package/extension-dist/chunks/shared-U9lBnzuH.js +33 -0
- package/extension-dist/chunks/shared-VvEftNwZ.js +1 -0
- package/extension-dist/chunks/shared-XKyaHtl9.js +1 -0
- package/extension-dist/chunks/shared-fJPHxpB5.css +1 -0
- package/extension-dist/chunks/shared-o0-3vI--.js +193 -0
- package/extension-dist/chunks/shared-uKTblxo0.js +15 -0
- package/extension-dist/content/canvas-interceptor.js +1 -1
- package/extension-dist/content/canvas-mapbox-bridge-main.js +1 -1
- package/extension-dist/content/content.css +1 -1
- package/extension-dist/content/content.js +289 -336
- package/extension-dist/content/early-nonce-inject.js +1 -1
- package/extension-dist/content/frame.js +160 -0
- package/extension-dist/content/main-world-nav.js +1 -1
- package/extension-dist/manifest.json +36 -45
- package/extension-dist/offscreen/offscreen.html +2 -2
- package/extension-dist/offscreen/offscreen.js +1 -1
- package/extension-dist/popup/popup.html +9 -9
- package/extension-dist/popup/popup.js +3 -3
- package/extension-dist/sidepanel/sidepanel.css +1 -1
- package/extension-dist/sidepanel/sidepanel.html +13 -13
- package/extension-dist/sidepanel/sidepanel.js +1 -1
- package/extension-dist/workspace/workspace.css +1 -1
- package/extension-dist/workspace/workspace.html +13 -13
- package/extension-dist/workspace/workspace.js +121 -53
- package/npm-shrinkwrap.json +469 -0
- package/package.json +17 -12
- package/extension-dist/chunks/shared-B5u-B6Qn.css +0 -1
- package/extension-dist/chunks/shared-BLDboBjL.js +0 -348
- package/extension-dist/chunks/shared-BdUzhaBn.js +0 -39
- package/extension-dist/chunks/shared-Bl2B_Px5.js +0 -1
- package/extension-dist/chunks/shared-CD1T06ac.js +0 -98
- package/extension-dist/chunks/shared-CDXdhl3P.js +0 -8
- package/extension-dist/chunks/shared-CVlB4Tu3.js +0 -15
- package/extension-dist/chunks/shared-Cz00vYCW.js +0 -1
- package/extension-dist/chunks/shared-D8QWnY4m.css +0 -1
- package/extension-dist/chunks/shared-DDffpwXS.js +0 -134
- package/extension-dist/chunks/shared-D_QceNk9.js +0 -254
- package/extension-dist/chunks/shared-Dp2jkJ8R.js +0 -1
- package/extension-dist/chunks/shared-Jcq39euZ.js +0 -199
- package/extension-dist/chunks/shared-R5ipc0Sn.js +0 -1
- package/extension-dist/chunks/shared-eZL18n5t.css +0 -1
- package/extension-dist/chunks/shared-gwUGKre-.js +0 -1
- package/extension-dist/chunks/shared-hePW80VL.js +0 -1
- package/extension-dist/chunks/shared-kKZVALIt.js +0 -1
- package/extension-dist/chunks/shared-nJgqlX01.js +0 -1
- package/extension-dist/chunks/shared-q9EK7cIP.js +0 -1
- package/extension-dist/chunks/shared-tcQ7xPb-.js +0 -1
- package/extension-dist/content/canvas-mapbox-fiber-discovery.js +0 -1
package/dist/supervisor/cli.js
CHANGED
|
@@ -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
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
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)) !== "fa065b918965327e2e8242f839a56c78d753ab214304a4f5d0b16dcdb4352e6a") {
|
|
6
|
+
throw new Error('Runner build is stale. Run npm run build:publish before starting.');
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
var su=Object.defineProperty;var o=(t,e)=>su(t,"name",{value:e,configurable:!0});import{realpathSync as FS}from"node:fs";import{pathToFileURL as BS}from"node:url";import{z as es}from"zod";var au=/^[a-z_]{1,32}@\d{1,3}$/,ts=es.array(es.string().regex(au)).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",Jn="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 lu=["running","pausing","paused","stopping","completed","cancelled","failed"],ds=y.enum(lu),us=["completed","cancelled","failed"],rE=y.enum(us),cu=["running","pausing","paused","stopping"],oE=y.enum(cu),du=["running","pausing","stopping"],iE=y.enum(du),uu=["paused",...us],sE=y.enum(uu),pu=["user","credits","user_credit_limit","provider_unavailable"],aE=y.enum(pu),mu=["exploring","curation","done"],lE=y.enum(mu),fu=["queued","running","done","failed","cancelled"],cE=y.enum(fu),hu=["done","failed","cancelled"],dE=y.enum(hu),gu=["lead_finished","user_cancelled","lead_failed"],uE=y.enum(gu);var yu=["none","attached","lost"],pE=y.enum(yu),wu=["idle","active","awaiting_user"],mE=y.enum(wu),Su=["atlas","make_auto","preset"],fE=y.enum(Su),Eu=["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"],hE=y.enum(Eu),vu=["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"],bu=y.enum(vu),_u=["web_runs_prompt","web_test_run_dialog","web_map_dialog","web_scenarios_dialog","extension_atlas_card","extension_make_auto_modal","web_workflow_repeat"],gE=y.enum(_u),yE=y.union([bu,y.literal("chat")]),ku=["browser","agent","none"],Ru=y.enum(ku),Tu=["browser","agent"],wE=y.enum(Tu),xu=["explore_app","find_bugs","create_tests","automate_scenarios","run_scenarios","custom"],SE=y.enum(xu),Iu=["file_bugs","write_tests","edit_project"],EE=y.enum(Iu),Ou=["text","auto"],vE=y.enum(Ou),Au=["project","scenarios","test_run","test_plan"],bE=y.enum(Au),Cu=["host_lost","awaiting_browser","awaiting_user","paused"],_E=y.enum(Cu),Pu=["window","mcp_agent","agent"],kE=y.enum(Pu),Nu=["opening","idle","busy","closing","closed"],RE=y.enum(Nu),Lu=["lead","user","window_closed","workflow_ended","workflow_paused","unit_ended"],TE=y.enum(Lu),Du=["lead","user","workflow_ended","no_connection","left"],xE=y.enum(Du),$u=["lead","user","workflow_ended","workflow_paused","unit_ended"],IE=y.enum($u),Uu=["lead","user","window_closed","workflow_ended","workflow_paused","no_connection","left","unit_ended"],OE=y.enum(Uu),Mu=["make_auto","atlas","run","agent","mcp_task","check_launch"],AE=y.enum(Mu);var Gu=["starting","running","ended"],CE=y.enum(Gu),Fu=["completed","cancelled","failed","start_failed","lost"],PE=y.enum(Fu),Bu=["user","lead","left","no_connection","workflow_ended","not_taken"],ju=y.enum(Bu);var Wu=["lead","user","window_closed","host_lost","host_refused","workflow_ended","workflow_paused"],NE=y.enum(Wu),Hu=["lead_choice","role_default"],LE=y.enum(Hu),Ku=["observe","main","dangerous"],DE=y.enum(Ku),Ju=["main","dangerous"],ps=y.enum(Ju);var Vu=["workflow.access_hint_lost","workflow.window_refused","workflow.tab_refused","workflow.scenario_needs_conversion","workflow.identity_busy","workflow.identity_not_set"],$E=y.enum(Vu),qu=["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"],UE=y.enum(qu),ME=y.object({status:ds}),Yu=y.object({status:ds}),Xu=["conversation_deleted","text_not_stored"],zu=y.enum(Xu),GE=Yu.extend({reason:zu.extract(["conversation_deleted"]).optional()}),FE=y.object({segment:y.number().int().min(1)}),BE=y.object({executorKind:Ru}),jE=y.object({reason:y.enum(["ended","no_browser"])}),WE=y.object({reason:y.literal("task_paused")}),HE=y.discriminatedUnion("outcome",[y.object({outcome:y.enum(["finished","stopped"]),lostReason:y.null()}),y.object({outcome:y.literal("lost"),lostReason:ju})]),KE=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()}),VE=y.object({leaseExpiresAt:y.iso.datetime()}),qE=y.object({workflowId:y.uuid()}),YE=y.object({agentId:y.uuid()});var ZE=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(),Qu=k.object({...fs.shape,environmentId:k.uuid().nullable()}).strict(),ev=k.union([fs,Qu]),tv=k.object({workflowId:k.uuid(),entryUrl:k.url({protocol:/^https?$/}),headful:k.boolean()}).strict(),nv=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 Zu=["queued","launching","in_progress"];var gs=["passed","failed"],ep=["before_hook_failed","no_start_page","no_path_for_page"],tp=["no_route_to_start_page","navigation_service_unavailable","scenario_load_failed","run_policy_unavailable","variables_load_failed","start_failed"],Po=[...ep,...tp],lv=De.enum(Po).exclude(["before_hook_failed"]),cv=De.object({executorFailureReason:De.literal("launch_error").optional()}).strict().default({});var dv=[...hs,...Zu];var uv=De.object({by:De.literal("human"),outcome:De.enum(gs)}).strict(),pv=De.object({outcome:De.enum(gs)}).strict();var np=["queued","launching","in_progress","completed","failed","cancelled"],yv=bt.enum(np);var rp=["queued","launching","in_progress"],ys=bt.enum(rp);var op=["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"],wv=bt.enum(op),ip=["launch_error","browser_gone","max_duration"],No=bt.enum(ip),sp=["name_not_resolved","unreachable","certificate","timeout","other"],ws=bt.enum(sp);var ap=["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"],lp=bt.enum(ap),cp=["workflow_host_lost"],Sv=lp.exclude(cp);var dp=f.enum(["darwin","linux","win32"]),up=f.enum(["x64","arm64"]),Es=f.enum(["official","debug"]),Tv=f.object({enrollmentCode:f.string().min(32),hostname:f.string().min(1).max(255),platform:dp,arch:up,agentVersion:f.string().min(1).max(30),protocolVersion:f.number().int().min(1)}).strict(),Vn=f.object({agentId:f.uuid(),agentToken:f.string().regex(vt),pollWaitSec:f.number().int().min(1).max(25),protocolVersion:f.literal(1)}).strict(),xv=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,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(),pp=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(),mp=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(),Iv=f.union([Lo,$o,Do,pp,mp,Uo]),fp={playback:!0,swarm:!0,scenario_launch:!0,task_identity:!0,task_launch:!0,conversation:!0},Ov=Object.keys(fp),Av=f.object({agentJobId:f.uuid(),updatedAt:f.iso.datetime()}).strict(),hp=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:hp}).strict()]),_s=f.object({cancelRequested:f.boolean(),killRequested:f.boolean()}).strict(),gp=2147483646,yp=f.object({stepId:f.uuid(),stepIndex:f.number().int().min(0).max(gp),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(),Cv=f.object({events:f.array(yp).min(1).max(50)}).strict(),Pv=f.object({updated:f.number().int().min(0),control:_s}).strict(),Nv=f.object({phase:f.enum(["running","paused"])}).strict(),Lv=f.object({control:_s}).strict(),Ss=f.string().max(500).optional(),Dv=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 Bv=v.union([v.object({}).strict(),v.object({capabilities:ts}).strict()]);function qn(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(qn,"checkClaimRunIdAgreement");function wp(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(wp,"checkPlaybackClaimProjectAgreement");var Sp=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(qn).check(wp),Yn=v.object({accessToken:v.string().min(1),refreshToken:v.string().min(1)}).strict(),Go=v.object({extensionSession:Yn}).strict(),Ep=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:Yn,command:$o}).strict().check(qn),vp=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:Yn,command:Do}).strict().check(qn),bp=v.object({kind:v.literal("conversation"),runId:v.uuid(),headful:v.boolean(),maxRunDurationSec:v.number().int().min(60).max(604800),extensionSession:Yn,command:Uo}).strict().check(qn),Rs=v.union([Sp,Ep,vp,bp]);import{z as Ts}from"zod";var _p=["finished","cancelled","ai_disabled"],kp=Ts.enum(_p),Kv=Ts.object({outcome:kp}).strict();import{spawn as Np}from"node:child_process";import{existsSync as Lp}from"node:fs";import{createRequire as Dp}from"node:module";import{dirname as Ls,join as $p}from"node:path";var Rp=new Set(["token","agenttoken","accesstoken","refreshtoken","pgrttoken","jobtoken","authorization","secret","password","resolvedvariables","cookie","set-cookie","x-api-key","proxy-authorization","api-key"]),Tp=/\b(?:pgat_|rr_|pgrt_|pgci_|pat_|mcp_at_)[A-Za-z0-9_-]+/g,an="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 xp(t){let e=[],n=0,r=-1,i=t.indexOf(an);for(;i!==-1;){let s=i+an.length;if(i>0&&Is(t.charCodeAt(i-1))){i=t.indexOf(an,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(an,r);continue}e.push(t.slice(n,i),ln),n=c,i=t.indexOf(an,n)}return e.length===0?t:(e.push(t.slice(n)),e.join(""))}o(xp,"redactJwsSpans");var Ip=["token","secret","password","authorization","api_key","api-key","apikey"],Op=new RegExp(`([?&](?:${Ip.join("|")})=)([^&\\s]+)`,"gi"),Ap=/(\bhttps?:\/\/)[^\s/?#]*@/gi,ln="[REDACTED]";function As(t){let e=xp(t);return e=e.replace(Tp,ln),e=e.replace(Op,`$1${ln}`),e=e.replace(Ap,`$1${ln}@`),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))Rp.has(r.toLowerCase())?n[r]=ln: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 Cp(){let t=process.env.PROGON_LOG_LEVEL;return t!==void 0&&Cs.has(t)?t:process.env.NODE_ENV==="production"?"info":"debug"}o(Cp,"resolveLogLevel");function Pp(){if(process.env.NODE_ENV!=="production")return{target:"pino-pretty",options:{translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname"}}}o(Pp,"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:Cp(),transport:Pp(),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 ib=jo(Ns,{});function Xn(){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(Xn,"routeLogsAwayFromStdout");var Wo=w("browser-provision"),Up=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=Dp(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=$p(Ls(e),"cli.js");if(!Lp(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?Up: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=Np(e.execPath,[e.cliPath,...r],{env:process.env,stdio:["ignore","pipe","pipe"]}),{stdout:c,stderr:a}=l,d=t.stdio==="pipe"?Gp:Mp;$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 iu=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 ${iu} (${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 Mp(t,e){t!==""&&process[e].write(`${C(t)}
|
|
16
|
+
`)}o(Mp,"printLine");function Gp(t,e){let n=t.replace(/\r/g,"").trim();n!==""&&Wo.info("Chromium provisioning output",{stream:e,line:n})}o(Gp,"logLine");import{homedir as Dm}from"node:os";import{isAbsolute as ia,join as rr,resolve as $m}from"node:path";var p=class extends Error{static{o(this,"OperatorRefusalError")}};var Fp=new Set(["localhost","127.0.0.1","::1","[::1]"]);function Bp(t){return t.protocol==="https:"||t.protocol==="http:"&&Fp.has(t.hostname)}o(Bp,"usesTrustedHttpScheme");function ke(t){let e;try{e=new URL(t)}catch{throw new p("[config] PROGON_SERVER_URL is not a valid https:// URL.")}if(!Bp(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(ke,"validateServerUrl");function cn(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(cn,"validateRunnerToken");function Ko(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(Ko,"validateRunnerMachineId");function Jo(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(Jo,"validateProtocolVersion");import{Agent as jp,EnvHttpProxyAgent as Wp}from"undici";var Us=w("gateway-proxy"),Hp=["http_proxy","HTTP_PROXY"],Kp=["https_proxy","HTTPS_PROXY"],Jp=["no_proxy","NO_PROXY"];function Vp(t){return t.http!==void 0||t.https!==void 0}o(Vp,"gatewayIsProxied");var qp=/^[A-Za-z][A-Za-z0-9+.-]*:\/\//,Yp=/:\d+$/,Xp=/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)?[^/?#]*@/;function zp(t){let e=Xp.exec(t);if(e===null)return t;let n=e[1];return`${n===void 0?"":n}***@${t.slice(e[0].length)}`}o(zp,"withoutProxyCredentials");function Rt(t,e,n){return new p(`[config] ${t} does not name a proxy this agent can use: ${n}. Got: ${JSON.stringify(zp(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 Qp(t){for(let e of Jp){let n=t[e];if(n!==void 0)return n}}o(Qp,"readNoProxy");function Gs(t,e){if(qp.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(!Yp.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 dn(t){let e=Ms(t,Hp),n=Ms(t,Kp);return{http:e===void 0?void 0:Gs(e.variable,e.raw),https:n===void 0?void 0:Gs(n.variable,n.raw),noProxy:Qp(t)}}o(dn,"resolveGatewayProxyConfig");function Fs(t,e,n){if(!Vp(t))return new jp(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 Wp(i)}o(Fs,"createProxyAwareDispatcher");function zn(t){dn(t)}o(zn,"validateGatewayProxyEnv");import{X509Certificate as Zp}from"node:crypto";import{readFileSync as em,statSync as tm}from"node:fs";import{isAbsolute as nm}from"node:path";import{rootCertificates as Bs}from"node:tls";var rm=w("gateway-tls-trust"),Qn="PROGON_AGENT_EXTRA_CA_CERTS",js="NODE_EXTRA_CA_CERTS";function om(t,e,n){let r=`[config] ${Qn} 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 ${Qn} to trust only the public roots.`;return n===void 0?new p(r):new p(r,{cause:n})}o(om,"refuseExtraCaValue");function Zn(t){let e=t[Qn];if(e===void 0||e==="")return;let n=Ws(e);if("because"in n)throw om(e,n.because,n.cause);return{variable:Qn,path:e,pem:n.pem}}o(Zn,"resolveExtraCaTrust");function Ws(t){if(!nm(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=tm(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=em(t,"utf8")}catch(r){return{because:"its contents could not be read",cause:r}}try{new Zp(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 Ks(t){let e=Zn(t);if(e!==void 0)return rm.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(Ks,"readTrustedCaBundle");function er(t){Zn(t)}o(er,"validateExtraCaTrustEnv");import{readFileSync as cm}from"node:fs";import{dirname as dm,join as um}from"node:path";import{fileURLToPath as pm}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 im}from"node:fs";import{dirname as sm,join as am}from"node:path";var Js="package.json";function we(t){let e=t;for(;;){if(lm(e))return e;let n=sm(e);if(n===e)throw new Error(`[package-root] No ${Js} 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(we,"findPackageRoot");function lm(t){try{return im(am(t,Js)),!0}catch(e){if(P(e))return!1;throw e}}o(lm,"holdsPackageManifest");var mm="extension-bundle.json";function Tt(){return fm(um(we(dm(pm(import.meta.url))),mm))}o(Tt,"readBundledAppUrl");function fm(t){let e;try{e=cm(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{ke(r)}catch(i){throw new p(`[extension-bundle] ${t} has an invalid 'appUrl': ${String(i)}`,{cause:i})}return r}o(fm,"readBundledAppUrlFrom");import{unlinkSync as Nm}from"node:fs";import{readFileSync as _m,writeFileSync as km,renameSync as Rm,existsSync as Tm,fchmodSync as xm,openSync as qs,fsyncSync as Ys,closeSync as Xs,unlinkSync as Im}from"node:fs";import{join as zs}from"node:path";import{spawnSync as hm}from"node:child_process";import{chmodSync as gm,mkdirSync as ym}from"node:fs";import{resolve as wm}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 un(t){return Buffer.from(t,"utf16le").toString("base64")}o(un,"encodePowerShellCommand");var Sm=3e4,Vs=new Set;function xt(t){let e=wm(t);if(ym(e,{recursive:!0,mode:448}),process.platform!=="win32"){gm(e,448);return}Vs.has(e)||(bm(e),Vs.add(e))}o(xt,"makeStateDirPrivate");function Em(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(Em,"renderAccessListScript");var vm=$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 bm(t){let e=hm(tt,["-NoProfile","-NonInteractive","-EncodedCommand",un(Em(t))],{encoding:"utf8",timeout:Sm,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=vm.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(bm,"setOwnerOnlyAccessList");var tr=w("state-file");function nt(t){return zs(t,"runner-state.json")}o(nt,"stateFilePath");function pn(t){return zs(t,"runner-state.json.tmp")}o(pn,"stateTmpPath");function Qs(t){let e=nt(t);if(!Tm(e))return tr.debug("No state file found \u2014 first start",{filePath:e}),null;let n;try{n=_m(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=Cm(r,e);return tr.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=pn(t),i=JSON.stringify(e,null,2);try{let s=qs(r,"w",384);try{xm(s,384),km(s,i,{encoding:"utf-8"}),Ys(s)}finally{Xs(s)}Rm(r,n),Am(t)}catch(s){throw Om(r),new p(`[state-file] Failed to write state file at ${n}: ${String(s)}. Check permissions on stateDir ${t}.`)}tr.info("State file written",{agentId:e.agentId,filePath:n})}o(Zs,"writeState");function Om(t){try{Im(t)}catch(e){if(e.code==="ENOENT")return;tr.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(Om,"removeStateTmp");function Am(t){let e=qs(t,"r");try{Ys(e)}finally{Xs(e)}}o(Am,"fsyncDirectory");function Cm(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).`);Ko(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).`);cn(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).`);Jo(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{ke(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:Pm(n,e)}}o(Cm,"validateState");function Pm(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(Pm,"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 nr(t){let e=nt(t),n=pn(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(nr,"wipeAgentIdentity");function ta(t,e){try{return Nm(t),!0}catch(n){if(Lm(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 Lm(t){return t.code==="ENOENT"}o(Lm,"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 ke(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
|
|
13
|
-
PROGON_SERVER_URL is not set; there is no state file in ${r}; and this build carries no ${
|
|
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.`)}
|
|
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 mn(t){let e=process.env[t];return e!==void 0&&e!==""?e:void 0}o(mn,"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 or="progon-agent";function fn(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 rr(n,"Library","Application Support",or);case"linux":{let r=e.XDG_STATE_HOME;if(r===void 0||r==="")return rr(n,".local","state",or);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 rr(r,or)}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 rr(r,or)}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(fn,"resolveDefaultStateDir");function G(){let t=mn("PROGON_RUNNER_STATE_DIR");return t!==void 0?{path:$m(t),source:"env"}:{path:fn(process.platform,process.env,Dm()),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 hn(){let t=mn("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(hn,"loadBrowserRuntimeEnv");function Me(){zn(process.env),er(process.env);let t=process.env.PROGON_AGENT_TOKEN;if(t==="")throw new p("[config] PROGON_AGENT_TOKEN is set but empty. To use the persisted state-file token, unset this variable entirely. To rotate the token, set it to the new pgat_ token. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.");let e=t;e!==void 0&&cn(e);let n=G().path,r=oa({envUrl:mn("PROGON_SERVER_URL"),envTokenPresent:e!==void 0,stateDir:n}),i=mn("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,...hn(),enrollmentCode:i,nodeEnv:mn("NODE_ENV")??"production"}}o(Me,"loadConfig");import{randomUUID as Mg}from"node:crypto";function gn(t,e,n){process.stderr.write(JSON.stringify({level:t,module:"process-guards",msg:e,...n})+`
|
|
48
|
+
`)}o(gn,"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){gn("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 ir=["SIGTERM","SIGINT","SIGHUP"];function da(t){let e=!1,n=o(r=>{if(e){gn("info","Shutdown already in progress \u2014 signal ignored",{signal:r});return}e=!0,gn("info","Signal received \u2014 shutting down",{signal:r}),(async()=>{try{await t(r)}catch(i){gn("fatal","Shutdown hook failed \u2014 the daemon may leave resources behind",{signal:r,...la(i)}),process.exit(1)}gn("info","Shutdown complete",{signal:r}),process.exit(0)})()},"handle");for(let r of ir)process.on(r,n);return n}o(da,"installShutdownHandlers");var Um=w("debug-env-guard"),Mm=["pw:protocol","pw:api"];function Gm(t){return t.replace(/[\\^$.|?+()[\]{}]/g,"\\$&")}o(Gm,"escapeRegExp");function ua(t){if(t.startsWith("-"))return!1;let e=`^${t.split("*").map(Gm).join(".*?")}$`,n=new RegExp(e);return Mm.some(r=>n.test(r))}o(ua,"enablesPlaywright");function Fm(){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(","),Um.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(Fm,"sanitizePlaywrightDebugEnv");Fm();import{statSync as fa}from"node:fs";import{isAbsolute as Jm,join as Vm}from"node:path";import{createRequire as Bm}from"node:module";var Re=Bm(import.meta.url)("playwright-core"),rt=Re.chromium,H_=Re.firefox,K_=Re.webkit,J_=Re.selectors,V_=Re.devices,pa=Re.errors,q_=Re.request,Y_=Re._electron,X_=Re._android;import{writeFileSync as jm}from"node:fs";import{join as Wm}from"node:path";var Hm="Local State",Km={async_dns:{enabled:!1},dns_over_https:{mode:"off"}};function ma(t){jm(Wm(t,Hm),JSON.stringify(Km),{flag:"wx"})}o(ma,"writeOsResolverLocalState");var yn="chromium";var sr="instances",ar="instance.json";var qm=["--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:yn,...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?qm:[]]})}o(ga,"launchExtensionContext");async function ya(t){return rt.launchPersistentContext(t,{headless:!0,channel:yn,...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 Ym(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(Ym,"requireBrowser");function Sa(t){return Ym(t).version()}o(Sa,"readChromeVersion");async function lr(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(lr,"raceClose");function cr(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=Vm(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(cr,"assertUsableExtensionDist");import{fetch as rf}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 Xm}from"node:fs";import{dirname as zm,join as Qm}from"node:path";import{fileURLToPath as Zm}from"node:url";var ef=/^\d+\.\d+\.\d+$/,Ea=30,qo=null;function te(){if(qo!==null)return qo;let t=we(zm(Zm(import.meta.url))),e=JSON.parse(Xm(Qm(t,"package.json"),"utf8")),n=typeof e=="object"&&e!==null?e.version:void 0;if(typeof n!="string"||!ef.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"?J(ee,t,e):null}o(ba,"mapClientVersionRefusal");function _a(t){return t.status===401&&t.errorCode==="agent_enroll.invalid_code"?J(At,"enroll",t):t.status===409&&t.errorCode==="agent_enroll.protocol_version"?J(ot,"enroll",t):ne("enroll",t)}o(_a,"mapEnrollError");function ka(t){return t.status===409&&t.errorCode==="agent_enroll.protocol_version"?J(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"?J(Nt,"enrollment_request_poll",t):t.status===410&&t.errorCode==="agent_enroll.expired"?J(Lt,"enrollment_request_poll",t):t.status===410&&t.errorCode==="agent_enroll.already_completed"?J(Dt,"enrollment_request_poll",t):t.status===401&&t.errorCode==="agent_enroll.invalid_request"?J($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 Te("poll_desired_state",t,()=>ne("poll_desired_state",t))}o(xa,"mapPollDesiredStateError");function Ia(t){return Te("claim",t,()=>t.status===409&&t.errorCode==="run.not_claimable"?J(Ct,"claim",t):t.status===404?J(it,"claim",t):ne("claim",t))}o(Ia,"mapClaimError");function Oa(t){return Te("fail",t,()=>t.status===404?J(it,"fail",t):ne("fail",t))}o(Oa,"mapFailError");function Aa(t){return Te("token_status",t,()=>ne("token_status",t))}o(Aa,"mapTokenStatusError");function Ca(t){return Te("token_rotate",t,()=>ne("token_rotate",t))}o(Ca,"mapTokenRotateError");function Pa(t){return Te("declare_capabilities",t,()=>ne("declare_capabilities",t))}o(Pa,"mapDeclareCapabilitiesError");function Na(t){return Te("identity_session",t,()=>ne("identity_session",t))}o(Na,"mapIdentitySessionError");function La(t){return Te("revoke",t,()=>ne("revoke",t))}o(La,"mapRevokeError");function Da(t){return Te("launch_session",t,()=>ne("launch_session",t))}o(Da,"mapLaunchSessionError");function Te(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"?J(O,t,e):e.status===401?J(Ot,t,e):n()}o(Te,"bearerRoute");function J(t,e,n){return new t(e,n.status,n.errorCode,n.params,n.message,n.retryAfterMs)}o(J,"named");function ne(t,e){return J(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,dr(i),i)}let r;try{r=await n.text()}catch(i){throw new Z(t.operation,dr(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 ur(t,e){return new URL(`${t.replace(/\/+$/,"")}${e}`)}o(ur,"buildServerRouteUrl");function Xo(t,e){let{status:n}=t,r=tf(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 tf(t){return t===null||!/^\d+$/.test(t)?null:Number(t)*1e3}o(tf,"parseRetryAfterMs");var Yo="the response body carried no Progon error envelope";function dr(t){if(!(t instanceof Error))return C(String(t));let e=nf(t.cause);return C(e===""?t.message:`${t.message}: ${e}`)}o(dr,"describeTransportCause");function nf(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(nf,"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 pr=[...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 wn=w("gateway-client"),of=Ga.object({success:Ga.literal(!0)}),sf="/api/agent-gateway";function q(t,e){return ur(t,`${sf}${e}`)}o(q,"buildGatewayUrl");var Fa=3e5,ja=1e4,Ba={headersTimeout:Fa,bodyTimeout:Fa,connect:{timeout:ja}};function af(){let t=Ks(process.env);return Fs(dn(process.env),t===void 0?Ba:{...Ba,connect:{timeout:ja,ca:t}},t)}o(af,"buildGatewayDispatcher");var Qo,Mt=o((t,e)=>{if(Qo===void 0){let n=af();Qo=o((r,i)=>rf(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",Vn.safeParse(i));return wn.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:pr},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 wn.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:pr},signal:e?.signal,mapHttpError:Pa}),wn.info("Capabilities declared",{capabilities:pr})}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",of.safeParse(e)),wn.info("Agent registration revoked on the server by this agent")}useAgentToken(e){this.agentToken=e,wn.info("Adopted a rotated agent token for all subsequent gateway requests")}};import{z as R}from"zod";var mr=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)}),lf=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(lf),total:R.number().int()}),fr="finished",hr="passed",gr="failed",Ka="no_result",Zo="passed",ei="failed",Ja="finished",yr="not_started";var cf="/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")}},df=100,wr=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(mr,r)}async getLaunch(e,n){let r=`/launches/${encodeURIComponent(e)}`,i=await this.call("GET",r,null,this.requestTimeoutMs,n);return this.parse(mr,i)}async listItems(e,n,r){let i=`/launches/${encodeURIComponent(e)}/items?offset=${n}&limit=${df}`,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(mr,i)}async call(e,n,r,i,s){let l=ur(this.serverUrl,`${cf}${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`:dr(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"}:uf(e)?{kind:"help"}:e!=="run"?{kind:"refused",reason:`unknown command 'ci ${e}'`}:pf(n)}o(qa,"parseCiArgs");function uf(t){return t==="--help"||t==="-h"||t==="help"}o(uf,"isHelpFlag");function pf(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 Sn(u);l=!0;continue}if(!mf.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 Sn(u);r=m;break;case"--entry-url":if(i!==null)return Sn(u);i=m;break;case"--runner":if(s!==null)return Sn(u);s=m;break;case"--timeout":{if(c!==null)return Sn(u);let g=ff(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(pf,"parseRunFlags");var mf=new Set(["--spec","--scenario","--environment","--entry-url","--runner","--timeout"]);function Sn(t){return{kind:"refused",reason:`'${t}' is given twice`}}o(Sn,"repeatedFlag");function ff(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(ff,"parseDurationMs");var ti=0,hf=1,ct=2,U=3,gf=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 En(t,e){return t===400||t===401||t===403||t===404||t===422||e!==null&&gf.get(t)?.has(e)===!0?ct:U}o(En,"exitCodeOfRefusalBeforeLaunch");function Ya(t){return t===hr?ti:t===gr?hf: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"?yf(t):t.GITLAB_CI==="true"?wf(t):D(t,"BITBUCKET_BUILD_NUMBER")!==null?Sf(t):null}o(Xa,"readCiJobFacts");function yf(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(yf,"fromGitHub");function wf(t){return ni(D(t,"CI_COMMIT_SHA"),D(t,"CI_COMMIT_REF_NAME"),D(t,"CI_JOB_URL"))}o(wf,"fromGitLab");function Sf(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(Sf,"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 _g,rmSync as kg}from"node:fs";import{tmpdir as Rg}from"node:os";import{join as gc}from"node:path";import{chmodSync as Tf,cpSync as xf,mkdirSync as If,readdirSync as Of,renameSync as Af,rmSync as ii,statSync as ol,writeFileSync as Cf}from"node:fs";import{dirname as Pf,join as Ft}from"node:path";import{fileURLToPath as Nf}from"node:url";import{randomBytes as Ef}from"node:crypto";import{lstatSync as za,readFileSync as vf,renameSync as bf,rmSync as _f,writeFileSync as kf}from"node:fs";import{join as Qa}from"node:path";var Rf=w("cleanup-ownership"),Sr="progon-agent-cleanup.json";function Za(t){return/^progon-agent-cleanup\.json\.tmp-\d+-[0-9a-f]{16}$/.test(t)}o(Za,"isCleanupTemporaryEntry");var Er={version:1,serviceFiles:!1,extensionCopy:!1,profiles:[]};function vr(t){let e=Qa(t,Sr),n;try{if(!za(e).isFile())throw new Error("Cleanup ownership marker is not a regular file");n=JSON.parse(vf(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(vr,"readCleanupOwnership");function br(t,e){let n=Qa(t,Sr),r=`${n}.tmp-${process.pid}-${Ef(8).toString("hex")}`;try{kf(r,JSON.stringify(e),{flag:"wx",mode:384,flush:!0}),bf(r,n)}finally{_f(r,{force:!0})}}o(br,"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=vr(t)??Er;n[e]||br(t,{...n,[e]:!0})}o(nl,"remember");function _r(t,e){return rl(t,e,"remember")}o(_r,"rememberProfileCleanup");function ri(t,e){return rl(t,e,"forget")}o(ri,"forgetProfileCleanup");function rl(t,e,n){try{let r=vr(t)??Er,{profiles:i}=r;return i.includes(e)===(n==="remember")||br(t,{...r,profiles:n==="remember"?[...i,e]:i.filter(s=>s!==e)}),!0}catch(r){return Rf.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 kr=w("extension-dist"),Lf="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 Df(){return we(Pf(Nf(import.meta.url)))}o(Df,"packageRoot");function $f(){return Uf(Ft(Df(),Lf))}o($f,"resolveBundledExtensionSource");function Uf(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(Uf,"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).`}
|
|
21
|
-
`,"utf8")}
|
|
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=
|
|
24
|
-
`)){let
|
|
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 Mf(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??$f(),i=Ft(e,ai),s=Ft(e,`${si}${process.pid}`);return If(e,{recursive:!0,mode:448}),tl(e),Ff(e),ii(s,{recursive:!0,force:!0}),xf(r,s,{recursive:!0}),Tf(s,448),Gf(s,n),ii(i,{recursive:!0,force:!0}),Af(s,i),kr.info("Agent-mode extension dist prepared",{extensionDist:i,sourceDir:r,agentId:n,protocolVersion:1}),i}o(Mf,"prepareAgentExtensionDist");function Gf(t,e){let n={agentMode:!0,agentId:e,protocolVersion:1};Cf(Ft(t,li),JSON.stringify(n,null,2)+`
|
|
83
|
+
`,"utf8")}o(Gf,"writeAgentManifest");function Ff(t){let e;try{e=Of(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}),kr.warn("Removed a leftover extension-dist staging directory",{leftover:r})}catch(i){kr.error("Failed to remove a leftover extension-dist staging directory",{leftover:r,err:i instanceof Error?i.message:String(i)})}}}o(Ff,"removeLeftoverStagingDirs");function Rr(t){return t.overridePath!==void 0?(kr.info("Using the PROGON_AGENT_EXTENSION_DIST override as built",{extensionDist:t.overridePath}),t.overridePath):Mf({stateDir:t.stateDir,agentId:ci(t.agentId)})}o(Rr,"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=Bf(t.error);return e!==null?{retry:!1,reason:e}:{retry:!0,delayMs:ge(t.attempt,t.rng)}}o(Be,"decideGatewayRetry");function Bf(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(Bf,"classifyFailure");import{mkdtempSync as nh,rmSync as rh}from"node:fs";import{tmpdir as oh}from"node:os";import{join as ih}from"node:path";import{execFile as Wf}from"node:child_process";import{promisify as Hf}from"node:util";import{setTimeout as ul}from"node:timers/promises";var Tr=Hf(Wf),xr={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 Kf(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(Kf,"parsePidLines");var di="--user-data-dir=",Jf=new Set([" "," ",'"',"'"]),Vf=new Set([" "," ",'"',"'"]);function qf(t){return t.replace(/[\\^$.|?*+()[\]{}]/g,"\\$&")}o(qf,"escapeEre");function Yf(t){return`(^|[[:space:]'"])${qf(`${di}${t}`)}([[:space:]'"]|$)`}o(Yf,"buildAnchorPattern");function Xf(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||Vf.has(l);if(c&&a)return!0}return!1}o(Xf,"matchesAnchor");async function zf(t){try{let{stdout:e}=await Tr("pgrep",["-f",Yf(t)],xr);return Kf(e)}catch(e){let n=pl(e);if(n!==null&&n.code===1&&n.stdout.trim()==="")return[];throw e}}o(zf,"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 Tr("powershell.exe",["-NoProfile","-NonInteractive","-Command",n],xr),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||Xf(a,t)&&i.push(c)}return i}o(ll,"discoverWin32");async function cl(){let{stdout:t}=await Tr("ps",["-A","-o","pid=,ppid=,pgid="],xr),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 Qf(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(Qf,"expandTree");function Zf(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(Zf,"sigkill");async function Bt(t){return process.platform==="win32"?th(t):eh(t)}o(Bt,"killProcessTree");async function eh(t){let e=await zf(t);if(e.length===0)return{platform:process.platform,userDataDir:t,discoveredPids:[],signalledPids:[],survivorPids:[]};let n=await cl(),{members:r,groups:i}=Qf(n,e),s=[];for(let a of r)Zf(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(eh,"killProcessTreePosix");async function th(t){let e=await ll(t),n=[];for(let i of e)try{await Tr("taskkill.exe",["/T","/F","/PID",String(i)],xr),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(th,"killProcessTreeWin32");var ml=w("browser-sandbox-probe"),sh=[" - 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 Ir(){let t=Date.now(),e=nh(ih(oh(),"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
|
+
${sh}
|
|
90
|
+
Chromium's output: ${r instanceof Error?r.message:String(r)}`,{cause:r})}finally{await ah(n,e)}ml.info("Chromium runs with its sandbox on this machine",{durationMs:Date.now()-t})}o(Ir,"probeBrowserSandbox");async function ah(t,e){try{t!==null&&(await lr(t,2e4)).settled==="closed"||await Bt(e),rh(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(ah,"closeProbeBrowser");var lh=w("run-browser-preparation");async function Or(t){if(await kt({stdio:"pipe",signal:t.signal}),t.signal?.throwIfAborted(),t.disableBrowserSandbox){lh.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 Ir()}o(Or,"prepareRunBrowser");var ch=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 xe(t){let e=t.evaluate(),n=!1;e.catch(s=>{n&&ch.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(xe,"evaluateWithDeadline");var fl={name:"progon-session",version:1,store:"tokens"},hl="accessToken",gl="refreshToken";async function wl(t,e){await xe({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 xe({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 xe({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 xe({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 xe({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 uh(t,e,n){let r=await xe({operation:`read chrome.storage.session['${Jn}']`,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)})),Jn),"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(uh,"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['${Jn}'] 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 uh(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 Ar(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(Ar,"remainingBudgetMs");async function kl(t){let e=Date.now(),n=e+45e3,r=n-5e3,i=await vl(t,Math.min(5e3,Ar(r,"the service-worker target wait")));try{let s=await bl(i,Ar(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,Ar(n,"the retry service-worker target wait"))),a=await bl(c,Ar(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 ph=/^\s*(?:- )?\[pid=\d+\]\[err\] ?(.*)$/;function Rl(t){let e=[];for(let n of t.split(`
|
|
91
|
+
`)){let r=ph.exec(n)?.[1];r!==void 0&&r!==""&&e.push(r)}return e.length===0?null:e.join(" | ")}o(Rl,"browserStderrOf");var mh=new Set(["ERR_CONNECTION_REFUSED","ERR_CONNECTION_RESET","ERR_CONNECTION_CLOSED","ERR_CONNECTION_FAILED","ERR_CONNECTION_TIMED_OUT","ERR_ADDRESS_UNREACHABLE","ERR_TIMED_OUT"]),fh=/\bnet::(ERR_[A-Z0-9_]+)\b/;function Tl(t){if(hh(t))return"timeout";let e=fh.exec(mi(t))?.[1];return e===void 0?"other":e==="ERR_NAME_NOT_RESOLVED"?"name_not_resolved":mh.has(e)?"unreachable":e.startsWith("ERR_CERT_")?"certificate":"other"}o(Tl,"entryFailureOf");function hh(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(hh,"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}},Cr=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 yh(t,r.worker);let{entryUrl:i}=t;return i===null?await ae(t.runId,"empty_tab",()=>vh(e)):await ae(t.runId,"entry_navigation",()=>Eh(e,i)),await wh(t,e),{context:e,chromeVersion:n,extensionId:r.extensionId,readinessAttempts:r.attempts,readyAfterMs:r.readyAfterMs}}o(Pr,"bringUpBrowser");async function yh(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(yh,"seed");async function wh(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(wh,"awaitDispatchAck");async function bn(t,e){let n=Date.now(),r="closed",i=null,s=null;if(e.context!==null){let g=await lr(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:Sh(e,i,s,a)}}o(bn,"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 Sh(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(Sh,"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 Eh(t,e){await(await Il(t)).goto(e,{waitUntil:"domcontentloaded"})}o(Eh,"navigateToEntry");async function vh(t){await Il(t)}o(vh,"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 bh}from"node:module";var Ol=bh(import.meta.url);function _h(){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(_h,"readPlaywrightCoreVersion");function Al(t){return{node:process.version,platform:`${Lr.platform()} ${Lr.release()} ${Lr.arch()}`,cpus:Lr.cpus().length,playwrightCore:_h(),chromiumExecutable:rt.executablePath(),channel:yn,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 xe({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 jt=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}},Wt=class{static{o(this,"TaskBrowserInstances")}#e;#t;#n;#r;#i;#a;#l=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.#l.keys()]}async start(e,n,r,i){let s=this.#l.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.#l.set(n,a),jt.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:e.entryUrl,onContext:o(m=>{a.context=m},"onContext"),assertNotAborted:o(()=>this.#s(a),"assertNotAborted")});this.#s(a),a.state="active",this.#c(a,u.context),jt.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=>{jt.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.#u(a,"launch_failure").catch(m);else if(await a.teardown.catch(m),a.context!==null&&a.context!==a.contextAtTeardown){let g=await bn(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.#l.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.#u(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.#l.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.#l.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)}#s(e){if(e.teardown!==null)throw new fi(e.subjectId)}#c(e,n){let r=o(s=>{if(e.state!=="active"||e.teardown!==null)return;let l=this.#u(e,"instance_lost"),c={jobId:e.jobId,subjectId:e.subjectId,at:new Date().toISOString(),source:s};jt.warn("Task browser instance disappeared without a dispose",{...c}),l.catch(a=>{jt.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"))}#u(e,n){e.state="tearing_down",e.contextAtTeardown=e.context;let r=(async()=>{try{let i=await bn(this.#e,{instanceKey:e.instanceKey,context:e.context,userDataDir:e.userDataDir,timeoutMs:2e4,trigger:n});if(jt.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.#l.get(e.subjectId)===e&&this.#l.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 Wt({...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 Wt({...e,kind:"launch",onLost:o(({subjectId:n,...r})=>e.onLaunchLost({...r,launchId:n}),"onLost")})}async startLaunch(e,n,r,i){let s=hi(e,n);await this.launches.start(s,r,i,{v:1,kind:"task_launch",runId:n,issuedAt:new Date().toISOString(),workflowId:s.workflowId,launchId:r})}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}};function hi(t,e){if(t===null||t.runId!==e)throw new Error(`[runtime] job ${e} is not the running instance (running: ${t===null?"none":t.runId})`);if(t.identityInputs===null)throw new Error(`[runtime] job ${e} is not a task job; only a swarm job hosts task browser instances`);return t.identityInputs}o(hi,"taskInputs");import{mkdirSync as Cl,lstatSync as Rh,readdirSync as Th,readFileSync as xh,renameSync as Ih,rmSync as Oh,writeFileSync as Ah}from"node:fs";import{join as _n}from"node:path";var dt=w("instance-registry");function Mr(t){return typeof t=="string"&&t!==""}o(Mr,"isNonEmptyString");function Ch(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(Ch,"parseInstanceRecord");function Ph(t,e){let n=`${t}.tmp`;Ah(n,JSON.stringify(e,null,2),{encoding:"utf8",mode:384}),Ih(n,t)}o(Ph,"writeMarkerAtomically");var ut=class{static{o(this,"InstanceRegistry")}#e;#t;constructor(e){this.#t=e,this.#e=_n(e,sr)}get instancesRoot(){return this.#e}userDataDirFor(e){return _n(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{_r(this.#t,e),Ph(_n(r,ar),{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(_n(this.userDataDirFor(e),ar))}release(e){let n=this.userDataDirFor(e);try{Rh(n)}catch(i){if(!P(i))throw i;ri(this.#t,e);return}let r=_r(this.#t,e);try{Oh(n,{recursive:!0,force:!0})}catch(i){throw r||_r(this.#t,e),i}ri(this.#t,e),dt.info("Instance released",{runId:e,userDataDir:n})}listRunIds(){let e;try{e=Th(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=_n(n,ar),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=xh(e,"utf8");return Ch(JSON.parse(n),e)}};var Ie=w("playwright-execution-runtime"),gi=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;#l;#o;#s=null;#c=null;#u=!1;#p=null;#m=null;constructor(e){cr(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.#l=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}),Ie.info("Execution runtime constructed",{stateDir:e.stateDir,instancesRoot:this.#a.instancesRoot,headfulOverride:e.headfulOverride,allowInsecureHttps:e.allowInsecureHttps,envFingerprint:this.#l})}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,n,r){await this.#o.identities.start(hi(this.#s,e),n,r)}async startLaunchInstance(e,n,r){await this.#o.startLaunch(this.#s,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.#s;return e===null?{ok:!1,observedAt:new Date().toISOString(),reason:"service_worker_absent",detail:"the runtime owns no browser instance"}:Dr(e.context)}async startRun(e){let n=this.#s;if(n!==null)throw new Cr(e.runId,n.runId);let r=Date.now(),i=new Date(r+e.maxRunDurationSec*1e3).toISOString(),s=this.#g(e),l=Nh(e,s,i),c=await ae(e.runId,"instance_reserve",()=>this.#a.reserve(e.runId,i));this.#m?.runId===e.runId&&(this.#m=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";Ie.info("Launching browser for run",{runId:e.runId,headful:s,requestHeadful:e.headful,headfulOverride:this.#t,keepBackgroundWindowsRendering:d,userDataDir:c.userDataDir,maxRunDurationSec:e.maxRunDurationSec,deadlineAt:i,envFingerprint:this.#l});let u=null;try{let m=await Pr({runId:e.runId,userDataDir:c.userDataDir,extensionDist:this.#e,headful:s,allowInsecureHttps:this.#n,disableBrowserSandbox:this.#r,keepBackgroundWindowsRendering:d,extensionSession:e.extensionSession,command:e.command,entryUrl:e.entryUrl,onContext:o(E=>{u=E,a.context=E},"onContext"),assertNotAborted:o(()=>this.#f(a),"assertNotAborted")}),g={runId:e.runId,context:m.context,userDataDir:c.userDataDir,headful:s,extensionId:m.extensionId,chromeVersion:m.chromeVersion,startedAt:c.startedAt,deadlineAt:i,identityInputs:l};this.#f(a),this.#y(g),this.#s=g,this.#c===a&&(this.#c=null),Ie.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.#h({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){let[r,i]=await Promise.allSettled([this.#o.disposeAll(e),this.#d(e,n)]);if(i.status==="rejected")throw i.reason;if(r.status==="rejected")throw r.reason;return i.value}async#d(e,n){let r=this.#p;if(r!==null&&r.runId===e)return Ie.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,Ie.warn("Dispose requested for a run that is still launching \u2014 aborting the launch",{runId:e,userDataDir:i.userDataDir,contextPresent:i.context!==null}),this.#h({runId:e,context:i.context,userDataDir:i.userDataDir,timeoutMs:n,trigger:"dispose_during_launch"});let s=this.#s;return s===null||s.runId!==e?this.#w(e):(this.#s=null,this.#h({runId:e,context:s.context,userDataDir:s.userDataDir,timeoutMs:n,trigger:"dispose"}))}#g(e){return e.headful||this.#t}#f(e){if(e.disposeRequested)throw new gi(e.runId)}#y(e){let n=o(i=>{if(this.#u||this.#s?.runId!==e.runId)return;this.#s=null;let s=this.#h({runId:e.runId,context:e.context,userDataDir:e.userDataDir,timeoutMs:2e4,trigger:"instance_lost"});this.#p={runId:e.runId,promise:s},s.catch(c=>{Ie.error("Teardown after a lost browser instance failed",{runId:e.runId,userDataDir:e.userDataDir,err:c instanceof Error?c.message:String(c)})}).finally(()=>{this.#p?.promise===s&&(this.#p=null)});let l={runId:e.runId,at:new Date().toISOString(),source:i};Ie.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"))}#w(e){let n=this.#m;if(n===null||n.runId!==e)return Ie.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(n.result.instanceReleased)return Ie.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.#m={runId:e,result:r,killConfirmed:!0},r}async#h(e){this.#u=!0;try{let n=await bn(this.#a,{instanceKey:e.runId,context:e.context,userDataDir:e.userDataDir,timeoutMs:e.timeoutMs,trigger:e.trigger});if(this.#m={runId:e.runId,result:n.result,killConfirmed:n.killConfirmed},n.failure!==null)throw n.failure;return n.result}finally{this.#u=!1}}};function Nh(t,e,n){if(t.command.kind!=="swarm")return null;if(t.entryUrl===null)throw new Error(`[runtime] swarm job ${t.runId} was handed to the runtime without its entry address, which its claim member requires`);return{jobId:t.runId,workflowId:t.command.workflowId,entryUrl:t.entryUrl,headful:e,deadlineAt:n}}o(Nh,"identityInputsOf");import{setTimeout as Lh}from"node:timers/promises";var He=w("supervisor-identity");function yi(t){if(t.initialToken!==void 0)return{source:"env_token",agentToken:t.initialToken};let e=L(t.stateDir);return e===null?null:(Bh(e.serverUrl,t.serverUrl),{source:"state_file",agentToken:e.agentToken,agentId:e.agentId})}o(yi,"selectExistingCredential");async function Fr(t){let{config:e}=t,n=yi(e);if(n?.source==="env_token")return Dh(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 Uh(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.`)}
|
|
28
|
-
Mint a fresh code in Progon (Settings \u2192 Agents) once the server is reachable, then run 'progon-agent enroll <code>' again.`,{cause:
|
|
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 Dh(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:$h(t.stateDir)}),{agentToken:e,agentId:null,pollWaitSec:void 0,source:"env_token"}}o(Dh,"identityFromEnvToken");function $h(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($h,"describeStateFile");async function Uh(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 Gh(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(Uh,"enrollThisMachine");var Pl=900*1e3,Mh=3e4;async function Gh(t,e,n,r){let i=Date.now()+Pl;for(let s=0;;s+=1)try{return await Fh(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 ${Pl/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 Lh(c.delayMs,void 0,{signal:r}).catch(a=>{throw r?.throwIfAborted(),a})}}o(Gh,"enrollWithRetry");async function Fh(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),Mh)},"onStop");n.addEventListener("abort",s,{once:!0});try{return await t.enroll(e,{signal:r.signal})}finally{n.removeEventListener("abort",s),clearTimeout(i)}}o(Fh,"enrollOnce");function Nl(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
|
-
`+
|
|
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
|
-
`+
|
|
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
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
`)
|
|
41
|
-
|
|
42
|
-
`),
|
|
43
|
-
`)
|
|
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
|
-
`)
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
99
|
+
`+n)}o(Nl,"assertEnrollmentCodeWasRedeemed");function Bh(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(Bh,"assertServerMatchesEnrollment");import{hostname as jh}from"node:os";var Ll=["darwin","linux","win32"],Dl=["x64","arm64"];function Wh(t){return Ll.includes(t)}o(Wh,"isSupportedPlatform");function Hh(t){return Dl.includes(t)}o(Hh,"isSupportedArch");function Ke(){let t=process.platform;if(!Wh(t))throw new Error(`[supervisor] Unsupported platform ${JSON.stringify(t)}. The local agent runs on ${Ll.join(", ")} (CONTRACT-la \xA75.1, \xA710.3).`);let e=process.arch;if(!Hh(e))throw new Error(`[supervisor] Unsupported CPU architecture ${JSON.stringify(e)}. The local agent runs on ${Dl.join(", ")} (CONTRACT-la \xA75.1).`);let n=jh();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(Ke,"describeAgentMachine");var $l=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($l,$l),n}};var Ul=w("supervisor-deadline"),kn=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 Je(t){let e=t.work(),n=!1;e.then(()=>{n&&Ul.warn("Abandoned work settled successfully after its deadline had passed",{operation:t.operation,timeoutMs:t.timeoutMs})},s=>{n&&Ul.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 kn(t.operation,t.timeoutMs))},t.timeoutMs)});try{return await Promise.race([e,i])}finally{r!==void 0&&clearTimeout(r)}}o(Je,"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,Ht=Wr*1e3,wi=3e4,Kt=3,Si=45*1e3,Ei="agent shutdown";var Hr=w("task-launch-reconciler"),Kr=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 Je({operation:`startLaunchInstance(${e.jobId}, ${n})`,timeoutMs:Ht,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 Jt=w("run-monitor");function Jh(t,e){let n=Date.now();return e.ok?e.tabs.some(i=>i.playback!==null&&i.playback.runId===t)?{healthy:!0}:Vh(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 (${qh(e.tabs)}; ${Yh(e.agentJob,n)})`}:{healthy:!1,reason:e.reason,detail:e.detail}}o(Jh,"judgeProbe");function Vh(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<=Si}o(Vh,"isJobPulseStanding");function qh(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(qh,"describeTabs");function Yh(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(Si)}ms)`}o(Yh,"describeJobMarker");var Vt=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());Jt.info("Monitoring launched run",{runId:this.#e.runId,identityId:this.#e.identityId,deadlineAt:this.#e.deadlineAt,deadlineInMs:e,probeIntervalMs:wi,probeStrikeLimit:Kt}),this.#n=setInterval(()=>{this.#l()},wi),this.#n.unref();let n=this.#e;n.identityId===null&&(this.#r=setTimeout(()=>{this.#a||(this.stop(),Jt.error("Run reached its server-authored deadline",{runId:this.#e.runId,identityId:this.#e.identityId,deadlineAt:this.#e.deadlineAt}),n.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#l(){if(this.#a)return;let e=await this.#o();if(this.#a)return;let n=e.ok?e.detachedIdentity:void 0;if(this.#e.identityId!==null&&n?.agentJobId===this.#e.runId&&n.identityId===this.#e.identityId){this.stop(),this.#e.onIdentityDetached();return}let r=Jh(this.#e.runId,e);if(r.healthy){this.#i>0&&Jt.info("Liveness probe recovered",{runId:this.#e.runId,identityId:this.#e.identityId,clearedStrikes:this.#i}),this.#i=0;return}this.#i+=1;let i=`${r.reason}: ${r.detail}`;Jt.warn("Liveness probe failed",{runId:this.#e.runId,identityId:this.#e.identityId,strike:this.#i,strikeLimit:Kt,reason:r.reason,detail:r.detail}),!(this.#i<Kt)&&(this.stop(),Jt.error("Liveness probe failed the strike limit \u2014 the browser is gone",{runId:this.#e.runId,identityId:this.#e.identityId,strikes:Kt,detail:i}),this.#e.onBrowserGone(`${Kt} consecutive liveness probes failed (${i})`))}async#o(){try{return await this.#e.probe()}catch(e){let n=e instanceof Error?e.message:String(e);return Jt.error("Liveness probe threw instead of reporting an observation",{runId:this.#e.runId,identityId:this.#e.identityId,err:n}),{ok:!1,observedAt:new Date().toISOString(),reason:"evaluate_failed",detail:n}}}};var Ee=w("identity-reconciler"),Jr=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&&Ee.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.#u(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&&Ee.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){Ee.info("An identity instance of a finished job went away \u2014 nothing to relaunch",{...e});return}this.#m(n,e.identityId),this.#c(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 Je({operation:`startIdentityInstance(${e.jobId}, ${n})`,timeoutMs:Ht,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.#l(e,n,r))}async#l(e,n,r){e.launching.delete(n);let i=this.#r===e;if(r!==null){if(Ee.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.#u(e,n,"identity_left_run_block");return}this.#o(e,n)}#o(e,n){let r=new Vt({runId:e.jobId,identityId:n,deadlineAt:e.deadlineAt,probe:o(()=>this.#e.probeIdentityInstance(n),"probe"),onBrowserGone:o(i=>{this.#n(()=>this.#s(e,n,i))},"onBrowserGone"),onIdentityDetached:o(()=>{this.#n(async()=>{this.#r!==e||e.monitors.get(n)!==r||this.#u(e,n,"identity_detached")})},"onIdentityDetached")});e.monitors.set(n,r),r.start(),Ee.info("Identity instance is up and monitored",{runId:e.jobId,identityId:n})}async#s(e,n,r){this.#r===e&&(e.monitors.delete(n),Ee.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.#c(e,n,r))}#c(e,n,r){if(this.#r===e){if(!e.desired.has(n)){Ee.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)||(Ee.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))}}#u(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.#c(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;Ee.info("Identity instance disposed",{runId:e.jobId,identityId:n,trigger:r,disposeOutcome:i.outcome,instanceReleased:i.instanceReleased,durationMs:i.durationMs})}catch(i){Ee.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 ve=w("launch-run");async function Fl(t){let e;try{e=await Xh(t)}finally{t.onClaimAnswered()}return e.kind!=="claimed"?e:Zh(t,e.payload)}o(Fl,"claimAndLaunch");async function Xh(t){try{let e=await t.client.claimRun(t.runId);return ve.info("Run claimed",zh(e)),{kind:"claimed",payload:e}}catch(e){if(e instanceof T)throw e;if(e instanceof O)throw ve.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 ve.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 ve.error("Claim produced no usable answer \u2014 not launching, leaving it to the sweep",{runId:t.runId,err:e.message}),{kind:"claim_unavailable"}}}o(Xh,"claimRun");function zh(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(zh,"describeClaim");function Qh(t){if(!("kind"in t))return t.entryUrl;switch(t.kind){case"swarm":case"scenario_launch":return t.entryUrl;case"conversation":return null;default:{let e=t;throw new Error(`Unexpected claim kind: ${JSON.stringify(e,["kind"])}`)}}}o(Qh,"entryUrlOf");async function Zh(t,e){try{await Je({operation:`startRun(${e.runId})`,timeoutMs:Ht,work:o(()=>t.runtime.startRun({runId:e.runId,entryUrl:Qh(e),headful:e.headful,maxRunDurationSec:e.maxRunDurationSec,extensionSession:e.extensionSession,command:e.command}),"work")})}catch(r){return{kind:"failed",body:tg(t.runId,r)}}let n=t.runtime.getActiveInstance();return n===null||n.runId!==e.runId?(ve.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(Zh,"launchClaimedRun");var Ml=500,Gl="\u2026";function eg(t){return t.length<=Ml?t:t.slice(0,Ml-Gl.length)+Gl}o(eg,"fitFailMessageToWire");function tg(t,e){if(e instanceof je){let n=mi(e),r=e.stage==="browser_launch"?Rl(n)??n:n,i=eg(`stage ${e.stage}: ${r}`);if(e.stage==="entry_navigation"){let s=Tl(e);return ve.error("Launch failed",{runId:t,stage:e.stage,failReason:e.failReason,entryFailure:s,err:e.message}),{reason:e.failReason,message:i,entryFailure:s}}return ve.error("Launch failed",{runId:t,stage:e.stage,failReason:e.failReason,err:e.message}),{reason:e.failReason,message:i}}return e instanceof kn?(ve.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?(ve.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"}):(ve.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(tg,"describeLaunchFailure");var be=w("instance-reconciler");function ng(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(ng,"createPendingLaunch");var Oe={kind:"reconciled"},Vr=class{static{o(this,"InstanceReconciler")}#e;#t;#n;#r;#i=new Set;#a=null;#l=null;#o=null;#s;#c;#u=null;constructor(e){this.#e=e.client,this.#t=e.runtime,this.#n=e.reporter,this.#r=e.detach,this.#c=new Kr(e),this.#s=new Jr({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(n=>n.runId)),be.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.#u=n===null?null:{runId:n.runId,identityIds:Bl(n),launchIds:jl(n)};let r=this.#l;if(r!==null)return n!==null&&n.runId===r.runId?n.phase!=="queued"?Oe:{kind:"claim_issued",runId:n.runId,claimAnswer:r.claimAnswered?null:r.claimAnswer}:(r.cancelledBy!==null||await this.#f(r,n===null?"desired_state_run_absent":"desired_state_runid_mismatch"),Oe);let i=this.#t.getActiveInstance();return n===null?(i!==null&&await this.dispose(i.runId,"desired_state_run_absent"),Oe):i!==null?i.runId===n.runId?(await this.#s.apply(i.runId,i.deadlineAt,Bl(n)),await this.#c.apply(i.runId,jl(n)),Oe):(await this.dispose(i.runId,"desired_state_runid_mismatch"),Oe):this.#n.hasVerdictFor(n.runId)?Oe:n.phase==="queued"?this.#o===n.runId?(be.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.#o=n.runId,this.#p(n.runId),Oe):(await this.#w(n.runId,n.phase),Oe)}async cancelLaunchAndSettle(e){let n=this.#l;return n===null?null:(be.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.#s.handleLost(e)}async handleLaunchInstanceLost(e){await this.#c.handleLost(e)}async handleInstanceLost(e){be.error("The runtime reported a lost browser instance",{...e}),await this.#h(e.runId,"browser_gone",`the browser instance disappeared (${e.source})`,"browser_gone")}async dispose(e,n){this.stopMonitor(),this.#s.forgetJob(n==="max_duration"?e:void 0),this.#c.forgetJob();try{let r=await this.#t.disposeRun(e);be.info("Instance disposed",{runId:e,trigger:n,disposeOutcome:r.outcome,instanceReleased:r.instanceReleased,kill:r.kill,durationMs:r.durationMs})}catch(r){be.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}#p(e){let n=ng(e);this.#l=n,this.#m(n)}async#m(e){try{let n=await this.#d(e);await this.#r(()=>this.#g(e,n))}finally{e.markSettled()}}async#d(e){try{return{kind:"outcome",outcome:await Fl({client:this.#e,runtime:this.#t,runId:e.runId,onClaimAnswered:e.markClaimAnswered})}}catch(n){return{kind:"thrown",error:n}}}async#g(e,n){if(this.#l===e&&(this.#l=null),n.kind==="thrown")throw n.error;let r=n.outcome;switch(r.kind){case"launched":if(e.cancelledBy!==null){be.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.#y(r.instance.runId,r.instance.deadlineAt),this.#u?.runId===r.instance.runId&&(await this.#s.apply(r.instance.runId,r.instance.deadlineAt,this.#u.identityIds),await this.#c.apply(r.instance.runId,this.#u.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){be.info("A cancelled launch failed on the way down \u2014 no verdict is sent",{runId:e.runId,trigger:e.cancelledBy,suppressedReason:r.body.reason});return}await this.#n.report({runId:e.runId,body:r.body});return}}async#f(e,n){be.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)}#y(e,n){this.#a=new Vt({runId:e,identityId:null,deadlineAt:n,probe:o(()=>this.#t.probePlaybackSession(),"probe"),onBrowserGone:o(r=>{this.#r(()=>this.#h(e,"browser_gone",r,"browser_gone"))},"onBrowserGone"),onDeadline:o(()=>{this.#r(()=>this.#h(e,"max_duration","the run reached its server-authored deadline","max_duration"))},"onDeadline")}),this.#a.start()}async#w(e,n){let r=this.#i.has(e),i=r?"browser_gone":"launch_error";be.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#h(e,n,r,i){await this.dispose(e,i),await this.#n.report({runId:e,body:{reason:n,message:r}})}};function Bl(t){return t.identities===void 0?[]:t.identities.map(e=>e.identityId)}o(Bl,"identityIdsOf");function jl(t){return t.launches===void 0?[]:t.launches.map(e=>e.launchId)}o(jl,"launchIdsOf");function vi(t,e){return t!==78?t:e==="linux"?78:0}o(vi,"serviceExitCode");var Wl="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>.",Hl={revoked:{exitCode:78,level:"error",message:"progon-agent stopped: this agent was revoked and its credential has been wiped. "+Wl},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. "+Wl},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"}},Kl={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,qt=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.#l(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#l(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.#c(r,i.value.tokenRotatedAt,e):this.#s(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}}#s(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#c(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.#u(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#u(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;#l;#o=null;#s=0;#c=0;#u=!1;#p=new AbortController;#m=null;#d=!1;#g=!1;#f;#y=null;#w=null;constructor(e){this.#e=e.client,this.#i=e.stateDir,this.#a=e.pollWaitSec,this.#l=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.#E(()=>this.#n.handleInstanceLost(r))},"onInstanceLost"),onIdentityInstanceLost:o(r=>{this.#E(()=>this.#n.handleIdentityInstanceLost(r))},"onIdentityInstanceLost"),onLaunchInstanceLost:o(r=>{this.#E(()=>this.#n.handleLaunchInstanceLost(r))},"onLaunchInstanceLost")});this.#n=new Vr({client:e.client,runtime:n,reporter:this.#t,detach:o(r=>this.#E(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.#x(),this.#l||await this.#P();!this.#u;){let n=this.#m;if(n!==null)return await this.#_(n),"revoked";if(this.#d)return await this.#k(),"reenroll_required";if(this.#g)return await this.#O(),"credential_unusable";try{await this.#r.run(()=>this.#t.retryPending());let r=await this.#U();this.#s=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),"revoked";if(r instanceof O&&await this.#I(r))return await this.#k(),"reenroll_required";if(this.#u)break;if(this.#v())continue;let i=await this.#j(r);if(i!==null)return i==="credential_unusable"?await this.#O():i==="upgrade_required"?await this.#F():await this.#B(),i}}return this.#h()}async#h(){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#P(){try{await this.#e.declareCapabilities({signal:this.#p.signal})}catch(e){if(await this.#C(e),this.#v())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.#N(e);return this.#w=r,r}async#N(e){B.info("Shutting down",{cause:e}),await this.#S(e==="fatal"?"fatal":"stopped",n=>this.#T(n))}async#S(e,n){this.#u=!0,this.#o?.abort(),this.#p.abort();let r=Kl[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#T(e){let{activeRunId:n,launchingRunId:r}=e;if(n!==null){await this.#R(()=>this.#t.report({runId:n,body:{reason:"browser_gone",message:Ei}}));return}if(r!==null){await this.#R(()=>this.#t.report({runId:r,body:{reason:"browser_gone",message:Ei}}));return}await this.#R(()=>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.#_(e),"revoked";throw e}return await this.#k(),"reenroll_required"}#x(){if(this.#u||this.#p.signal.aborted)return;let e=setTimeout(()=>{this.#y=null,this.#D().finally(()=>{this.#x()})},Jl);e.unref(),this.#y=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.#A(e)}}#$(){this.#y!==null&&(clearTimeout(this.#y),this.#y=null)}async#I(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.#c=0;return}await this.#G(e.runId,e.claimAnswer)}async#G(e,n){let r=ge(this.#c);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.#c,waitMs:r,claimOnTheWire:n!==null}),this.#c+=1;let i=new AbortController;if(this.#o=i,this.#p.signal.aborted||this.#v()){this.#o=null;return}n?.then(()=>i.abort());try{await oe(r,i.signal)}finally{this.#o=null}}async#b(){await this.#f.settle(),nr(this.#i)}async#_(e){B.error("This agent has been revoked \u2014 disposing, wiping the credential and stopping",{signal:e.signal}),await this.#S("revoked",qr),await this.#b()}async#O(){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.#S("credential_unusable",qr)}async#F(){await this.#S("upgrade_required",qr)}async#B(){await this.#S("fatal",e=>this.#T(e))}async#k(){B.error("This agent token has been superseded and its family is no longer accepted \u2014 disposing, wiping the credential and stopping"),await this.#S("reenroll_required",qr),await this.#b()}async#j(e){if(!(e instanceof A))throw e;let n=this.#W(e);return n.kind==="exit"?n.exit:(this.#s+=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.#s);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.#s,retryInMs:r}),{kind:"retry",delayMs:r}}let n=Be({attempt:this.#s,error:e});return n.retry?(B.warn("Desired-state poll failed \u2014 backing off",{attempt:this.#s,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"})}#E(e){return this.#r.run(e).catch(n=>this.#A(n))}async#A(e){await this.#C(e)||B.error("A background supervisor action failed",{err:e instanceof Error?e.message:String(e)})}async#C(e){if(e instanceof T)return this.#m=e,this.#o?.abort(),!0;if(!(e instanceof O))return!1;try{await this.#I(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.#v()&&this.#o?.abort(),!0}#v(){return this.#m!==null||this.#d||this.#g}async#R(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.#b(),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 Vl=w("supervisor-boot");async function ql(t){t?.throwIfAborted();let e=Me();Vl.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=Ke(),r=await Fr({config:e,machine:n,signal:t});t?.throwIfAborted(),Vl.info("Agent identity resolved",{source:r.source,agentId:r.agentId,hostname:n.hostname,platform:n.platform,arch:n.arch,agentVersion:n.agentVersion});let i=Rr({overridePath:e.extensionDistOverride,stateDir:e.stateDir,agentId:r.agentId});await Or({disableBrowserSandbox:e.disableBrowserSandbox,signal:t}),t?.throwIfAborted();let s=new Ge({serverUrl:e.serverUrl,agentToken:r.agentToken}),l=new qt({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(ql,"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 Rn}from"zod";var rg="scenario_launches.scenarios_not_launchable",og=Rn.object({items:Rn.array(Rn.object({scenarioId:Rn.string(),notStartedReason:Rn.string()}))});function Yl(t){if(t.errorCode!==rg)return[];let e=og.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(Yl,"refusedScenarioLines");import{stripVTControlCharacters as dg}from"node:util";import{appendFileSync as ig,statSync as sg}from"node:fs";var ag=1024*1024,Xl=`
|
|
101
|
+
### Progon
|
|
102
|
+
|
|
103
|
+
`;function Zl(t,e){let n;try{n=sg(t).size}catch(i){return{kind:"failed",reason:Ql(i)}}let r=lg(e,ag-n);if(r===null)return{kind:"no_room",fileBytes:n};try{ig(t,r,"utf8")}catch(i){return{kind:"failed",reason:Ql(i)}}return{kind:"written"}}o(Zl,"appendStepSummary");function lg(t,e){let n=t.result.map(Xr).join(""),r=t.reportUrl===null?"":`
|
|
104
|
+
Report: <${t.reportUrl}>
|
|
105
|
+
`,i=pt(Xl)+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=cg(t.details.slice(s.length));for(;l>0&&i+pt(zl(l))>e;){let d=s.pop();if(d===void 0)break;i-=pt(Xr(d)),ec(d)&&(l+=1)}let c=l>0?zl(l):"",a=Xl+n+s.map(Xr).join("")+c+r;return pt(a)<=e?a:null}o(lg,"fitStepSummary");function Xr(t){return` ${t}
|
|
106
|
+
`}o(Xr,"codeLine");function zl(t){return`
|
|
107
|
+
${t} more line(s) are in the job log.
|
|
108
|
+
`}o(zl,"omissionOf");function ec(t){return t.trim()!==""}o(ec,"isText");function cg(t){return t.filter(ec).length}o(cg,"countText");function pt(t){return Buffer.byteLength(t,"utf8")}o(pt,"byteLength");function Ql(t){return t instanceof Error?t.message:String(t)}o(Ql,"describeError");var ug=/[\t\n\v\f\r\u0085\u2028\u2029]+/gu,pg=/[\p{Cc}\p{Bidi_Control}]/gu,mg=/^(\s*):(?=:)/u,fg=/##(?=[a-z]*\[)/giu;function hg(t){return dg(t).replace(ug," ").replace(pg,"")}o(hg,"toSingleLine");function gg(t){return t.replace(mg,"$1: ").replace(fg,"# #")}o(gg,"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=Zl(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 gg(this.mask(hg(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===Ja||t.status===yr}o(ki,"isItemOver");function Tn(t){return t.status===yr?` NOT STARTED ${t.scenarioName}${_i(t.notStartedReason)}`:t.outcome===Zo?` PASSED ${t.scenarioName}`:t.outcome===ei?` FAILED ${t.scenarioName}${_i(yg(t))}`:` ${t.outcome??"no outcome reported"} ${t.scenarioName}${_i(t.failureReason)}`}o(Tn,"formatItemLine");function _i(t){return t===null||t===""?"":` - ${t}`}o(_i,"detail");function yg(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(yg,"describeFailure");function tc(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(tc,"formatStatusLine");function nc(t){let e={passed:[],failed:[],notStarted:[],other:[]};for(let n of t)n.status===yr?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(nc,"groupItems");function rc(t,e){let n=nc(e),r=t.counts.total;return{result:[wg(t.verdict,r,n.failed.length),`Scenarios: ${sc(n)} (of ${r}).`],details:ic(n),reportUrl:t.webUrl}}o(rc,"formatReport");function oc(t,e,n){let{total:r,finished:i,notStarted:s,running:l,queued:c}=e.counts,a=nc(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: ${sc(a)}.`,...ic(a)];return{result:[t],details:d,reportUrl:e.webUrl}}o(oc,"formatPartialReport");function ic({failed:t,notStarted:e,other:n}){let r=[];return t.length>0&&r.push("","Failed scenarios:",...t.map(Tn)),e.length>0&&r.push("","Did not start:",...e.map(Tn)),n.length>0&&r.push("","Other outcomes:",...n.map(Tn)),r}o(ic,"detailsOf");function sc({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(sc,"tallyOf");function wg(t,e,n){return t===hr?`Result: PASSED - all ${e} scenario(s) passed.`:t===gr?`Result: FAILED - ${n} of ${e} scenario(s) failed.`:t===Ka?"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(wg,"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")}},Yt=class extends Error{static{o(this,"CiReadFailed")}};function ac(t,e,n,r){return cc(t,n,r,i=>t.api.createLaunch(e,i))}o(ac,"createLaunchWithRetry");function lc(t,e){return cc(t,e,bg,n=>t.api.createRunner(n))}o(lc,"createRunnerWithRetry");async function cc(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 Sg(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 Eg(n,a)}if(!dc(a))throw a;let d=uc(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(cc,"callBeforeLaunchWithRetry");async function Sg(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(Sg,"callWithStopGrace");async function xn(t,e,n,r){let{output:i,timings:s}=t,l=null,c=o(a=>{throw new Yt(`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),!dc(d))throw d;let u=Date.now();l===null&&(l=u);let m=uc(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(xn,"readWithRetry");function dc(t){return t instanceof Gt||t instanceof he&&Ri(t)}o(dc,"isTemporaryFailure");function Ri(t){return t.status===429||t.status>=500}o(Ri,"isRepeatableRefusal");function uc(t,e){return t instanceof he&&t.status===429&&t.retryAfterMs!==null?t.retryAfterMs:ge(e)}o(uc,"retryDelayMs");function Eg(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(En(e.status,e.errorCode),{result:n,details:Yl(e),reportUrl:null})}o(Eg,"refuseBeforeLaunch");var pc=[["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."]],vg=new Map([...pc,["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."]]),mc=new Map(pc),fc={noun:"the launch",hints:vg,mayExistAfterLostAnswer:!0},hc={noun:"the launch",hints:mc,mayExistAfterLostAnswer:!0},bg={noun:"the runner of this job",hints:mc,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 Tg="progon-agent-job-",xg=new Set(["ENOENT","ENOTDIR","EACCES","EPERM","EROFS"]),eo=class{static{o(this,"CiJobRunner")}#e;#t;#n;#r=Cg();#i=null;#a=null;#l=!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 lc(this.#e,e);this.#e.output.addSecret(i);let s=new Ut({serverUrl:this.#t,machine:Ke()}),l=await this.#s(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.#s(e,"accept what this runner can run",()=>c.declareCapabilities({signal:e.signal}));let a=Rr({overridePath:this.#n.extensionDistOverride,stateDir:this.#r,agentId:l.agentId});return this.#d(e),this.#c(bi({client:c,stateDir:this.#r,pollWaitSec:l.pollWaitSec,tokenRotation:new qt({client:c,stateDir:this.#r,identitySource:"one_shot"}),extensionDist:a,browserEnv:this.#n,capabilitiesDeclared:!0})),r}async dispose(){this.#l=!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{kg(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 Or({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#s(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=Ig(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?Og(a):U,F([`Progon did not ${n}: ${a.message}`,"No launch was created."],null))}}}#c(e){this.#i=e,this.#a=e.run().then(n=>this.#u(n),n=>this.#p(n))}#u(e){this.#l||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.#l)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 Ig(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(Ig,"gatewayRetryDelayMs");function Og(t){return t instanceof x?En(t.status,t.errorCode):t instanceof T?En(403,"agents.revoked"):U}o(Og,"exitCodeOfGatewayFailure");function Ag(){let t=Rg();try{return _g(gc(t,Tg))}catch(e){let n=e instanceof Error?e.code:void 0;throw e instanceof Error&&n!==void 0&&xg.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(Ag,"createJobStateDir");function Cg(){let t=Ag();return process.env.XDG_CONFIG_HOME=gc(t,"xdg-config"),t}o(Cg,"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(Tn(i)))});this.printed.has(this.firstUnprinted);)this.firstUnprinted+=1;return this.firstUnprinted>r&&e+n.items.length<n.total}};var yc=new AbortController().signal;async function wc(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=Ng(e,r,a,Pg(n));return await Lg(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(wc,"runCiLaunch");function Pg(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(Pg,"timeoutSecOf");function Ng(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(Ng,"createBody");async function Lg(t,e,n,r,i){let{output:s,timings:l}=t,a=await ac(t,e,n,i?hc:fc);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 Dg(t,a,d,i,r);if(a.status===fr){let S=a;if(await xn(t,n.signal,"the scenarios of the launch",I=>d.drain(S,I))===null)continue;return Sc(a,d)}let m=tc(a);r(m),a.waitingForRunner!==null!==u&&(u=a.waitingForRunner!==null,s.line(m));let g=a;if(await xn(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 xn(t,n.signal,"the state of the launch",S=>t.api.getLaunch(g.id,S));E!==null&&(a=E)}}catch(m){if(m instanceof Yt)return Xt(m.message,a,d);throw m}}o(Lg,"driveLaunch");function Sc(t,e){return{exitCode:Ya(t.verdict),final:rc(t,e.items())}}o(Sc,"reportAndExit");async function Dg(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 Ug(t,e,n);if(d instanceof Fe)return Xt(`Could not stop the launch: ${Ae(d)}. No result.`,e,n);throw d}return r?$g(t,a,n,i):Xt("The launch was stopped; no verdict was waited for. No result.",a,n)}o(Dg,"stopLaunchOnce");async function $g(t,e,n,r){let{api:i,output:s,timings:l}=t,c=e;if(c.status!==fr){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!==fr;){await oe(l.pollIntervalMs,yc);let{id:a}=c,d=await xn(t,yc,"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 Yt)return Xt(a.message,c,n);throw a}return Xt("The launch was stopped and has ended. No result.",c,n)}o($g,"awaitStoppedLaunch");async function Ug(t,e,n){try{let r=await t.api.getLaunch(e.id,void 0);return await n.drain(r,void 0),Sc(r,n)}catch(r){if(r instanceof Fe)return Xt(`Could not read the ended launch: ${Ae(r)}. No result.`,e,n);throw r}}o(Ug,"reportEndedLaunch");function Xt(t,e,n){return{exitCode:U,final:oc(t,e,n.items())}}o(Xt,"noResult");var Gg=3e4,Fg={pollIntervalMs:1e4,statusCheckMs:1e4,statusQuietMs:4e4,createBudgetMs:12e4,readBudgetMs:3e5,signalStopTimeoutMs:5e3},Bg=25e3;async function bc(t){Xn();let e=D(process.env,"PROGON_CI_KEY"),n=new zr(e,D(process.env,"GITHUB_STEP_SUMMARY")),r={current:null},i=o(s=>{vc(n,s),Jg(r.current)},"onDefect");process.on("uncaughtException",i),process.on("unhandledRejection",i);try{let s=await jg(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):(vc(n,s),await n.flush(),U)}}o(bc,"runCiCommand");async function jg(t,e,n,r){let i=qa(t);if(i.kind==="help")return Ec(l=>n.line(l)),ti;if(i.kind==="refused")return Ec(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;zn(process.env),er(process.env);let s=i.options.inJob?Wg():null;return Kg(i.options,e,Hg(s),s,n,r)}o(jg,"runParsedCommand");function Wg(){let t=hn();return t.extensionDistOverride!==void 0&&cr(t.extensionDistOverride),t}o(Wg,"loadJobBrowserEnv");function Hg(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(ke(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(Hg,"resolveCiServerUrl");async function Kg(t,e,n,r,i,s){let l=new Qr(t.timeoutMs),c=o(()=>l.cancel(),"onSignal");for(let g of ir)process.on(g,c);let d={api:new wr({serverUrl:n,key:e,requestTimeoutMs:Gg}),output:i,timings:Fg},u={idempotencyKey:Mg(),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 wc(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 ir)process.removeListener(g,c)}}o(Kg,"runWithControls");async function Jg(t){if(t!==null){let e,n=new Promise(r=>{e=setTimeout(r,Bg)});await Promise.race([t.dispose(),n]),clearTimeout(e)}process.exit(U)}o(Jg,"exitAfterDefect");function Ec(t){for(let e of Va.split(`
|
|
111
|
+
`))t(e)}o(Ec,"writeUsage");function vc(t,e){t.final(F([`progon-agent: internal error: ${Vg(e)}`],null),"stderr")}o(vc,"writeDefect");function Vg(t){return t instanceof Error?t.stack??t.message:String(t)}o(Vg,"describeDefect");import{resolve as qg}from"node:path";var _c=` 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>.`,Yg=new Set(["service","status","stop","reset","doctor","update","uninstall"]),Xg=/^\d+\.\d+\.\d+$/;function kc(t){return t==="--version"||Yg.has(t)}o(kc,"isLifecycleVerb");function In(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:qg(n)}}o(In,"readStateDirFlag");var zg=new Set(["enable","disable","start","stop","restart","status"]);function Qg(t){return t!==void 0&&zg.has(t)}o(Qg,"isServiceVerb");function Rc(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(!Qg(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=In(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=In(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(!Xg.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(Rc,"parseLifecycleArgs");function le(t){return{kind:"refusal",reason:t}}o(le,"refusal");import{accessSync as bw,existsSync as _w,constants as kw,statSync as Rw}from"node:fs";import{createHash as yy}from"node:crypto";import{statSync as wy}from"node:fs";import{connect as Fc}from"node:net";import{resolve as Sy}from"node:path";import{z as M}from"zod";import{createHmac as Zg,randomBytes as Ti,timingSafeEqual as ey}from"node:crypto";import{chmodSync as ty,linkSync as ny,readFileSync as ry,statSync as oy,unlinkSync as iy,writeFileSync as sy}from"node:fs";import{join as no}from"node:path";var ft="control.key",ay=32,ly=/^[0-9a-f]{64}$/,cy=16,dy=/^control\.key\.tmp-\d+-[0-9a-f]{8}$/;function Tc(t){return t===ft||dy.test(t)}o(Tc,"isControlKeyEntry");function oo(){return Ti(cy).toString("hex")}o(oo,"newNonce");function xc(t){return typeof t=="object"&&t!==null?t.code:void 0}o(xc,"errnoOf");function io(t){if(process.platform==="win32")return;let e=oy(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 Ic(t){let e=ro(t);if(e!==null)return e;let n=Ti(ay),r=no(t,`${ft}.tmp-${process.pid}-${Ti(4).toString("hex")}`);sy(r,n.toString("hex"),{mode:384,flag:"wx"});try{ty(r,384),ny(r,no(t,ft))}catch(s){if(xc(s)!=="EEXIST")throw s}finally{iy(r)}let i=ro(t);if(i===null)throw new Error(`[control-auth] ${no(t,ft)} vanished after creation`);return i}o(Ic,"ensureControlKey");function ro(t){let e=no(t,ft),n;try{n=ry(e,"utf8")}catch(r){if(xc(r)==="ENOENT")return null;throw r}if(!ly.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 Oc(t,e){return Zg("sha256",t).update(e.join(`
|
|
144
|
+
`)).digest("hex")}o(Oc,"hmac");function so(t,e,n,r){return Oc(t,["progon-agent control request",e,n,r])}o(so,"requestProof");function ao(t,e,n){return Oc(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&&ey(n,r)}o(lo,"proofMatches");import{randomBytes as uy}from"node:crypto";import{readdirSync as Cc,readlinkSync as py,renameSync as my,symlinkSync as fy,unlinkSync as Pc}from"node:fs";import{join as ht}from"node:path";var Nc="control.sock",xi=/^control-\d+-[0-9a-f]{8}\.sock$/,Lc=/^control-\d+-[0-9a-f]{8}\.sock\.next$/,Dc=/^control\.sock\.head-\d+-[0-9a-f]{8}\.tmp$/,hy=/^control-\d+-[0-9a-f]{8}\.sock\.pending$/,gy=w("control-socket-chain");function $c(t){return t===Nc||xi.test(t)||Lc.test(t)||Dc.test(t)||hy.test(t)}o($c,"isControlSocketEntry");function co(t){return ht(t,Nc)}o(co,"controlLinkPath");function Ii(t,e){return ht(t,`${e}.next`)}o(Ii,"successorLinkPath");function Uc(t,e){let n=ht(t,`control.sock.head-${process.pid}-${uy(4).toString("hex")}.tmp`);fy(e,n);try{my(n,co(t))}catch(r){throw Pc(n),r}}o(Uc,"checkpointControlSocket");async function Mc(t,e,n){let r=[];for(let i of Cc(t,{withFileTypes:!0}))i.isSocket()&&xi.test(i.name)&&r.push(i.name);for(let[i,s]of r.entries()){if(!e()){gy.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(Mc,"reapControlSockets");function Gc(t,e){for(let n of Cc(t,{withFileTypes:!0}))if(n.isSymbolicLink())if(Lc.test(n.name)){let r=n.name.slice(0,-5);if(r===e)continue;qe(ht(t,n.name)),qe(ht(t,r))}else Dc.test(n.name)&&qe(ht(t,n.name))}o(Gc,"pruneControlHistory");function qe(t){try{Pc(t)}catch(e){if(typeof e!="object"||e===null||e.code!=="ENOENT")throw e}}o(qe,"unlinkControlEntry");function On(t){let e=Ac(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=Ac(Ii(t,e));if(r===null)return e;e=r}}o(On,"resolveControlSocketName");function Ac(t){try{return py(t)}catch(e){if((typeof e=="object"&&e!==null?e.code:null)==="ENOENT")return null;throw e}}o(Ac,"readLink");var Ye=5e3,Ey=64*1024,Cn=2,Bc=/^[0-9a-f]{32}$/,jc=/^[0-9a-f]{64}$/,vy=M.object({protocol:M.literal(Cn),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()}),by=M.object({protocol:M.literal(Cn),challenge:M.string().regex(Bc)}),Wc=M.object({type:M.enum(["status","stop"]),nonce:M.string().regex(Bc),proof:M.string().regex(jc)}),_y=M.object({proof:M.string().regex(jc),status:vy});function Oi(t){return process.platform==="win32"?{kind:"pipe",name:`\\\\?\\pipe\\progon-agent-${yy("sha256").update(Sy(t).toLowerCase()).digest("hex").slice(0,32)}`}:{kind:"unix",dir:t}}o(Oi,"controlAddress");function Hc(t){return $c(t)||Tc(t)}o(Hc,"isControlChannelEntry");function po(t,e){let n=process.cwd();process.chdir(t);try{return e()}finally{process.chdir(n)}}o(po,"inDir");function An(t){return typeof t=="object"&&t!==null?t.code:void 0}o(An,"errnoOf");async function $(t,e){return Jc(t,"status",e)}o($,"queryOwner");async function Kc(t){return Jc(t,"stop")}o(Kc,"requestOwnerStop");async function Jc(t,e,n){if(!ky(t))return{kind:"none"};io(t);let r=Oi(t),i;try{let s=r.kind==="unix"?n??On(t):r.name;if(s===null)return{kind:"none"};i=r.kind==="unix"?po(r.dir,()=>Fc(s)):Fc(s)}catch(s){if(An(s)==="ENOENT"||An(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,by);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,_y);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>Ey){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=An(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 ky(t){try{return wy(t).isDirectory()}catch(e){if(An(e)==="ENOENT"||An(e)==="ENOTDIR")return!1;throw e}}o(ky,"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 Pn(t){return t.source==="env"?` --state-dir "${t.path}"`:""}o(Pn,"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 Ry}from"node:child_process";import{existsSync as qc,readFileSync as Yc}from"node:fs";import{basename as Ai,dirname as gt,join as Nn}from"node:path";import{fileURLToPath as Ty}from"node:url";var ye="progon-agent";function zt(){let t=we(gt(Ty(import.meta.url))),e=gt(t);if(Ai(t)!==ye||Ai(e)!=="node_modules")return{kind:"not_global",packageRoot:t};let n;if(process.platform==="win32"){if(n=gt(e),!xy(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:Iy(n)}}o(zt,"locateInstallation");function xy(t){try{return Yc(Nn(t,`${ye}.cmd`),"utf8").toLowerCase().includes(`"%dp0%\\node_modules\\${ye}\\dist\\supervisor\\cli.js"`)}catch(e){if(P(e))return!1;throw e}}o(xy,"hasGlobalWindowsShim");function Vc(t){return process.platform==="win32"?Nn(t,"node_modules","npm","bin","npm-cli.js"):Nn(t,"lib","node_modules","npm","bin","npm-cli.js")}o(Vc,"npmCliUnder");function Iy(t){let e=gt(process.execPath),n=process.platform==="win32"?e:gt(e);for(let r of[Vc(n),Vc(t)])if(qc(r))return r;return null}o(Iy,"findNpmCli");async function fo(t,e){return Ln(t,e)}o(fo,"runNpm");async function Ln(t,e){return new Promise((n,r)=>{let i=Ry(process.execPath,[t,...e],{stdio:"inherit",env:process.env});i.once("error",r),i.once("exit",s=>n(s))})}o(Ln,"runNode");function Ci(t){let e=Nn(t,"package.json"),n;try{n=JSON.parse(Yc(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[ye]:void 0;if(typeof i!="string"||typeof l!="string")return{kind:"damaged",reason:`${e} has no version or no '${ye}' bin`};let c=Nn(t,l);return qc(c)?{kind:"installed",version:i,cliPath:c}:{kind:"damaged",reason:`${c} is missing`}}o(Ci,"readInstalledPackage");import{execFile as Oy}from"node:child_process";var Dn=3e4;function X(t,e,n={}){let r=n.timeoutMs??Dn;return new Promise(i=>{Oy(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 _e(t,e,n){try{return n()}catch(r){throw Ay(r)?new _(`Could not ${t} ${e}: ${r.message}`,{cause:r}):r}}o(_e,"registrationFileStep");function Ay(t){if(!(t instanceof Error))return!1;let{code:e,syscall:n}=t;return typeof e=="string"&&typeof n=="string"}o(Ay,"isFileSystemError");import{mkdirSync as Fy,readFileSync as By,readdirSync as jy,renameSync as Wy,unlinkSync as Hy,writeFileSync as Ky}from"node:fs";import{homedir as Jy}from"node:os";import{setTimeout as Vy}from"node:timers/promises";import{join as go}from"node:path";import{z as Ni}from"zod";import{setTimeout as Cy}from"node:timers/promises";var Ce=9e4,Py=250;async function Xc(t,e){let n=await Kc(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 Cy(Py)}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(Xc,"stopStateDirOwner");import{createHash as Ny}from"node:crypto";import{realpathSync as Ly}from"node:fs";import{homedir as Dy}from"node:os";import{dirname as $y,join as zc,resolve as Pi}from"node:path";import{fileURLToPath as Uy}from"node:url";var My=zc("dist","supervisor","cli.js"),ze="service.log",ho="service-error.log";function Qc(t){return ed()?.(t)===!0}o(Qc,"isServiceFileEntry");function Zc(){return ed()!==null}o(Zc,"serviceWritesFiles");function ed(){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(ed,"serviceFileMatcher");var $n="progon-agent";function se(t){return{stateDir:t,name:Qt(t)}}o(se,"serviceTargetFor");function Qt(t){let e=Pi(t);if(Gy(e))return $n;let n=process.platform==="win32"?e.toLowerCase():e;return`${$n}-${Ny("sha256").update(n).digest("hex").slice(0,8)}`}o(Qt,"serviceNameFor");function Gy(t){let e;try{e=Pi(fn(process.platform,process.env,Dy()))}catch(n){if(n instanceof p)return!1;throw n}return process.platform==="win32"?e.toLowerCase()===t.toLowerCase():e===t}o(Gy,"isStandardStateDir");function Zt(){let t=we($y(Uy(import.meta.url))),e=zc(t,My);try{return Ly(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(Zt,"packageCliPath");function td(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:Qt(e),program:[process.execPath,Zt(),"start","--state-dir",e,"--service"],environment:n}}o(td,"buildServiceDefinition");function nd(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(nd,"stateDirOfProgram");var ad="io.progon.agent",qy=/^io\.progon\.agent(-[0-9a-f]{8})?\.plist$/;function yo(t){return`${ad}${t.slice($n.length)}`}o(yo,"labelOf");function Yy(t){return`${$n}${t.slice(ad.length)}`}o(Yy,"nameOfLabel");function Di(){return go(Jy(),"Library","LaunchAgents")}o(Di,"agentsDir");function Un(t){return go(Di(),`${yo(t)}.plist`)}o(Un,"plistPath");function nn(){let t=process.getuid?.();if(t===void 0)throw new Error("[launchd-service] process.getuid is unavailable");return`gui/${t}`}o(nn,"domain");function Qe(t){return`${nn()}/${yo(t)}`}o(Qe,"target");function en(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}o(en,"xml");function rd(t){let e=en(go(t.stateDir,ze)),n=t.program.map(i=>` <string>${en(i)}</string>`).join(`
|
|
149
|
+
`),r=t.environment.map(([i,s])=>` <key>${en(i)}</key>
|
|
150
|
+
<string>${en(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>${en(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>${en(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(rd,"renderPlist");function od(t){return _e("read the LaunchAgent",t,()=>{try{return By(t,"utf8")}catch(e){if(e.code==="ENOENT")return null;throw e}})}o(od,"readFileOrNull");async function tn(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(tn,"isLoaded");var id=1e4,Xy=100;async function Li(t){await ie("launchctl",["bootout",Qe(t)],{timeoutMs:Ce+Dn});let e=Date.now()+id;for(;await tn(t);){if(Date.now()>e)throw new _(`launchd still has ${Qe(t)} loaded ${id/1e3} s after bootout; run the command again.`);await Vy(Xy)}}o(Li,"bootout");async function sd(t){let e=await X("launchctl",["print-disabled",nn()]);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(sd,"isEnabled");var zy=Ni.object({ProgramArguments:Ni.array(Ni.string())});async function Qy(t){let e=await X("plutil",["-convert","json","-o","-",t]);if(e.exitCode!==0)return null;try{let n=zy.safeParse(JSON.parse(e.stdout));return n.success?n.data.ProgramArguments:null}catch{return null}}o(Qy,"readProgram");var ld={description:"a LaunchAgent (launchd) \u2014 starts when you log in",async isCurrent(t){return od(Un(t.name))===rd(t)&&await tn(t.name)&&await sd(t.name)===!0},async install(t){let e=Un(t.name);return await tn(t.name)&&await Li(t.name),_e("write the LaunchAgent",e,()=>{Fy(Di(),{recursive:!0});let n=`${e}.tmp-${process.pid}`;Ky(n,rd(t),{mode:384}),Wy(n,e)}),await ie("launchctl",["enable",Qe(t.name)]),await ie("launchctl",["bootstrap",nn(),e]),[]},async start(t){await tn(t)?await ie("launchctl",["kickstart",Qe(t)]):(await ie("launchctl",["enable",Qe(t)]),await ie("launchctl",["bootstrap",nn(),Un(t)]))},async stop(t){await tn(t)&&await Li(t)},async remove(t){let e=Un(t),n=await tn(t);return n&&await Li(t),_e("delete the LaunchAgent",e,()=>{try{return Hy(e),!0}catch(i){if(i.code!=="ENOENT")throw i;return!1}})||n?"removed":"absent"},async read(t){let e=Un(t);if(od(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 ${nn()}`+(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 ${nn()}`));return{kind:"registered",location:e,program:await Qy(e),facts:n,active:r,autostart:o(()=>sd(t),"autostart")}},async registeredNames(){let t;try{t=jy(Di())}catch(e){if(e.code==="ENOENT")return[];throw e}return t.filter(e=>qy.test(e)).map(e=>Yy(e.slice(0,-6)))},logHint(t){return go(t.stateDir,ze)}};import{mkdirSync as Zy,readdirSync as ew,readFileSync as tw,renameSync as nw,unlinkSync as rw,writeFileSync as ow}from"node:fs";import{homedir as iw,userInfo as cd}from"node:os";import{isAbsolute as sw,join as $i}from"node:path";import{z as dd}from"zod";var aw=/^progon-agent(-[0-9a-f]{8})?\.service$/,Ui="# progon-agent program: ";function Mi(){let t=process.env.XDG_CONFIG_HOME,e=t!==void 0&&sw(t)?t:$i(iw(),".config");return $i(e,"systemd","user")}o(Mi,"unitDir");function Pe(t){return`${t}.service`}o(Pe,"unitName");function Mn(t){return $i(Mi(),Pe(t))}o(Mn,"unitPath");function ud(t,e){let n=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%");return e&&(n=n.replace(/\$/g,"$$$$")),`"${n}"`}o(ud,"quote");function pd(t){let e=t.program.map(r=>ud(r,!0)).join(" "),n=t.environment.map(([r,i])=>`Environment=${ud(`${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(pd,"renderUnit");function wo(t){return _e("read the systemd unit",t,()=>{try{return tw(t,"utf8")}catch(e){if(e.code==="ENOENT")return null;throw e}})}o(wo,"readFileOrNull");var lw=dd.array(dd.string());function cw(t){let e=t.split(`
|
|
204
|
+
`,1)[0];if(e===void 0||!e.startsWith(Ui))return null;try{let n=lw.safeParse(JSON.parse(e.slice(Ui.length)));return n.success?n.data:null}catch{return null}}o(cw,"programOf");async function rn(t,e=!1){await ie("systemctl",["--user",...t],e?{timeoutMs:Ce+Dn}:{})}o(rn,"systemctl");async function dw(t){return(await X("systemctl",["--user","is-enabled",Pe(t)])).exitCode===0}o(dw,"isEnabled");var md={description:"a systemd user service \u2014 starts at boot (with lingering) or at login",async isCurrent(t){return wo(Mn(t.name))===pd(t)&&await dw(t.name)},async install(t){let e=[],n=Mn(t.name);_e("write the systemd unit",n,()=>{Zy(Mi(),{recursive:!0});let i=`${n}.tmp-${process.pid}`;ow(i,pd(t),{mode:384}),nw(i,n)}),await rn(["daemon-reload"]),await rn(["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 ${cd().username}`),e},async start(t){await rn(["start",Pe(t)])},async stop(t){wo(Mn(t))!==null&&await rn(["stop",Pe(t)],!0)},async remove(t){let e=Mn(t);return wo(e)===null?"absent":(await rn(["disable","--now",Pe(t)],!0),_e("delete the systemd unit",e,()=>rw(e)),await rn(["daemon-reload"]),await X("systemctl",["--user","reset-failed",Pe(t)]),"removed")},async read(t){let e=Mn(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",cd().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:cw(n),facts:r,active:i,autostart:o(()=>Promise.resolve(s),"autostart")}},async registeredNames(){let t;try{t=ew(Mi())}catch(e){if(e.code==="ENOENT")return[];throw e}return t.filter(e=>aw.test(e)).map(e=>e.slice(0,-8))},logHint(t){return`journalctl --user -u ${Pe(t.name)}`}};import{randomBytes as uw}from"node:crypto";import{unlinkSync as pw,writeFileSync as mw}from"node:fs";import{join as Gn}from"node:path";import{z as K}from"zod";var fw="^progon-agent(-[0-9a-f]{8})?$",Bi="progon-agent program: ";function hw(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(hw,"quoteWindowsArg");function gw(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(hw).join(" "))} -WorkingDirectory ${me(t.stateDir)} -NoNewWindow -Wait -PassThru -RedirectStandardOutput ${me(Gn(t.stateDir,ze))} -RedirectStandardError ${me(Gn(t.stateDir,ho))}`,"exit $p.ExitCode"].join(`
|
|
206
|
+
`)}o(gw,"renderWrapperScript");function fd(t){return`-NoProfile -NonInteractive -WindowStyle Hidden -EncodedCommand ${un(gw(t))}`}o(fd,"actionArguments");function hd(t){return`${Bi}${JSON.stringify(t.program)}`}o(hd,"description");function Gi(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}o(Gi,"xml");function yw(){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(yw,"currentUserId");function ww(t){let e=Gi(yw());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(hd(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(fd(t))}</Arguments>
|
|
251
|
+
</Exec>
|
|
252
|
+
</Actions>
|
|
253
|
+
</Task>
|
|
254
|
+
`}o(ww,"renderTaskXml");async function ji(t,e){let n=["-NoProfile","-NonInteractive","-EncodedCommand",un(`[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 Sw=K.union([K.object({registered:K.literal(!1)}),K.object({registered:K.literal(!0),description:K.string().nullable(),arguments:K.string().nullable(),state:K.string(),lastResult:K.number().nullable(),lastRun:K.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`,Sw)}o(Fi,"readTask");var Ew=K.array(K.string());function vw(t){if(t===null||!t.startsWith(Bi))return null;try{let e=Ew.safeParse(JSON.parse(t.slice(Bi.length)));return e.success?e.data:null}catch{return null}}o(vw,"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===hd(t)&&e.arguments===fd(t)},async install(t){xt(t.stateDir);let e=Gn(t.stateDir,`${t.name}.task-${uw(8).toString("hex")}.xml`);_e("write the task definition",e,()=>mw(e,`\uFEFF${ww(t)}`,{encoding:"utf16le",mode:384,flag:"wx"}));try{await ie("schtasks",["/Create","/TN",t.name,"/XML",e,"/F"])}finally{pw(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'`,K.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:vw(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 '${fw}' } | ForEach-Object { $_.TaskName })`,K.array(K.string()))},logHint(t){return`${Gn(t.stateDir,ze)} and ${Gn(t.stateDir,ho)}`}};function ce(){switch(process.platform){case"darwin":return ld;case"linux":return md;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(Qt(t))}o(vo,"readServiceOf");async function bo(){let t=ce(),e=Zt(),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:nd(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(Zc()&&(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 Tw={ok:"[ok] ",warn:"[warn]",fail:"[FAIL]",info:"[info]"};function de(t){return t instanceof Error?t.message:String(t)}o(de,"describe");async function gd(){let t=0,e=o((l,c,a)=>{l==="fail"&&(t+=1),h(`${Tw[l]} ${c}: ${a}`)},"report");e("info","progon-agent",`${te()} on Node ${process.version} (${process.execPath})`),xw(e);let n=G().path;Iw(n,e),await Ow(n,e);let r=t,i=Cw(e);t===r?Nw(e):e("info","Start","not checked \u2014 'progon-agent start' refuses the settings above");let s=await Lw(e);return await Dw(s,i,e),await Aw(n,e),h(t===0?"No problems found.":`${t} check(s) failed \u2014 see [FAIL] above.`),t===0?0:1}o(gd,"runDoctorCommand");function xw(t){let e=zt();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(xw,"checkInstallation");function Iw(t,e){try{Rw(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{bw(t,kw.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(Iw,"checkStateDir");async function Ow(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(Ow,"checkAgentProcess");async function Aw(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=>!_w(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!==Zt()){e("warn","Autostart",`${r}: it starts ${s} ${l}, not this node and installation (${process.execPath} ${Zt()}). Refresh it: progon-agent service enable --state-dir "${t}"`);return}e("ok","Autostart",r)}o(Aw,"checkService");function Cw(t){try{let e=dn(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))}Pw(t);try{let e=hn();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(Cw,"checkConfiguration");function Pw(t){let e=[],n=!1;try{let r=Zn(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(Pw,"checkCertificates");function Nw(t){try{let e=Me(),n=yi(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(Nw,"checkStart");async function Lw(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(Lw,"checkChromium");async function Dw(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 Ir(),n("ok","Browser sandbox","Chromium starts with its sandbox")}catch(r){if(!(r instanceof p))throw r;n("fail","Browser sandbox",de(r))}}o(Dw,"checkSandbox");async function yd(){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: ${Mw(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 Uw(t.path)}`),h(`Autostart: ${await $w(t.path)}`),0}o(yd,"runStatusCommand");async function $w(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($w,"describeAutostart");async function Uw(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(Uw,"describeAgentProcess");function Mw(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(Mw,"describeEnrollment");import{setTimeout as Ww}from"node:timers/promises";import{setTimeout as Gw}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 Xc(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 Gw(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 Fw}from"node:readline/promises";var Bw=new Set(["y","yes","\u0434","\u0434\u0430"]),jw=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=Fw({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(Bw.has(l))return"yes";if(jw.has(l))return"no";h("Answer 'y' or 'n'.")}}finally{n.close()}}o(ko,"askYesNo");var wd=2e4,Hw=250;async function Sd(t){let e=G().path;switch(t){case"enable":return await Hi(e),0;case"disable":return await vd(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 Vw(e),0}}o(Sd,"runServiceCommand");function Ed(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(Ed,"announceHandOver");function Kw(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(Kw,"assertEnrolled");async function Hi(t){Kw(t);let e=ce(),n=td(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,Ed));let s=r?[]:await e.install(n);r||h(`Registered ${n.name} as ${e.description}.`),Jw(n),await e.start(n.name),await bd(n);for(let l of s)h(l)}o(Hi,"enableService");async function vd(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(vd,"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,Ed)),await e.start(r),await bd(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 bd(t){let e=Date.now()+wd;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 Ww(Hw)}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 ${wd/1e3} s.${i} Its log says why: ${n.logHint(t)}`)}o(bd,"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 Vw(t){let e=ce(),n=Qt(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(Vw,"printServiceStatus");async function _d(t){let e=G(),n=t==="ask"?await qw():t;if(n==="keep")return h(`Autostart was not changed (no terminal to ask, no answer). Turn it on with: progon-agent service enable${Pn(e)}`),0;try{return n==="on"?await Hi(e.path):await vd(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"}${Pn(e)}`),!i)throw r;return 1}}o(_d,"applyAutostartAfterEnroll");async function qw(){let t=await ko("Start the runner automatically in the background?","yes");return t==="yes"?"on":t==="no"?"off":"keep"}o(qw,"askAutostart");import{readdirSync as Td,rmdirSync as Yw,rmSync as Ki}from"node:fs";import{basename as kd,join as Rd}from"node:path";function Le(t){return t instanceof Error?t.message:String(t)}o(Le,"describe");function xd(t){let e=[],n;try{n=Td(t,{withFileTypes:!0})}catch(a){return P(a)?e:[{path:t,reason:Le(a)}]}let r=new Set([kd(nt(t)),kd(pn(t))]),i=n.some(a=>r.has(a.name)&&!a.isDirectory()),s=n.some(a=>a.name===ft&&a.isFile()),l=Rd(t,Sr),c=null;try{c=vr(t);let a=i||s||c!==null,d=c===null?[]:c.profiles,u=Xw(t,n,e,a,d);(u.length>0||c===null&&a)&&(c={...c??Er,profiles:[...d,...u]},br(t,c))}catch(a){e.push({path:l,reason:Le(a)}),c=null}if(i)try{nr(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{Ki(u,{recursive:!0,force:!0})}catch(m){e.push({path:u,reason:Le(m)})}}try{Ji(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||Hc(a.name)||c.serviceFiles&&Qc(a.name))))continue;let m=Rd(t,a.name);if(!(a.isDirectory()&&!d))try{Ki(m,{recursive:a.isDirectory(),force:!0})}catch(g){e.push({path:m,reason:Le(g)})}}if(c!==null&&e.length===0)try{Ki(l)}catch(a){e.push({path:l,reason:Le(a)})}return e}o(xd,"removeRunnerFiles");function Xw(t,e,n,r,i){if(!e.some(c=>c.name===sr&&c.isDirectory()))return[];let s=new ut(t),l=[];try{for(let c of Td(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(Xw,"findInstanceProfiles");function Ji(t){try{return Yw(t),"removed"}catch(e){if(P(e))return"absent";let n=e.code;if(n==="ENOTEMPTY"||n==="EEXIST")return"not_empty";throw e}}o(Ji,"removeDirectoryIfEmpty");async function on(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 zw(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=Qw(n),a=xd(n),d=c.kind==="read"?await Zw(c.identity):{kind:"not_attempted"};return{kind:"done",stateDir:n,stop:i,service:l,identity:c,cleanupFailures:a,remote:d}}o(on,"resetStateDir");async function zw(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(zw,"removeServiceRegistration");function Qw(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(Qw,"readIdentity");async function Zw(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(Zw,"revokeRegistration");function wt(t){h(`Stopping progon-agent (${j(t)})\u2026`)}o(wt,"announceStop");async function Id(){let t=G().path;return await To(t),0}o(Id,"runStopCommand");async function Od(){let t=await on(se(G().path),wt);return Vi(t)?0:1}o(Od,"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 eS}from"node:fs";import{homedir as tS}from"node:os";import{resolve as nS}from"node:path";async function Ad(t){let e=[],n=await rS(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 on(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=Ji(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 oS(e),e.length===0?await iS(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(Ad,"runUninstallCommand");async function rS(t,e){let n=[],r=o(s=>{let l=nS(s);n.some(c=>c.stateDir===l)||n.push(se(l))},"add");try{r(fn(process.platform,process.env,tS()))}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(rS,"collectTargets");async function oS(t){let e;try{e=Ho().cliPath}catch(r){if(!(r instanceof Q))throw r;t.push(`Chromium \u2014 ${r.message}`);return}if(!eS(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 Ln(e,["uninstall"]);n!==0&&t.push(`Chromium \u2014 Playwright's uninstall exited ${n===null?"by signal":String(n)}`)}o(oS,"removeChromium");async function iS(t){let e=zt();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 ${ye}`);return}h(`Removing the package from ${e.prefix}\u2026`);let n=await fo(e.npmCli,["uninstall","--global","--prefix",e.prefix,ye]);n!==0&&t.push(`the package \u2014 npm exited ${n===null?"by signal":String(n)}; run: npm uninstall -g ${ye}`)}o(iS,"removePackage");async function Cd(t){let e=zt();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=`${ye}@${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 aS(r.path),l=!1,c;try{c=await sS(e.npmCli,e.prefix,e.packageRoot,n)}finally{Ci(e.packageRoot).kind==="installed"?l=await Pd(s):lS(s),i&&h(`Start the agent again: progon-agent start${r.source==="env"?` --state-dir "${r.path}"`:""}`)}return c===0&&l?0:1}o(Cd,"runUpdateCommand");async function sS(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 Ln(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(sS,"installUpdate");async function aS(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 Pd(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(aS,"stopRunningAgents");async function Pd(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(Pd,"restartServices");function lS(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(lS,"reportServicesLeftStopped");async function Nd(t){if(t.command==="version")return process.stdout.write(`${te()}
|
|
263
|
+
`),0;switch(Xn(),t.command!=="uninstall"&&t.stateDir!==void 0&&(process.env.PROGON_RUNNER_STATE_DIR=t.stateDir),t.command){case"status":return yd();case"stop":return Id();case"reset":return Od();case"doctor":return gd();case"update":return Cd(t.version);case"uninstall":return Ad(t.stateDirs);case"service":return Sd(t.verb)}}o(Nd,"runLifecycleCommand");import{randomBytes as dS}from"node:crypto";import{linkSync as uS,symlinkSync as pS}from"node:fs";import{createServer as mS}from"node:net";import{join as jn,resolve as fS}from"node:path";var Fn=w("state-dir-owner"),cS=4*1024,xo=class{static{o(this,"OwnerState")}#e;#t;#n;#r=new Date().toISOString();#i="starting";#a=o(()=>null,"#readActiveRun");#l;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(),Fn.info("State directory released",{stateDir:r}))},"release");return process.on("exit",i),Fn.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.#l=s},"setStopHandler"),release:i}}serve(e){e.setEncoding("utf8");let n=oo(),r="";e.on("error",i=>{Fn.debug("Control channel connection failed",{err:i.message})}),e.write(`${JSON.stringify({protocol:Cn,challenge:n})}
|
|
264
|
+
`),e.on("data",i=>{r+=i;let s=r.indexOf(`
|
|
265
|
+
`);if(s===-1){r.length>cS&&e.destroy();return}let l=uo(r.slice(0,s),Wc);if(!l.ok||!lo(so(this.#t,n,l.value.nonce,l.value.type),l.value.proof)){Fn.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.#s()})}
|
|
266
|
+
`),c==="stop"&&this.#o()})}#o(){Fn.info("Stop requested over the control channel",{stateDir:this.#e}),this.#l()}#s(){return{protocol:Cn,pid:process.pid,version:te(),startedAt:this.#r,stateDir:this.#e,phase:this.#i,activeRunId:this.#a(),service:this.#n}}};var Wn=5;async function Dd(t,e){let n=fS(t);xt(n),io(n);let r=Ic(n),i=new xo(n,r,e.service),s=mS(g=>i.serve(g)),l=Oi(n);if(l.kind==="pipe"){for(let g=0;g<Wn;g+=1){if(await Ld(s,()=>s.listen(l.name))==="bound")return{kind:"acquired",ownership:i.own(()=>Bn(s,n,null))};let S=await $(n);if(S.kind!=="none")return{kind:"held",answer:S}}throw Io(n)}let c=performance.now()+Wn*Ye;await Mc(n,()=>performance.now()+2*Ye<c,async g=>(await $(n,g)).kind==="none");let a=`control-${process.pid}-${dS(4).toString("hex")}.sock`,d=`${a}.pending`;if(await Ld(s,()=>po(n,()=>s.listen(d)))!=="bound")throw new Error(`[state-dir-owner] Cannot bind the control socket ${jn(n,a)}: the name is already in use.`);let m=!1;try{uS(jn(n,d),jn(n,a)),m=!0,qe(jn(n,d));for(let g=0;g<Wn;g+=1){let E=On(n);if(E!==null){if(performance.now()+Ye>c)throw Io(n);let b=await $(n,E);if(b.kind!=="none")return Bn(s,n,a),{kind:"held",answer:b}}if(performance.now()>c)throw Io(n);let S=E===null?co(n):Ii(n,E);try{pS(a,S)}catch(b){if($d(b)!=="EEXIST")throw b;continue}if(On(n)!==a){E!==null&&qe(S);continue}return E!==null&&Uc(n,a),Gc(n,a),{kind:"acquired",ownership:i.own(()=>Bn(s,n,a))}}}catch(g){throw Bn(s,n,m?a:d),g}throw Bn(s,n,a),Io(n)}o(Dd,"acquireStateDirOwnership");async function Ld(t,e){return new Promise((n,r)=>{let i=o(l=>{t.off("listening",s),$d(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(Ld,"listen");function Bn(t,e,n){if(n===null){t.close();return}qe(jn(e,n)),po(e,()=>t.close())}o(Bn,"closeOwnSocket");function Io(t){return new Error(`[state-dir-owner] Could not take ownership of ${t} within ${Wn} claim rounds and their ${Wn*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 $d(t){return typeof t=="object"&&t!==null?t.code:void 0}o($d,"errnoOf");var Hn=w("daemon");async function Md(t){ca(),Hn.info("progon-agent starting");let e=G().path,n=await Dd(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"?Hn.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}):Hn.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=ql(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],`${Ud(u)} \u2014 and the teardown after it failed too, so the browser may still be running: ${Ud(m)}`)}),u}let d=Hl[a];return d.level==="error"?Hn.error(d.message):Hn.info(d.message),d.exitCode}finally{r.release()}}o(Md,"runDaemon");function Ud(t){return t instanceof Error?t.message:String(t)}o(Ud,"describe");import{createHash as kS,randomBytes as RS}from"node:crypto";import{z as W}from"zod";var Gd=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()}),Fd=W.object({status:W.literal("authorization_pending"),expiresAt:W.iso.datetime({offset:!0}),pollIntervalSec:W.number().int().positive()}),hS=W.object({companyName:W.string(),approvedByEmail:W.string(),approvedAt:W.string()}),Bd=W.object({credential:Vn,approval:hS});var jd=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",Gd.safeParse(n));return jd.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",Bd.safeParse(n));return jd.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",Fd.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 on(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=Pn(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 gS}from"node:child_process";var Kn=w("browser-open");function Ao(t){return t!==void 0&&t!==""}o(Ao,"isSet");function yS(t,e){return!(Ao(t.SSH_CONNECTION)||Ao(t.SSH_TTY)||e==="linux"&&!Ao(t.DISPLAY)&&!Ao(t.WAYLAND_DISPLAY))}o(yS,"shouldAttemptBrowserOpen");var wS=/[&|^<>"'` ]/;function SS(t){let e;try{e=new URL(t)}catch{return!1}return e.protocol!=="http:"&&e.protocol!=="https:"||t!==e.href?!1:!wS.test(t)}o(SS,"isSpawnSafeUrl");function ES(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(ES,"browserOpenCommand");function Wd(t,e,n){if(!yS(e,n)){Kn.debug("Not opening a browser: this host has no desktop to open one on",{platform:n});return}if(!SS(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=ES(t,n);if(r===null){Kn.debug("Not opening a browser: no opener is defined for this platform",{platform:n});return}try{let i=gS(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(Wd,"openVerificationUrl");var vS=30,bS=5;function Hd(t){return{intervalSec:t.pollIntervalSec,deadlineMs:t.timeoutSec===null?t.expiresAtMs:Math.min(t.expiresAtMs,t.nowMs+t.timeoutSec*1e3)}}o(Hd,"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+bS,i=e.retryAfterSec!==null&&e.retryAfterSec>r?e.retryAfterSec:r,s=Math.min(i,vS);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 Kd(t,e){return e>=t.deadlineMs}o(Kd,"isDeadlinePassed");function Jd(t,e,n){return Math.max(0,Math.min(e,t.deadlineMs-n))}o(Jd,"clampDelayToDeadline");async function Vd(t,e){try{return await e()}catch(n){let r=_S(n,t);throw r!==null?r:n}}o(Vd,"explainingEnrollRefusals");function _S(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(_S,"explainEnrollRefusal");var sn=w("device-enrollment"),TS=24,xS=2e3,zi=0,St=1,Yd=130,IS="This machine is already enrolled. Start the daemon with: progon-agent start",OS="Enrollment was denied in the browser. Nothing was created on this machine.",AS="Cancelled. Nothing was saved on this machine.",CS="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 qd(t){return`Enrollment request expired. Run: progon-agent enroll --server ${t}`}o(qd,"expiredLine");function PS(t,e){return`Timed out after ${t}s waiting for approval. The request is still open \u2014 approve at: ${e}`}o(PS,"timedOutLine");function NS(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(NS,"alreadyCompletedLine");function LS(t){return`Enrollment request is no longer valid. Run: progon-agent enroll --server ${t}`}o(LS,"noLongerValidLine");async function Xd(t){let e=t.env??process.env;t.serverUrl!==void 0&&(process.env.PROGON_SERVER_URL=t.serverUrl);let n=Me(),r=Ke(),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(`${IS}
|
|
270
|
+
`),zi;if(await Xi(n,{text:`progon-agent enroll --server ${n.serverUrl}`,withCode:!1})==="stopped")return St;let c=RS(TS).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(GS(c));return US(d),t.openBrowser&&Wd(d.verificationUrl,e,process.platform),DS({client:a,config:n,created:d,deviceSecret:c,timeoutSec:t.timeoutSec,rng:t.rng})}o(Xd,"runDeviceEnrollment");async function DS(t){let{client:e,config:n,created:r,deviceSecret:i,timeoutSec:s,rng:l}=t,c=Date.parse(r.expiresAt),a=Hd({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(`${CS}
|
|
271
|
+
`),process.exit(Yd)),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 $S(e,i,m.signal);if(Kd(a,Date.now()))return s!==null&&a.deadlineMs<c?process.stdout.write(`${PS(s,r.verificationUrl)}
|
|
272
|
+
`):process.stdout.write(`${qd(n.serverUrl)}
|
|
273
|
+
`),St;let S;try{S=await e.poll(i)}catch(I){if(I instanceof Nt)return process.stdout.write(`${OS}
|
|
274
|
+
`),St;if(I instanceof Lt)return process.stdout.write(`${qd(n.serverUrl)}
|
|
275
|
+
`),St;if(I instanceof Dt)return sn.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(`${NS(n.serverUrl)}
|
|
276
|
+
`),St;if(I instanceof $t)return sn.warn("The server no longer recognises this enrollment request",{requestId:r.requestId,errorCode:I.errorCode,status:I.status}),process.stdout.write(`${LS(n.serverUrl)}
|
|
277
|
+
`),St;if(I instanceof Pt){let N=Co(a,{kind:"slow_down",retryAfterSec:I.retryAfterSec});a=N.state,d=N.delayMs,sn.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,sn.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(DS,"waitForApproval");async function $S(t,e,n){try{await Je({operation:"device enrollment cancel",timeoutMs:xS,work:o(()=>t.cancel(e),"work")})}catch(r){sn.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(`${AS}
|
|
279
|
+
`),Yd}o($S,"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 Vd(e.serverUrl,()=>Fr({config:e,machine:n,fetchImpl:r,rng:i}));return Nl(s,e),sn.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 US(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 ${MS(t.expiresAt)})...
|
|
283
|
+
`)}o(US,"printRequestOpened");function MS(t){let e=Date.parse(t)-Date.now();return`${Math.ceil(e/6e4)}m`}o(MS,"describeExpiry");function GS(t){return kS("sha256").update(t,"utf8").digest("hex")}o(GS,"sha256Hex");var zd=`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
|
|
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
|
+
${_c}
|
|
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
|
|
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
|
|
100
|
-
failing when the deadline passed
|
|
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
|
-
|
|
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 nu(t){let[e,...n]=t;if(e===void 0||e==="--help"||e==="-h"||e==="help")return{kind:"usage",reason:null};if(e==="start")return jS(n);if(kc(e)){let r=Rc(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"?HS(n):e==="ci"?{kind:"ci",args:n}:{kind:"usage",reason:`unknown command '${e}'`}}o(nu,"parseCliArgs");function jS(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=In(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(jS,"parseStart");function ru(t,e,n){return t[e]!=="--state-dir"?null:n!==void 0?{reason:"'--state-dir' is given twice"}:In(t,e)}o(ru,"readEnrollStateDir");function ou(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(ou,"readAutostartFlag");function WS(t){return t.startsWith("-")&&t.length<32}o(WS,"isOptionInCodeSlot");function HS(t){let[e,...n]=t;if(e===void 0||WS(e))return KS(t);let r,i="ask",s;for(let l=0;l<n.length;l+=1){let c=n[l],a=ou(c,i);if(a!==null){if("reason"in a)return{kind:"usage",reason:a.reason};i=a.choice;continue}let d=ru(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(HS,"parseEnroll");var Qd=1,Zd=3600;function KS(t){let e,n=!0,r=null,i="ask",s;for(let l=0;l<t.length;l+=1){let c=t[l],a=ou(c,i);if(a!==null){if("reason"in a)return{kind:"usage",reason:a.reason};i=a.choice;continue}let d=ru(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<Qd||m>Zd)return{kind:"usage",reason:`'--timeout' must be between ${Qd} and ${Zd} 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(KS,"parseEnrollDevice");function Zi(t){t!==void 0&&(process.env.PROGON_RUNNER_STATE_DIR=t)}o(Zi,"useStateDir");async function JS(t){let e=nu(t);switch(e.kind){case"usage":return e.reason===null?(process.stdout.write(`${zd}
|
|
117
382
|
`),0):(process.stderr.write(`progon-agent: ${e.reason}
|
|
118
383
|
|
|
119
|
-
${
|
|
120
|
-
`),2);case"enroll":return
|
|
121
|
-
`;let
|
|
122
|
-
`}
|
|
384
|
+
${zd}
|
|
385
|
+
`),2);case"enroll":return Zi(e.stateDir),eu(await qS(e.code,e.serverUrl),e.autostart);case"enroll-device":return Zi(e.stateDir),eu(await Xd({serverUrl:e.serverUrl,openBrowser:e.openBrowser,timeoutSec:e.timeoutSec}),e.autostart);case"install-browser":return VS();case"ci":return bc(e.args);case"lifecycle":return Nd(e.invocation);case"start":{Zi(e.stateDir);let n=await Md({service:e.service});return n!==null&&e.service?vi(n,process.platform):n}}}o(JS,"runAgentCli");async function eu(t,e){return t!==0?t:_d(e)}o(eu,"afterEnrollment");async function VS(){return await kt({stdio:"terminal"}),0}o(VS,"installBrowser");async function qS(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:Ke(),retryCommand:`progon-agent enroll <code> --server ${n.serverUrl}`})}o(qS,"enrollThisMachine");function YS(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(YS,"formatCliFailure");function XS(t){JS(t).then(e=>{e!==null&&process.exit(e)}).catch(e=>{let n=nu(t);process.stderr.write(YS(e,n)),process.exit(zS(e,n))})}o(XS,"runAgentCliProcess");function zS(t,e){return e.kind==="start"&&(t instanceof p||t instanceof ee)?e.service?vi(78,process.platform):78:1}o(zS,"failureExitCode");var tu=process.argv[1];tu!==void 0&&import.meta.url===BS(FS(tu)).href&&XS(process.argv.slice(2));export{YS as formatCliFailure,nu as parseCliArgs,JS as runAgentCli,XS as runAgentCliProcess};
|