progon-agent 1.3.2 → 1.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/supervisor/cli.js +44 -44
- package/extension-bundle.json +3 -3
- package/extension-dist/background/background.js +88 -89
- package/extension-dist/card/card.css +1 -1
- package/extension-dist/card/card.html +9 -9
- package/extension-dist/card/card.js +3 -9
- package/extension-dist/chunks/shared-B5dGSIVr.js +1 -0
- package/extension-dist/chunks/shared-BAuQl9-k.js +323 -0
- package/extension-dist/chunks/shared-BBv6J4oP.js +199 -0
- package/extension-dist/chunks/shared-BQbdfGz-.css +1 -0
- package/extension-dist/chunks/shared-BROt3HHj.js +1 -0
- package/extension-dist/chunks/shared-Beih6ywL.js +1 -0
- package/extension-dist/chunks/shared-C05lJ8nQ.js +98 -0
- package/extension-dist/chunks/shared-C0apd10a.js +21 -0
- package/extension-dist/chunks/shared-C5qHe-zg.js +239 -0
- package/extension-dist/chunks/shared-CFv6cSrr.js +1 -0
- package/extension-dist/chunks/shared-CNYvsh0O.js +39 -0
- package/extension-dist/chunks/shared-CUdYAeXx.js +134 -0
- package/extension-dist/chunks/shared-CdFf-X4Y.css +1 -0
- package/extension-dist/chunks/shared-CgUMEof2.js +1 -0
- package/extension-dist/chunks/shared-CmGrLhdH.js +1 -0
- package/extension-dist/chunks/shared-DDyAbNyB.js +1 -0
- package/extension-dist/chunks/shared-Dbbjj01C.js +1 -0
- package/extension-dist/chunks/shared-Dk6zuyaK.css +1 -0
- package/extension-dist/chunks/shared-pdVr5lDK.js +1 -0
- package/extension-dist/content/content.css +1 -1
- package/extension-dist/content/content.js +216 -231
- package/extension-dist/manifest.json +32 -31
- package/extension-dist/offscreen/offscreen.html +2 -3
- package/extension-dist/offscreen/offscreen.js +1 -1
- package/extension-dist/popup/popup.html +8 -8
- package/extension-dist/popup/popup.js +3 -3
- package/extension-dist/sidepanel/sidepanel.html +11 -10
- package/extension-dist/sidepanel/sidepanel.js +1 -1
- package/extension-dist/workspace/workspace.css +1 -1
- package/extension-dist/workspace/workspace.html +12 -11
- package/extension-dist/workspace/workspace.js +47 -74
- package/package.json +2 -2
- package/extension-dist/chunks/shared-9kMbf8PO.js +0 -1
- package/extension-dist/chunks/shared-BEB011Tg.js +0 -1
- package/extension-dist/chunks/shared-BWYPh-Al.js +0 -1
- package/extension-dist/chunks/shared-Bi_ASAsl.js +0 -377
- package/extension-dist/chunks/shared-BjgSKbjc.js +0 -1
- package/extension-dist/chunks/shared-Bts1WtwM.js +0 -1
- package/extension-dist/chunks/shared-BvwA-cm2.css +0 -1
- package/extension-dist/chunks/shared-Bwk7ZjOr.js +0 -21
- package/extension-dist/chunks/shared-CInXPYm9.js +0 -1
- package/extension-dist/chunks/shared-COCbj3mN.js +0 -1
- package/extension-dist/chunks/shared-CX8XGwZc.js +0 -1
- package/extension-dist/chunks/shared-CZrS2BT6.js +0 -111
- package/extension-dist/chunks/shared-C_dmgeUK.js +0 -120
- package/extension-dist/chunks/shared-CeuPJn47.js +0 -227
- package/extension-dist/chunks/shared-CiEEQWpw.js +0 -1
- package/extension-dist/chunks/shared-Cxo909tK.js +0 -1
- package/extension-dist/chunks/shared-DyRhAmgo.js +0 -51
- package/extension-dist/chunks/shared-Xq2emDMe.js +0 -98
- package/extension-dist/chunks/shared-_jlBqdBD.css +0 -1
package/dist/supervisor/cli.js
CHANGED
|
@@ -1,54 +1,54 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Ko=Object.defineProperty;var i=(t,e)=>Ko(t,"name",{value:e,configurable:!0});import{realpathSync as Zl}from"node:fs";import{pathToFileURL as Ql}from"node:url";import{z as pn}from"zod";var Jo=/^[a-z_]{1,32}@\d{1,3}$/,hn=pn.array(pn.string().regex(Jo)).min(1).max(32),fn=["playback@1"],gn="make_auto@2",wn="atlas_crawl@2",yn="atlas_crawl@1",_n="swarm@1",En="swarm@2";import{z as h}from"zod";var ae=/^pgat_[0-9A-Za-z]{43}$/;var Ie="agent:command",$e="agent:command-ack",Nt="agent:active-job";import{z as l}from"zod";import{z as _}from"zod";import{z as f}from"zod";var Yo=["running","stopping","completed","cancelled","failed"],Xo=f.enum(Yo),zo=["completed","cancelled","failed"],hd=f.enum(zo),Zo=["lead_finished","user_cancelled","lead_failed"],fd=f.enum(Zo);var Qo=["none","attached","lost"],gd=f.enum(Qo),ei=["idle","active","awaiting_user"],wd=f.enum(ei),ti=["atlas","make_auto","preset"],yd=f.enum(ti),ni=["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"],_d=f.enum(ni),Sn=["web_runs_prompt","web_test_run_dialog","web_map_dialog","web_scenarios_dialog"],ri=f.enum(Sn),Ed=f.union([ri,f.literal("chat")]),Rn=["extension_atlas_card","extension_make_auto_modal","web_make_auto_dialog","web_job_repeat","web_workflow_repeat"],Sd=f.enum(Rn),oi=[...Rn,...Sn],Rd=f.enum(oi),ii=["browser","agent","none"],bd=f.enum(ii),ai=["browser","agent"],kd=f.enum(ai),si=["explore_app","find_bugs","create_tests","automate_scenarios","run_scenarios","custom"],Td=f.enum(si),li=["file_bugs","write_tests","edit_project"],vd=f.enum(li),di=["project","scenarios","test_run","test_plan"],Ad=f.enum(di),ci=["server","chat"],xd=f.enum(ci),ui=["host_lost","awaiting_browser","awaiting_user"],Id=f.enum(ui),mi=["opening","idle","busy","closing","closed"],Od=f.enum(mi),pi=["lead","user","window_closed","workflow_ended"],Nd=f.enum(pi),hi=["make_auto","atlas","run"],Pd=f.enum(hi),fi=["starting","running","ended"],Cd=f.enum(fi),gi=["completed","cancelled","failed","start_failed"],Dd=f.enum(gi),wi=["lead","user","window_closed","host_lost","host_refused","workflow_ended"],Ld=f.enum(wi),yi=["lead_choice","role_default"],Gd=f.enum(yi),_i=["observe","main","dangerous"],Ud=f.enum(_i),Ei=["main","dangerous"],bn=f.enum(Ei);var Si=["workflow.access_hint_lost","workflow.window_refused","workflow.tab_refused","workflow.scenario_needs_conversion"],Md=f.enum(Si),Ri=["workflows.not_found","workflows.not_initiator","workflows.not_initiator_or_admin","workflows.worker_not_found","workflows.not_running","workflows.host_held","workflows.host_mismatch","workflows.host_lost","workflows.host_attached","workflows.host_pending","workflows.executor_kind_mismatch","workflows.executor_mismatch","workflows.agent_mismatch","workflows.request_mismatch","workflows.agents_over_max","workflows.scope_not_found","workflows.scope_forbidden","workflows.conversation_busy","workflows.max_requires_browser","workflows.not_preset"],$d=f.enum(Ri),Fd=f.object({status:Xo}),jd=f.object({leaseExpiresAt:f.iso.datetime()}),Bd=f.object({workflowId:f.uuid()}),Wd=f.object({agentId:f.uuid()});var kn=_.object({queueId:_.uuid(),projectId:_.uuid(),projectDomain:_.string().min(1),applicationId:_.uuid().nullable(),entryUrl:_.url({protocol:/^https?$/}),headful:_.boolean()}).strict(),Fe=_.object({projectId:_.uuid(),projectDomain:_.string().min(1),entryUrl:_.url({protocol:/^https?$/}),standMode:bn,accountLabel:_.string().min(1),role:_.string().min(1),locale:_.string().min(1),viewportWidth:_.number().int().min(1),viewportHeight:_.number().int().min(1)}).strict(),Pt=_.object({...Fe.shape,environmentId:_.uuid().nullable()}).strict(),Kd=_.union([Fe,Pt]),Jd=_.object({workflowId:_.uuid(),entryUrl:_.url({protocol:/^https?$/}),headful:_.boolean()}).strict();import{z as se}from"zod";import{z as L}from"zod";var Tn=["passed","failed","infra","cancelled","abandoned"];var bi=["queued","launching","in_progress"];var vn=["passed","failed"],ki=["before_hook_failed","no_start_page","no_path_for_page"],Ti=["no_route_to_start_page","navigation_service_unavailable","scenario_load_failed","run_policy_unavailable","variables_load_failed","start_failed"],Ct=[...ki,...Ti];var ec=[...Tn,...bi];var tc=L.discriminatedUnion("by",[L.object({by:L.literal("human"),outcome:L.enum(vn)}).strict(),L.object({by:L.literal("not_started"),cause:L.enum(Ct),hookSharedStepId:L.uuid().optional()}).strict().refine(t=>t.hookSharedStepId!==void 0==(t.cause==="before_hook_failed"),{message:"hookSharedStepId is required for before_hook_failed and forbidden for any other cause",path:["hookSharedStepId"]})]),nc=L.object({outcome:L.enum(vn)}).strict();var vi=["queued","launching","in_progress","completed","failed","cancelled"],sc=se.enum(vi);var Ai=["queued","launching","in_progress"],An=se.enum(Ai);var xi=["claim_timeout","launch_timeout","launch_error","browser_gone","agent_lost","max_duration","killed","lease_lost","budget_exhausted",...Ct,"result_not_saved"],lc=se.enum(xi),Ii=["launch_error","browser_gone","max_duration"],Dt=se.enum(Ii),Oi=["name_not_resolved","unreachable","certificate","timeout","other"],xn=se.enum(Oi);var Ni=["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"],Pi=se.enum(Ni),Ci=["workflow_host_lost"],dc=Pi.exclude(Ci);var Di=l.enum(["darwin","linux","win32"]),Li=l.enum(["x64","arm64"]),On=l.enum(["official","debug"]),gc=l.object({enrollmentCode:l.string().min(32),hostname:l.string().min(1).max(255),platform:Di,arch:Li,agentVersion:l.string().min(1).max(30),protocolVersion:l.number().int().min(1)}).strict(),je=l.object({agentId:l.uuid(),agentToken:l.string().regex(ae),pollWaitSec:l.number().int().min(1).max(25),protocolVersion:l.literal(1)}).strict(),wc=l.object({waitSec:l.coerce.number().int().min(0).max(25).optional()}).strict(),Nn=l.object({agent:l.object({revoked:l.boolean()}).strict(),run:l.union([l.null(),l.object({runId:l.uuid(),phase:An}).strict()])}).strict(),Lt=l.object({v:l.literal(1),kind:l.literal("playback"),runId:l.uuid(),scenarioId:l.uuid(),projectId:l.uuid(),projectDomain:l.string().min(1),applicationId:l.uuid().nullable(),environmentId:l.uuid().nullable(),executionMode:l.literal("auto"),issuedAt:l.iso.datetime()}).strict(),Gt=l.object({v:l.literal(1),kind:l.literal("make_auto"),runId:l.uuid(),issuedAt:l.iso.datetime(),...kn.shape}).strict(),Gi=l.object({v:l.literal(1),kind:l.literal("atlas_crawl"),runId:l.uuid(),issuedAt:l.iso.datetime(),...Fe.shape}).strict(),Ui=l.object({v:l.literal(1),kind:l.literal("atlas_crawl"),runId:l.uuid(),issuedAt:l.iso.datetime(),...Pt.shape}).strict(),Ut=l.union([Ui,Gi]),Mt=l.object({v:l.literal(1),kind:l.literal("swarm"),runId:l.uuid(),issuedAt:l.iso.datetime(),workflowId:l.uuid()}).strict(),yc=l.union([Lt,Gt,Ut,Mt]),Mi={playback:!0,make_auto:!0,atlas_crawl:!0,swarm:!0},_c=Object.keys(Mi),Ec=l.object({agentJobId:l.uuid(),updatedAt:l.iso.datetime()}).strict(),$i=l.enum(["invalid_envelope","dispatch_failed"]),Pn=l.discriminatedUnion("outcome",[l.object({runId:l.uuid(),outcome:l.literal("dispatched")}).strict(),l.object({runId:l.uuid(),outcome:l.literal("rejected"),reason:$i}).strict()]),Cn=l.object({cancelRequested:l.boolean(),killRequested:l.boolean()}).strict(),Fi=2147483646,ji=l.object({stepId:l.uuid(),stepIndex:l.number().int().min(0).max(Fi),status:l.enum(["passed","failed","skipped"]),failureCode:l.string().max(64).regex(/^[a-z0-9_]+$/).nullable(),notes:l.string().max(4e3).nullable(),startedAt:l.iso.datetime().nullable(),completedAt:l.iso.datetime().nullable()}).strict(),Sc=l.object({events:l.array(ji).min(1).max(50)}).strict(),Rc=l.object({updated:l.number().int().min(0),control:Cn}).strict(),bc=l.object({phase:l.enum(["running","paused"])}).strict(),kc=l.object({control:Cn}).strict(),In=l.string().max(500).optional(),Tc=l.discriminatedUnion("reason",[l.object({reason:l.literal(Dt.enum.launch_error),message:In,entryFailure:xn.optional()}).strict(),l.object({reason:Dt.exclude(["launch_error"]),message:In}).strict()]),Dn=l.object({status:l.enum(["failed","already_terminal"])}).strict();var Nc=h.union([h.object({}).strict(),h.object({capabilities:hn}).strict()]);function Be(t){let{value:e}=t;e.command.runId!==e.runId&&t.issues.push({code:"custom",input:e.command.runId,path:["command","runId"],message:"command.runId must be the claimed runId \u2014 the agent and the extension must monitor the same unit of work"})}i(Be,"checkClaimRunIdAgreement");function Bi(t){let{value:e}=t;e.command.projectId!==e.projectId&&t.issues.push({code:"custom",input:e.command.projectId,path:["command","projectId"],message:"command.projectId must be the claimed projectId"})}i(Bi,"checkPlaybackClaimProjectAgreement");var Wi=h.object({runId:h.uuid(),scenarioId:h.uuid(),projectId:h.uuid(),applicationId:h.uuid().nullable(),projectDomain:h.string().min(1),entryUrl:h.url({protocol:/^https?$/}),environmentId:h.uuid().nullable(),runPurpose:On,headful:h.boolean(),maxRunDurationSec:h.number().int().min(60).max(3600),extensionSession:h.object({accessToken:h.string().min(1),refreshToken:h.string().min(1)}).strict(),command:Lt}).strict().check(Be).check(Bi),Ft=h.object({accessToken:h.string().min(1),refreshToken:h.string().min(1)}).strict(),qi=h.object({kind:h.literal("make_auto"),runId:h.uuid(),entryUrl:h.url({protocol:/^https?$/}),headful:h.boolean(),maxRunDurationSec:h.number().int().min(60).max(604800),extensionSession:Ft,command:Gt}).strict().check(Be),Vi=h.object({kind:h.literal("atlas_crawl"),runId:h.uuid(),entryUrl:h.url({protocol:/^https?$/}),headful:h.boolean(),maxRunDurationSec:h.number().int().min(60).max(604800),extensionSession:Ft,command:Ut}).strict().check(Be),Hi=h.object({kind:h.literal("swarm"),runId:h.uuid(),entryUrl:h.url({protocol:/^https?$/}),headful:h.boolean(),maxRunDurationSec:h.number().int().min(60).max(604800),extensionSession:Ft,command:Mt}).strict().check(Be),Ln=h.union([Wi,qi,Vi,Hi]);import{z as Gn}from"zod";var Ki=["finished","cancelled","ai_disabled"],Ji=Gn.enum(Ki),Lc=Gn.object({outcome:Ji}).strict();import{spawn as ra}from"node:child_process";import{existsSync as oa}from"node:fs";import{createRequire as ia}from"node:module";import{dirname as $n,join as aa}from"node:path";import ea from"pino";var Yi=new Set(["token","agenttoken","accesstoken","refreshtoken","pgrttoken","jobtoken","authorization","secret","password","resolvedvariables","cookie","set-cookie","x-api-key","proxy-authorization","api-key"]),Xi=/\b(?:pgat_|rr_|pgrt_)[A-Za-z0-9_-]+/g,zi=/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,Zi=["token","secret","password","authorization","api_key","api-key","apikey"],Qi=new RegExp(`([?&](?:${Zi.join("|")})=)([^&\\s]+)`,"gi"),We="[REDACTED]";function Un(t){let e=t.replace(zi,We);return e=e.replace(Xi,We),e=e.replace(Qi,`$1${We}`),e}i(Un,"redactValueString");function Z(t){if(Array.isArray(t))return t.map(Z);if(t!==null&&typeof t=="object"){let e=t,n={};for(let r of Object.keys(e))Yi.has(r.toLowerCase())?n[r]=We:n[r]=Z(e[r]);return n}return typeof t=="string"?Un(t):t}i(Z,"redactSecrets");function $(t){return Un(t)}i($,"redactSensitiveText");function ta(){let t=process.env.PROGON_LOG_LEVEL;return t!==void 0&&new Set(["trace","debug","info","warn","error","fatal","silent"]).has(t)?t:process.env.NODE_ENV==="production"?"info":"debug"}i(ta,"resolveLogLevel");function na(){if(process.env.NODE_ENV!=="production")return{target:"pino-pretty",options:{translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname"}}}i(na,"buildTransport");var Mn=ea({name:"qa-runner",level:ta(),transport:na(),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 jt(t){return{debug(e,n){n!==void 0?t.debug(Z(n),e):t.debug(e)},info(e,n){n!==void 0?t.info(Z(n),e):t.info(e)},warn(e,n){n!==void 0?t.warn(Z(n),e):t.warn(e)},error(e,n){n!==void 0?t.error(Z(n),e):t.error(e)},child(e){return jt(t.child(e))}}}i(jt,"adaptPino");function u(t){return jt(Mn.child({module:t}))}i(u,"createLogger");var Yc=jt(Mn);var Bt=u("browser-provision"),sa=60*6e4,V=class extends Error{static{i(this,"BrowserProvisionError")}exitCode;timedOut;constructor(e,n={}){super(e,{cause:n.cause}),this.name="BrowserProvisionError",this.exitCode=n.exitCode===void 0?null:n.exitCode,this.timedOut=n.timedOut===void 0?!1:n.timedOut}},Fn=[" - Behind a proxy? Set HTTPS_PROXY (and NO_PROXY for internal hosts) before starting the",' agent, as http://host:port or https://host:port \u2014 a scheme-less "host:port" is read as'," HTTP, and a SOCKS proxy is not one this agent can use (gateway/proxy-config.ts)."," - TLS intercepted by a corporate gateway? Point NODE_EXTRA_CA_CERTS at the root certificate."," - CDN blocked? Set PLAYWRIGHT_DOWNLOAD_HOST to an internal Playwright download mirror."," - Out of disk? Chromium needs roughly 500MB unpacked in the Playwright browsers cache"," (PLAYWRIGHT_BROWSERS_PATH, or the per-user default cache)."].join(`
|
|
3
|
-
`);function
|
|
4
|
-
`),process.kill(process.pid,
|
|
5
|
-
${
|
|
6
|
-
${
|
|
7
|
-
`);if(o===-1)return;let
|
|
8
|
-
`))Bn(s,e)}),t.on("end",()=>{let r=n;n="",Bn(r,e)})}i(jn,"forwardLinesToLogger");function Bn(t,e){let n=t.replace(/\r/g,"").trim();n!==""&&Bt.info("Chromium provisioning output",{stream:e,line:n})}i(Bn,"logLine");import{homedir as Ya}from"node:os";import{isAbsolute as mr,join as ze}from"node:path";var m=class extends Error{static{i(this,"OperatorRefusalError")}};var da=new Set(["localhost","127.0.0.1","::1","[::1]"]);function Q(t){let e;try{e=new URL(t)}catch{throw new m("[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:"&&da.has(e.hostname)))throw new m(`[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 m(`[config] PROGON_SERVER_URL must include a non-empty host. Got: ${JSON.stringify(t)}. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`);if(e.username!==""||e.password!=="")throw new m("[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 m(`[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(Q,"validateServerUrl");function Oe(t){if(!ae.test(t))throw new m("[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(Oe,"validateRunnerToken");function Wt(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 m(`[config] agentId must be a valid UUID (issued by the server at enroll). Got: ${JSON.stringify(t)}. The state file may be corrupted \u2014 remove it and re-enroll.`)}i(Wt,"validateRunnerMachineId");function qt(t){if(t!==1)throw new m(`[config] Protocol version mismatch: state file records version ${t} but this daemon requires version ${1}. Remove the state file and re-enroll with the correct daemon version.`)}i(qt,"validateProtocolVersion");import{Agent as ca,EnvHttpProxyAgent as ua}from"undici";var Wn=u("gateway-proxy"),ma=["http_proxy","HTTP_PROXY"],pa=["https_proxy","HTTPS_PROXY"],ha=["no_proxy","NO_PROXY"];function fa(t){return t.http!==void 0||t.https!==void 0}i(fa,"gatewayIsProxied");var ga=/^[A-Za-z][A-Za-z0-9+.-]*:\/\//,wa=/:\d+$/,ya=/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)?[^/?#]*@/;function _a(t){let e=ya.exec(t);if(e===null)return t;let n=e[1];return`${n===void 0?"":n}***@${t.slice(e[0].length)}`}i(_a,"withoutProxyCredentials");function de(t,e,n){return new Error(`[config] ${t} does not name a proxy this agent can use: ${n}. Got: ${JSON.stringify(_a(e))}. Accepted: an absolute "http://host:port" (or "https://host:port"), or the scheme-less curl form "host:port", which is read as "http://host:port". The agent-gateway transport speaks HTTP proxying only \u2014 a SOCKS proxy cannot carry it. Unset ${t} to connect to the server directly. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`)}i(de,"refuseProxyValue");function qn(t,e){for(let n of e){let r=t[n];if(r!==void 0)return r===""?void 0:{variable:n,raw:r}}}i(qn,"readProxyVariable");function Ea(t){for(let e of ha){let n=t[e];if(n!==void 0)return n}}i(Ea,"readNoProxy");function Vn(t,e){if(ga.test(e)){let s;try{s=new URL(e)}catch{throw de(t,e,"it carries a scheme but is not a URL that parses")}if(s.protocol!=="http:"&&s.protocol!=="https:")throw de(t,e,`its scheme is ${JSON.stringify(s.protocol)}, not http: or https:`);if(s.hostname==="")throw de(t,e,"it names no host");return{variable:t,url:e,schemeCompleted:!1}}let n=e.search(/[/?#]/),r=n===-1?e:e.slice(0,n);if(!wa.test(r))throw de(t,e,'it carries no scheme, so it is read as the curl "host:port" form, and it names no port');let o=`http://${e}`,a;try{a=new URL(o)}catch{throw de(t,e,'it is neither a URL nor a "host:port" pair')}if(a.hostname==="")throw de(t,e,"it names no host");return{variable:t,url:o,schemeCompleted:!0}}i(Vn,"parseProxyValue");function Vt(t){let e=qn(t,ma),n=qn(t,pa);return{http:e===void 0?void 0:Vn(e.variable,e.raw),https:n===void 0?void 0:Vn(n.variable,n.raw),noProxy:Ea(t)}}i(Vt,"resolveGatewayProxyConfig");function Hn(t,e,n){if(!fa(t))return new ca(e);Wn.info("Gateway traffic follows the proxy configured in this environment",{httpProxy:t.http!==void 0,httpsProxy:t.https!==void 0,noProxy:t.noProxy!==void 0});let r=[];for(let a of[t.http,t.https])a!==void 0&&a.schemeCompleted&&r.push(a.variable);r.length>0&&Wn.info('A proxy variable carries no scheme and is read as an HTTP proxy (curl convention: "host:port" means "http://host:port")',{variables:r});let o={...e,...n===void 0?{}:{requestTls:{ca:n},proxyTls:{ca:n}},httpProxy:t.http?.url,httpsProxy:t.https?.url,noProxy:t.noProxy};return new ua(o)}i(Hn,"createProxyAwareDispatcher");function Kn(t){Vt(t)}i(Kn,"validateGatewayProxyEnv");import{readFileSync as Sa,statSync as Ra}from"node:fs";import{isAbsolute as ba}from"node:path";import{rootCertificates as Jn}from"node:tls";var ka=u("gateway-tls-trust"),He="PROGON_AGENT_EXTRA_CA_CERTS";function Ve(t,e,n){let r=`[config] ${He} 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 ${He} to trust only the public roots.`;return n===void 0?new Error(r):new Error(r,{cause:n})}i(Ve,"refuseExtraCaValue");function Yn(t){let e=t[He];if(e===void 0||e==="")return;if(!ba(e))throw Ve(e,"it is not an absolute path, and a relative one would be resolved against the working directory the daemon happens to have been started in");let n;try{n=Ra(e)}catch(o){throw Ve(e,"it cannot be read",o)}if(!n.isFile())throw Ve(e,"it is not a file");let r;try{r=Sa(e,"utf8")}catch(o){throw Ve(e,"its contents could not be read",o)}return{variable:He,path:e,pem:r}}i(Yn,"resolveExtraCaTrust");function Xn(t){let e=Yn(t);if(e!==void 0)return ka.info("Trusting an extra certificate authority for the agent's own connections",{variable:e.variable,path:e.path,publicRootCount:Jn.length}),[...Jn,e.pem]}i(Xn,"readTrustedCaBundle");function zn(t){Yn(t)}i(zn,"validateExtraCaTrustEnv");import{readFileSync as Ia}from"node:fs";import{dirname as Oa,join as Na}from"node:path";import{fileURLToPath as Pa}from"node:url";function ee(t){if(typeof t!="object"||t===null)return!1;let e=t.code;return e==="ENOENT"||e==="ENOTDIR"}i(ee,"isAbsentPathError");import{statSync as Ta}from"node:fs";import{dirname as va,join as Aa}from"node:path";var Zn="package.json";function Ke(t){let e=t;for(;;){if(xa(e))return e;let n=va(e);if(n===e)throw new Error(`[package-root] No ${Zn} was found in ${t} or in any of its parent directories, so the root of the package this file belongs to cannot be determined. This is a packaging defect, not a configuration one: the module asking is supposed to be running from inside an installed or checked-out package.`);e=n}}i(Ke,"findPackageRoot");function xa(t){try{return Ta(Aa(t,Zn)),!0}catch(e){if(ee(e))return!1;throw e}}i(xa,"holdsPackageManifest");var Ca="extension-bundle.json";function Ht(){return Da(Na(Ke(Oa(Pa(import.meta.url))),Ca))}i(Ht,"readBundledAppUrl");function Da(t){let e;try{e=Ia(t,"utf-8")}catch(o){if(ee(o))return null;throw new m(`[extension-bundle] ${t} exists but could not be read: ${String(o)}. It records the deployment this package was built for, so the agent cannot tell which Progon it belongs to until the file is readable. Check the permissions on the installed package, or reinstall it: npm i -g progon-agent@latest.`,{cause:o})}let n;try{n=JSON.parse(e)}catch(o){throw new m(`[extension-bundle] ${t} contains invalid JSON: ${String(o)}. This package's record of the deployment it was built for is damaged \u2014 reinstall it: npm i -g progon-agent@latest.`,{cause:o})}if(typeof n!="object"||n===null||Array.isArray(n)){let o=n===null?"null":Array.isArray(n)?"array":typeof n;throw new m(`[extension-bundle] ${t} must contain a JSON object, got: ${o}. Reinstall the package: npm i -g progon-agent@latest.`)}let r=n.appUrl;if(typeof r!="string"||r==="")throw new m(`[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{Q(r)}catch(o){throw new m(`[extension-bundle] ${t} has an invalid 'appUrl': ${String(o)}`,{cause:o})}return r}i(Da,"readBundledAppUrlFrom");import{unlinkSync as Ka}from"node:fs";import{readFileSync as La,writeFileSync as Ga,renameSync as Ua,mkdirSync as Ma,existsSync as $a,chmodSync as Fa,fchmodSync as ja,openSync as Qn,fsyncSync as er,closeSync as tr,unlinkSync as Ba}from"node:fs";import{join as nr}from"node:path";var Je=u("state-file");function Ye(t){return nr(t,"runner-state.json")}i(Ye,"stateFilePath");function Kt(t){return nr(t,"runner-state.json.tmp")}i(Kt,"stateTmpPath");function rr(t){let e=Ye(t);if(!$a(e))return Je.debug("No state file found \u2014 first start",{filePath:e}),null;let n;try{n=La(e,"utf-8")}catch(a){throw new m(`[state-file] Failed to read state file at ${e}: ${String(a)}. Check that this user owns the file and its directory. If it is beyond repair, remove it and enroll the machine again with 'progon-agent enroll' (a source checkout, which carries no bundled deployment, also needs --server <url>).`)}let r;try{r=JSON.parse(n)}catch(a){throw new m(`[state-file] State file at ${e} contains invalid JSON: ${String(a)}. Remove the file and enroll the machine again with 'progon-agent enroll' (a source checkout, which carries no bundled deployment, also needs --server <url>).`)}let o=Va(r,e);return Je.info("State file loaded",{agentId:o.agentId,protocolVersion:o.protocolVersion}),o}i(rr,"readState");function or(t,e){Ma(t,{recursive:!0,mode:448}),Fa(t,448);let n=Ye(t),r=Kt(t),o=JSON.stringify(e,null,2);try{let a=Qn(r,"w",384);try{ja(a,384),Ga(a,o,{encoding:"utf-8"}),er(a)}finally{tr(a)}Ua(r,n),qa(t)}catch(a){throw Wa(r),new m(`[state-file] Failed to write state file at ${n}: ${String(a)}. Check permissions on stateDir ${t}.`)}Je.info("State file written",{agentId:e.agentId,filePath:n})}i(or,"writeState");function Wa(t){try{Ba(t)}catch(e){if(e.code==="ENOENT")return;Je.error("Failed to remove the temporary state file \u2014 it may still hold the agent credential",{tmpPath:t,err:e instanceof Error?e.message:String(e)})}}i(Wa,"removeStateTmp");function qa(t){let e=Qn(t,"r");try{er(e)}finally{tr(e)}}i(qa,"fsyncDirectory");function Va(t,e){if(typeof t!="object"||t===null||Array.isArray(t)){let d=t===null?"null":Array.isArray(t)?"array":typeof t;throw new m(`[state-file] State file ${e} must contain a JSON object, got: ${d}`)}let n=t,r=n.agentId;if(typeof r!="string"||r==="")throw new m(`[state-file] State file ${e} is missing or has invalid 'agentId' (expected non-empty string).`);Wt(r);let o=n.agentToken;if(typeof o!="string"||o==="")throw new m(`[state-file] State file ${e} is missing or has invalid 'agentToken' (expected non-empty string).`);Oe(o);let a=n.protocolVersion;if(typeof a!="number"||!Number.isInteger(a))throw new m(`[state-file] State file ${e} is missing or has invalid 'protocolVersion' (expected integer).`);qt(a);let s=n.serverUrl;if(typeof s!="string"||s==="")throw new m(`[state-file] State file ${e} is missing or has invalid 'serverUrl' (expected non-empty string).`);try{Q(s)}catch(d){throw new m(`[state-file] State file ${e} has an invalid 'serverUrl': ${String(d)}`)}return{agentId:r,agentToken:o,protocolVersion:a,serverUrl:s,tokenRotatedAt:Ha(n,e)}}i(Va,"validateState");function Ha(t,e){let n=t.tokenRotatedAt;if(n==null)return null;if(typeof n!="string"||n==="")throw new m(`[state-file] State file ${e} has an invalid 'tokenRotatedAt' (expected a non-empty ISO string, null, or the key to be absent on a file written before agent token rotation shipped).`);return n}i(Ha,"readTokenRotatedAt");var ir=u("token-store");function F(t){return rr(t)}i(F,"loadAgentIdentity");function ce(t,e){or(t,e)}i(ce,"saveAgentIdentity");function sr(t){let e=Ye(t),n=Kt(t),r=ar(n,"temporary state file"),o=ar(e,"identity");if(!o&&!r){ir.info("Agent identity wipe: no state file to remove",{filePath:e,tmpPath:n});return}ir.warn("Agent identity wiped \u2014 this agent was revoked and must be re-enrolled",{filePath:e,tmpPath:n,removedState:o,removedTmp:r})}i(sr,"wipeAgentIdentity");function ar(t,e){try{return Ka(t),!0}catch(n){if(Ja(n))return!1;throw new Error(`[token-store] Failed to wipe the agent ${e} at ${t}: ${String(n)}. The agent has been revoked (CONTRACT-la \xA715 A15.1) and its credential must not remain on disk \u2014 remove the file manually.`)}}i(ar,"removeCredentialFile");function Ja(t){return t.code==="ENOENT"}i(Ja,"isFileNotFound");var lr="extension-bundle.json";function Xe(t,e){return dr(t)===dr(e)}i(Xe,"isSameDeployment");function dr(t){let e=new URL(t);return`${e.origin}${e.pathname.replace(/\/+$/,"")}`}i(dr,"normalizeDeployment");function cr(t){let{envUrl:e,envTokenPresent:n,stateDir:r}=t;if(e!==void 0)return Q(e),{url:e,source:"env"};if(n){let s=Ht();if(s!==null)return{url:s,source:"bundle"};throw new m(`[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 ${
|
|
2
|
+
var oi=Object.defineProperty;var i=(n,e)=>oi(n,"name",{value:e,configurable:!0});import{realpathSync as Id}from"node:fs";import{pathToFileURL as xd}from"node:url";import{z as En}from"zod";var ii=/^[a-z_]{1,32}@\d{1,3}$/,Sn=En.array(En.string().regex(ii)).min(1).max(32),Rn=["playback@1"],bn="swarm@1",kn="swarm@2",vn="scenario_launch@1",Tn="browser_channel@1";import{z as y}from"zod";var le=/^pgat_[0-9A-Za-z]{43}$/;var Le="agent:command",He="agent:command-ack",Ft="agent:active-job";import{z as d}from"zod";import{z as _}from"zod";import{z as u}from"zod";var si=["running","pausing","paused","stopping","finalizing","completed","cancelled","failed"],In=u.enum(si),xn=["completed","cancelled","failed"],Bd=u.enum(xn),ai=["running","pausing","paused","stopping","finalizing"],Kd=u.enum(ai),li=["running","pausing","stopping"],qd=u.enum(li),di=["paused",...xn],Hd=u.enum(di),ci=["user","credits","user_credit_limit"],Vd=u.enum(ci),ui=["exploring","final_analysis","done"],Jd=u.enum(ui),mi=["queued","running","done","failed","cancelled"],Yd=u.enum(mi),pi=["done","failed","cancelled"],Xd=u.enum(pi),hi=["lead_finished","user_cancelled","lead_failed"],zd=u.enum(hi);var fi=["none","attached","lost"],Zd=u.enum(fi),gi=["idle","active","awaiting_user"],Qd=u.enum(gi),wi=["atlas","make_auto","preset"],ec=u.enum(wi),yi=["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"],tc=u.enum(yi),_i=["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"],Ei=u.enum(_i),Si=["web_runs_prompt","web_test_run_dialog","web_map_dialog","web_scenarios_dialog","extension_atlas_card","extension_make_auto_modal","web_workflow_repeat"],nc=u.enum(Si),rc=u.union([Ei,u.literal("chat")]),Ri=["browser","agent","none"],bi=u.enum(Ri),ki=["browser","agent"],oc=u.enum(ki),vi=["explore_app","find_bugs","create_tests","automate_scenarios","run_scenarios","custom"],ic=u.enum(vi),Ti=["file_bugs","write_tests","edit_project"],sc=u.enum(Ti),Ii=["text","auto"],ac=u.enum(Ii),xi=["project","scenarios","test_run","test_plan"],lc=u.enum(xi),Ai=["host_lost","awaiting_browser","awaiting_user","paused"],dc=u.enum(Ai),Oi=["window","mcp_agent","agent"],cc=u.enum(Oi),Ni=["opening","idle","busy","closing","closed"],uc=u.enum(Ni),Pi=["lead","user","window_closed","workflow_ended","workflow_paused","unit_ended"],mc=u.enum(Pi),Ci=["lead","user","workflow_ended","no_connection","left"],pc=u.enum(Ci),Di=["lead","user","workflow_ended","workflow_paused","unit_ended"],hc=u.enum(Di),Li=["lead","user","window_closed","workflow_ended","workflow_paused","no_connection","left","unit_ended"],fc=u.enum(Li),Gi=["make_auto","atlas","run","agent","mcp_task"],gc=u.enum(Gi);var Ui=["starting","running","ended"],wc=u.enum(Ui),Mi=["completed","cancelled","failed","start_failed","lost"],yc=u.enum(Mi),$i=["user","lead","left","no_connection","workflow_ended","not_taken"],Fi=u.enum($i);var ji=["lead","user","window_closed","host_lost","host_refused","workflow_ended","workflow_paused"],_c=u.enum(ji),Wi=["lead_choice","role_default"],Ec=u.enum(Wi),Bi=["observe","main","dangerous"],Sc=u.enum(Bi),Ki=["main","dangerous"],An=u.enum(Ki);var qi=["workflow.access_hint_lost","workflow.window_refused","workflow.tab_refused","workflow.scenario_needs_conversion","workflow.identity_busy","workflow.identity_not_set"],Rc=u.enum(qi),Hi=["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.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"],bc=u.enum(Hi),kc=u.object({status:In}),Vi=u.object({status:In}),Ji=["conversation_deleted"],Yi=u.enum(Ji),vc=Vi.extend({reason:Yi.optional()}),Tc=u.object({segment:u.number().int().min(1)}),Ic=u.object({executorKind:bi}),xc=u.object({reason:u.enum(["ended","no_browser"])}),Ac=u.object({reason:u.literal("task_paused")}),Oc=u.discriminatedUnion("outcome",[u.object({outcome:u.enum(["finished","stopped"]),lostReason:u.null()}),u.object({outcome:u.literal("lost"),lostReason:Fi})]),Nc=u.object({taskIds:u.array(u.uuid()).min(2)}),Pc=u.object({stepNumber:u.number().int().min(1),currentStepNumber:u.number().int().min(1).nullable()}),Cc=u.object({leaseExpiresAt:u.iso.datetime()}),Dc=u.object({workflowId:u.uuid()}),Lc=u.object({agentId:u.uuid()});var $c=_.object({queueId:_.uuid(),projectId:_.uuid(),projectDomain:_.string().min(1),applicationId:_.uuid().nullable(),entryUrl:_.url({protocol:/^https?$/}),headful:_.boolean()}).strict(),On=_.object({launchId:_.uuid(),projectId:_.uuid(),projectDomain:_.string().min(1),entryUrl:_.url({protocol:/^https?$/}),headful:_.boolean()}).strict(),Nn=_.object({projectId:_.uuid(),projectDomain:_.string().min(1),entryUrl:_.url({protocol:/^https?$/}),standMode:An,accountLabel:_.string().min(1),role:_.string().min(1),locale:_.string().min(1),viewportWidth:_.number().int().min(1),viewportHeight:_.number().int().min(1)}).strict(),Xi=_.object({...Nn.shape,environmentId:_.uuid().nullable()}).strict(),Fc=_.union([Nn,Xi]),jc=_.object({workflowId:_.uuid(),entryUrl:_.url({protocol:/^https?$/}),headful:_.boolean()}).strict();import{z as ce}from"zod";import{z as de}from"zod";var Pn=["passed","failed","infra","cancelled","abandoned"];var zi=["queued","launching","in_progress"];var Cn=["passed","failed"],Zi=["before_hook_failed","no_start_page","no_path_for_page"],Qi=["no_route_to_start_page","navigation_service_unavailable","scenario_load_failed","run_policy_unavailable","variables_load_failed","start_failed"],jt=[...Zi,...Qi],Vc=de.enum(jt).exclude(["before_hook_failed"]);var Jc=[...Pn,...zi];var Yc=de.object({by:de.literal("human"),outcome:de.enum(Cn)}).strict(),Xc=de.object({outcome:de.enum(Cn)}).strict();var es=["queued","launching","in_progress","completed","failed","cancelled"],tu=ce.enum(es);var ts=["queued","launching","in_progress"],Dn=ce.enum(ts);var ns=["claim_timeout","launch_timeout","launch_error","browser_gone","agent_lost","max_duration","killed","lease_lost","budget_exhausted",...jt,"result_not_saved","mcp_agent_disconnected"],nu=ce.enum(ns),rs=["launch_error","browser_gone","max_duration"],Wt=ce.enum(rs),os=["name_not_resolved","unreachable","certificate","timeout","other"],Ln=ce.enum(os);var is=["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"],ss=ce.enum(is),as=["workflow_host_lost"],ru=ss.exclude(as);var ls=d.enum(["darwin","linux","win32"]),ds=d.enum(["x64","arm64"]),Un=d.enum(["official","debug"]),cu=d.object({enrollmentCode:d.string().min(32),hostname:d.string().min(1).max(255),platform:ls,arch:ds,agentVersion:d.string().min(1).max(30),protocolVersion:d.number().int().min(1)}).strict(),Ve=d.object({agentId:d.uuid(),agentToken:d.string().regex(le),pollWaitSec:d.number().int().min(1).max(25),protocolVersion:d.literal(1)}).strict(),uu=d.object({waitSec:d.coerce.number().int().min(0).max(25).optional()}).strict(),Mn=d.object({agent:d.object({revoked:d.boolean()}).strict(),run:d.union([d.null(),d.object({runId:d.uuid(),phase:Dn,identities:d.array(d.object({identityId:d.uuid()}).strict()).optional()}).strict()])}).strict(),Bt=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(),Kt=d.object({v:d.literal(1),kind:d.literal("scenario_launch"),runId:d.uuid(),issuedAt:d.iso.datetime(),...On.shape}).strict(),qt=d.object({v:d.literal(1),kind:d.literal("swarm"),runId:d.uuid(),issuedAt:d.iso.datetime(),workflowId:d.uuid()}).strict(),cs=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(),mu=d.union([Bt,qt,Kt,cs]),us={playback:!0,swarm:!0,scenario_launch:!0,task_identity:!0},pu=Object.keys(us),hu=d.object({agentJobId:d.uuid(),updatedAt:d.iso.datetime()}).strict(),ms=d.enum(["invalid_envelope","dispatch_failed"]),$n=d.discriminatedUnion("outcome",[d.object({runId:d.uuid(),outcome:d.literal("dispatched")}).strict(),d.object({runId:d.uuid(),outcome:d.literal("rejected"),reason:ms}).strict()]),Fn=d.object({cancelRequested:d.boolean(),killRequested:d.boolean()}).strict(),ps=2147483646,hs=d.object({stepId:d.uuid(),stepIndex:d.number().int().min(0).max(ps),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(),fu=d.object({events:d.array(hs).min(1).max(50)}).strict(),gu=d.object({updated:d.number().int().min(0),control:Fn}).strict(),wu=d.object({phase:d.enum(["running","paused"])}).strict(),yu=d.object({control:Fn}).strict(),Gn=d.string().max(500).optional(),_u=d.discriminatedUnion("reason",[d.object({reason:d.literal(Wt.enum.launch_error),message:Gn,entryFailure:Ln.optional()}).strict(),d.object({reason:Wt.exclude(["launch_error"]),message:Gn}).strict()]),jn=d.object({status:d.enum(["failed","already_terminal"])}).strict();var vu=y.union([y.object({}).strict(),y.object({capabilities:Sn}).strict()]);function Ht(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(Ht,"checkClaimRunIdAgreement");function fs(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(fs,"checkPlaybackClaimProjectAgreement");var gs=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:Un,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:Bt}).strict().check(Ht).check(fs),Vt=y.object({accessToken:y.string().min(1),refreshToken:y.string().min(1)}).strict(),Bn=y.object({extensionSession:Vt}).strict(),ws=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:Vt,command:qt}).strict().check(Ht),ys=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:Vt,command:Kt}).strict().check(Ht),Kn=y.union([gs,ws,ys]);import{z as qn}from"zod";var _s=["finished","cancelled","ai_disabled"],Es=qn.enum(_s),Au=qn.object({outcome:Es}).strict();import{spawn as As}from"node:child_process";import{existsSync as Os}from"node:fs";import{createRequire as Ns}from"node:module";import{dirname as Jn,join as Ps}from"node:path";import Ts from"pino";var Ss=new Set(["token","agenttoken","accesstoken","refreshtoken","pgrttoken","jobtoken","authorization","secret","password","resolvedvariables","cookie","set-cookie","x-api-key","proxy-authorization","api-key"]),Rs=/\b(?:pgat_|rr_|pgrt_)[A-Za-z0-9_-]+/g,bs=/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,ks=["token","secret","password","authorization","api_key","api-key","apikey"],vs=new RegExp(`([?&](?:${ks.join("|")})=)([^&\\s]+)`,"gi"),Je="[REDACTED]";function Hn(n){let e=n.replace(bs,Je);return e=e.replace(Rs,Je),e=e.replace(vs,`$1${Je}`),e}i(Hn,"redactValueString");function Q(n){if(Array.isArray(n))return n.map(Q);if(n!==null&&typeof n=="object"){let e=n,t={};for(let r of Object.keys(e))Ss.has(r.toLowerCase())?t[r]=Je:t[r]=Q(e[r]);return t}return typeof n=="string"?Hn(n):n}i(Q,"redactSecrets");function $(n){return Hn(n)}i($,"redactSensitiveText");function Is(){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(Is,"resolveLogLevel");function xs(){if(process.env.NODE_ENV!=="production")return{target:"pino-pretty",options:{translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname"}}}i(xs,"buildTransport");var Vn=Ts({name:"qa-runner",level:Is(),transport:xs(),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 Jt(n){return{debug(e,t){t!==void 0?n.debug(Q(t),e):n.debug(e)},info(e,t){t!==void 0?n.info(Q(t),e):n.info(e)},warn(e,t){t!==void 0?n.warn(Q(t),e):n.warn(e)},error(e,t){t!==void 0?n.error(Q(t),e):n.error(e)},child(e){return Jt(n.child(e))}}}i(Jt,"adaptPino");function m(n){return Jt(Vn.child({module:n}))}i(m,"createLogger");var Bu=Jt(Vn);var Yt=m("browser-provision"),Cs=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}},Yn=[" - Behind a proxy? Set HTTPS_PROXY (and NO_PROXY for internal hosts) before starting the",' agent, as http://host:port or https://host:port \u2014 a scheme-less "host:port" is read as'," HTTP, and a SOCKS proxy is not one this agent can use (gateway/proxy-config.ts)."," - TLS intercepted by a corporate gateway? Point NODE_EXTRA_CA_CERTS at the root certificate."," - CDN blocked? Set PLAYWRIGHT_DOWNLOAD_HOST to an internal Playwright download mirror."," - Out of disk? Chromium needs roughly 500MB unpacked in the Playwright browsers cache"," (PLAYWRIGHT_BROWSERS_PATH, or the per-user default cache)."].join(`
|
|
3
|
+
`);function Ds(){let n=Ns(import.meta.url),e;try{e=n.resolve("playwright-core/package.json")}catch(r){throw new V(`[browser-provision] Cannot locate the 'playwright-core' package from ${import.meta.url}. It is a declared dependency of this agent \u2014 reinstall the package ('npm ci') rather than installing a browser by hand: the agent launches the revision THIS copy of playwright-core expects.`,{cause:r})}let t=Ps(Jn(e),"cli.js");if(!Os(t))throw new V(`[browser-provision] 'playwright-core' resolved to ${Jn(e)} but its CLI is not at ${t}. That installation is incomplete or has been altered \u2014 reinstall it ('npm ci'). This agent installs Chromium through that CLI and through no other path (CONTRACT-la \xA715 A31.1).`);return{execPath:process.execPath,cliPath:t,args:["install","chromium","--no-shell"]}}i(Ds,"resolveInstallCommand");async function Ye(n){let e=n.commandOverride===void 0?Ds():n.commandOverride,t=n.deadlineMs===void 0?Cs:n.deadlineMs,r=n.stdio==="pipe"?[...e.args,"--no-progress"]:[...e.args],o=`${e.execPath} ${e.cliPath} ${r.join(" ")}`,s=Date.now();Yt.info("Provisioning Chromium",{cliPath:e.cliPath,args:r,deadlineMs:t});let a=As(e.execPath,[e.cliPath,...r],{env:process.env,stdio:n.stdio==="inherit"?"inherit":["ignore","pipe","pipe"]});if(n.stdio==="pipe"){let{stdout:g,stderr:h}=a;if(g===null||h===null)throw new V(`[browser-provision] The installer was spawned without the stdout/stderr pipes this module requested (${o}).`);Xn(g,"stdout"),Xn(h,"stderr")}let l=!1,c=setTimeout(()=>{l=!0,a.kill("SIGKILL")},t),w=new Map,f=i(()=>{for(let[g,h]of w)process.off(g,h);w.clear()},"removeSignalHandlers");for(let g of["SIGTERM","SIGINT"]){let h=i(()=>{a.kill("SIGKILL"),f(),process.stderr.write(JSON.stringify({level:"warn",module:"browser-provision",msg:"Chromium provisioning aborted by signal: the installer was killed, and the next start downloads again",signal:g,installerPid:a.pid})+`
|
|
4
|
+
`),process.kill(process.pid,g)},"handler");w.set(g,h),process.on(g,h)}try{await new Promise((g,h)=>{a.once("error",v=>{h(new V(`[browser-provision] Could not start the Playwright installer (${o}): ${v.message}`,{cause:v}))}),a.once("close",(v,k)=>{if(l){h(new V(`[browser-provision] Chromium installation did not finish within ${t}ms and was killed (${o}). A stalled installer is a known Playwright failure mode (microsoft/playwright#40998) and usually means the download connection went silent rather than failing.
|
|
5
|
+
${Yn}`,{exitCode:v,timedOut:!0}));return}if(v===0){g();return}let qe=v===null?`was terminated by signal ${String(k)}`:`exited with code ${v}`;h(new V(`[browser-provision] Chromium could not be installed: the Playwright installer ${qe} (${o}). The agent cannot run scenarios without a browser and does not retry \u2014 a failed download is an environment condition, not a transient one.
|
|
6
|
+
${Yn}`,{exitCode:v}))})})}finally{clearTimeout(c),f()}Yt.info("Chromium is provisioned",{durationMs:Date.now()-s})}i(Ye,"provisionBrowser");function Xn(n,e){let t="";n.setEncoding("utf8"),n.on("data",r=>{t+=r;let o=t.lastIndexOf(`
|
|
7
|
+
`);if(o===-1)return;let s=t.slice(0,o);t=t.slice(o+1);for(let a of s.split(`
|
|
8
|
+
`))zn(a,e)}),n.on("end",()=>{let r=t;t="",zn(r,e)})}i(Xn,"forwardLinesToLogger");function zn(n,e){let t=n.replace(/\r/g,"").trim();t!==""&&Yt.info("Chromium provisioning output",{stream:e,line:t})}i(zn,"logLine");import{homedir as Sa}from"node:os";import{isAbsolute as Sr,join as nt}from"node:path";var p=class extends Error{static{i(this,"OperatorRefusalError")}};var Ls=new Set(["localhost","127.0.0.1","::1","[::1]"]);function ee(n){let e;try{e=new URL(n)}catch{throw new p("[config] PROGON_SERVER_URL is not a valid https:// URL. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.")}if(e.protocol!=="https:"&&!(e.protocol==="http:"&&Ls.has(e.hostname)))throw new p(`[config] PROGON_SERVER_URL must use the https:// scheme (encrypted HTTP). http:// is only allowed for loopback hosts (localhost, 127.0.0.1, [::1]). Got scheme: ${JSON.stringify(e.protocol)} with host: ${JSON.stringify(e.hostname)}. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`);if(e.host==="")throw new p(`[config] PROGON_SERVER_URL must include a non-empty host. Got: ${JSON.stringify(n)}. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`);if(e.username!==""||e.password!=="")throw new p("[config] PROGON_SERVER_URL must not contain embedded credentials (userinfo). Use the PROGON_AGENT_TOKEN env var for authentication instead. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.");if(e.search!==""||e.hash!=="")throw new p(`[config] PROGON_SERVER_URL must be a base URL with no query string and no fragment \u2014 the agent-gateway routes are appended to it, and a query or a fragment would swallow them instead of preceding them. Got query ${JSON.stringify(e.search)} and fragment ${JSON.stringify(e.hash)}. Use scheme + host + optional path prefix only (https://host, https://host/prefix). See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`)}i(ee,"validateServerUrl");function Ge(n){if(!le.test(n))throw new p("[config] Agent token must match the pgat_ wire format (CONTRACT-la \xA75.1). Got a token that does not match this format. Ensure PROGON_AGENT_TOKEN was copied from the server correctly.")}i(Ge,"validateRunnerToken");function Xt(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 p(`[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(Xt,"validateRunnerMachineId");function zt(n){if(n!==1)throw new p(`[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(zt,"validateProtocolVersion");import{Agent as Gs,EnvHttpProxyAgent as Us}from"undici";var Zn=m("gateway-proxy"),Ms=["http_proxy","HTTP_PROXY"],$s=["https_proxy","HTTPS_PROXY"],Fs=["no_proxy","NO_PROXY"];function js(n){return n.http!==void 0||n.https!==void 0}i(js,"gatewayIsProxied");var Ws=/^[A-Za-z][A-Za-z0-9+.-]*:\/\//,Bs=/:\d+$/,Ks=/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)?[^/?#]*@/;function qs(n){let e=Ks.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 me(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(me,"refuseProxyValue");function Qn(n,e){for(let t of e){let r=n[t];if(r!==void 0)return r===""?void 0:{variable:t,raw:r}}}i(Qn,"readProxyVariable");function Hs(n){for(let e of Fs){let t=n[e];if(t!==void 0)return t}}i(Hs,"readNoProxy");function er(n,e){if(Ws.test(e)){let a;try{a=new URL(e)}catch{throw me(n,e,"it carries a scheme but is not a URL that parses")}if(a.protocol!=="http:"&&a.protocol!=="https:")throw me(n,e,`its scheme is ${JSON.stringify(a.protocol)}, not http: or https:`);if(a.hostname==="")throw me(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(!Bs.test(r))throw me(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 me(n,e,'it is neither a URL nor a "host:port" pair')}if(s.hostname==="")throw me(n,e,"it names no host");return{variable:n,url:o,schemeCompleted:!0}}i(er,"parseProxyValue");function Zt(n){let e=Qn(n,Ms),t=Qn(n,$s);return{http:e===void 0?void 0:er(e.variable,e.raw),https:t===void 0?void 0:er(t.variable,t.raw),noProxy:Hs(n)}}i(Zt,"resolveGatewayProxyConfig");function tr(n,e,t){if(!js(n))return new Gs(e);Zn.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&&Zn.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 Us(o)}i(tr,"createProxyAwareDispatcher");function nr(n){Zt(n)}i(nr,"validateGatewayProxyEnv");import{readFileSync as Vs,statSync as Js}from"node:fs";import{isAbsolute as Ys}from"node:path";import{rootCertificates as rr}from"node:tls";var Xs=m("gateway-tls-trust"),ze="PROGON_AGENT_EXTRA_CA_CERTS";function Xe(n,e,t){let r=`[config] ${ze} 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 ${ze} to trust only the public roots.`;return t===void 0?new Error(r):new Error(r,{cause:t})}i(Xe,"refuseExtraCaValue");function or(n){let e=n[ze];if(e===void 0||e==="")return;if(!Ys(e))throw Xe(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=Js(e)}catch(o){throw Xe(e,"it cannot be read",o)}if(!t.isFile())throw Xe(e,"it is not a file");let r;try{r=Vs(e,"utf8")}catch(o){throw Xe(e,"its contents could not be read",o)}return{variable:ze,path:e,pem:r}}i(or,"resolveExtraCaTrust");function ir(n){let e=or(n);if(e!==void 0)return Xs.info("Trusting an extra certificate authority for the agent's own connections",{variable:e.variable,path:e.path,publicRootCount:rr.length}),[...rr,e.pem]}i(ir,"readTrustedCaBundle");function sr(n){or(n)}i(sr,"validateExtraCaTrustEnv");import{readFileSync as ta}from"node:fs";import{dirname as na,join as ra}from"node:path";import{fileURLToPath as oa}from"node:url";function te(n){if(typeof n!="object"||n===null)return!1;let e=n.code;return e==="ENOENT"||e==="ENOTDIR"}i(te,"isAbsentPathError");import{statSync as zs}from"node:fs";import{dirname as Zs,join as Qs}from"node:path";var ar="package.json";function Ze(n){let e=n;for(;;){if(ea(e))return e;let t=Zs(e);if(t===e)throw new Error(`[package-root] No ${ar} 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(Ze,"findPackageRoot");function ea(n){try{return zs(Qs(n,ar)),!0}catch(e){if(te(e))return!1;throw e}}i(ea,"holdsPackageManifest");var ia="extension-bundle.json";function Qt(){return sa(ra(Ze(na(oa(import.meta.url))),ia))}i(Qt,"readBundledAppUrl");function sa(n){let e;try{e=ta(n,"utf-8")}catch(o){if(te(o))return null;throw new p(`[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 p(`[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 p(`[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 p(`[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{ee(r)}catch(o){throw new p(`[extension-bundle] ${n} has an invalid 'appUrl': ${String(o)}`,{cause:o})}return r}i(sa,"readBundledAppUrlFrom");import{unlinkSync as _a}from"node:fs";import{readFileSync as aa,writeFileSync as la,renameSync as da,mkdirSync as ca,existsSync as ua,chmodSync as ma,fchmodSync as pa,openSync as lr,fsyncSync as dr,closeSync as cr,unlinkSync as ha}from"node:fs";import{join as ur}from"node:path";var Qe=m("state-file");function et(n){return ur(n,"runner-state.json")}i(et,"stateFilePath");function en(n){return ur(n,"runner-state.json.tmp")}i(en,"stateTmpPath");function mr(n){let e=et(n);if(!ua(e))return Qe.debug("No state file found \u2014 first start",{filePath:e}),null;let t;try{t=aa(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(t)}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 o=wa(r,e);return Qe.info("State file loaded",{agentId:o.agentId,protocolVersion:o.protocolVersion}),o}i(mr,"readState");function pr(n,e){ca(n,{recursive:!0,mode:448}),ma(n,448);let t=et(n),r=en(n),o=JSON.stringify(e,null,2);try{let s=lr(r,"w",384);try{pa(s,384),la(s,o,{encoding:"utf-8"}),dr(s)}finally{cr(s)}da(r,t),ga(n)}catch(s){throw fa(r),new p(`[state-file] Failed to write state file at ${t}: ${String(s)}. Check permissions on stateDir ${n}.`)}Qe.info("State file written",{agentId:e.agentId,filePath:t})}i(pr,"writeState");function fa(n){try{ha(n)}catch(e){if(e.code==="ENOENT")return;Qe.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(fa,"removeStateTmp");function ga(n){let e=lr(n,"r");try{dr(e)}finally{cr(e)}}i(ga,"fsyncDirectory");function wa(n,e){if(typeof n!="object"||n===null||Array.isArray(n)){let l=n===null?"null":Array.isArray(n)?"array":typeof n;throw new p(`[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 p(`[state-file] State file ${e} is missing or has invalid 'agentId' (expected non-empty string).`);Xt(r);let o=t.agentToken;if(typeof o!="string"||o==="")throw new p(`[state-file] State file ${e} is missing or has invalid 'agentToken' (expected non-empty string).`);Ge(o);let s=t.protocolVersion;if(typeof s!="number"||!Number.isInteger(s))throw new p(`[state-file] State file ${e} is missing or has invalid 'protocolVersion' (expected integer).`);zt(s);let a=t.serverUrl;if(typeof a!="string"||a==="")throw new p(`[state-file] State file ${e} is missing or has invalid 'serverUrl' (expected non-empty string).`);try{ee(a)}catch(l){throw new p(`[state-file] State file ${e} has an invalid 'serverUrl': ${String(l)}`)}return{agentId:r,agentToken:o,protocolVersion:s,serverUrl:a,tokenRotatedAt:ya(t,e)}}i(wa,"validateState");function ya(n,e){let t=n.tokenRotatedAt;if(t==null)return null;if(typeof t!="string"||t==="")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 t}i(ya,"readTokenRotatedAt");var hr=m("token-store");function F(n){return mr(n)}i(F,"loadAgentIdentity");function pe(n,e){pr(n,e)}i(pe,"saveAgentIdentity");function gr(n){let e=et(n),t=en(n),r=fr(t,"temporary state file"),o=fr(e,"identity");if(!o&&!r){hr.info("Agent identity wipe: no state file to remove",{filePath:e,tmpPath:t});return}hr.warn("Agent identity wiped \u2014 this agent was revoked and must be re-enrolled",{filePath:e,tmpPath:t,removedState:o,removedTmp:r})}i(gr,"wipeAgentIdentity");function fr(n,e){try{return _a(n),!0}catch(t){if(Ea(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(fr,"removeCredentialFile");function Ea(n){return n.code==="ENOENT"}i(Ea,"isFileNotFound");var wr="extension-bundle.json";function tt(n,e){return yr(n)===yr(e)}i(tt,"isSameDeployment");function yr(n){let e=new URL(n);return`${e.origin}${e.pathname.replace(/\/+$/,"")}`}i(yr,"normalizeDeployment");function _r(n){let{envUrl:e,envTokenPresent:t,stateDir:r}=n;if(e!==void 0)return ee(e),{url:e,source:"env"};if(t){let a=Qt();if(a!==null)return{url:a,source:"bundle"};throw new p(`[config] PROGON_SERVER_URL is not set, and PROGON_AGENT_TOKEN names no deployment \u2014 a pgat_ token is only meaningful at the backend that minted it, and this daemon will not guess which one that is.
|
|
9
|
+
This build carries no ${wr} either, so it was not built for a particular deployment \u2014 that is what a source checkout is, and an installed progon-agent from npm always has one.
|
|
10
10
|
The state file in ${r} is deliberately NOT consulted on this path: PROGON_AGENT_TOKEN is the rotation and recovery mechanism, and it must not start depending on the very file an operator sets it to recover from.
|
|
11
11
|
Set PROGON_SERVER_URL to the deployment this token belongs to; or unset PROGON_AGENT_TOKEN, after which an enrolled machine takes both its credential and its server from that state file.
|
|
12
|
-
See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`)}let o=F(r);if(o!==null)return{url:o.serverUrl,source:"state_file"};let
|
|
13
|
-
PROGON_SERVER_URL is not set; there is no state file in ${r}; and this build carries no ${
|
|
12
|
+
See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`)}let o=F(r);if(o!==null)return{url:o.serverUrl,source:"state_file"};let s=Qt();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.
|
|
13
|
+
PROGON_SERVER_URL is not set; there is no state file in ${r}; and this build carries no ${wr}, so it was not built for a particular deployment \u2014 that is what a source checkout is, and an installed progon-agent from npm always has one.
|
|
14
14
|
Enroll this machine \u2014 'progon-agent enroll --server <url>' (approved in a browser), or 'progon-agent enroll <code> --server <url>' with a code from Progon (Settings \u2192 Agents). Enrollment persists the server together with the credential, so every later command finds it with no environment at all.
|
|
15
15
|
If this machine WAS enrolled with PROGON_RUNNER_STATE_DIR set, set the same variable again \u2014 that directory is where its credential and its server are.
|
|
16
16
|
Setting PROGON_SERVER_URL on its own names a server but no agent: it is what an 'enroll' needs, and it is enough for 'start' only alongside PROGON_AGENT_TOKEN.
|
|
17
|
-
See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`)}i(
|
|
18
|
-
`)}i(
|
|
17
|
+
See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`)}i(_r,"resolveServerUrl");function Ue(n){let e=process.env[n];return e!==void 0&&e!==""?e:void 0}i(Ue,"getOptional");function Er(n,e){let t=process.env[n];if(t===void 0||t==="")return e;let r=t.trim().toLowerCase();if(r==="true"||r==="1")return!0;if(r==="false"||r==="0")return!1;throw new p(`[config] Environment variable ${n} must be one of true/false/1/0, got: ${JSON.stringify(t)}. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`)}i(Er,"getOptionalBool");var rt="progon-agent";function Ra(n,e,t){if(t==="")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(n){case"darwin":return nt(t,"Library","Application Support",rt);case"linux":{let r=e.XDG_STATE_HOME;if(r===void 0||r==="")return nt(t,".local","state",rt);if(!Sr(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 nt(r,rt)}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 nt(r,rt)}default:throw new p(`[config] No default state directory is defined for platform ${JSON.stringify(n)} (supported: darwin, linux, win32 \u2014 CONTRACT-la \xA75.1, \xA710.3). Set PROGON_RUNNER_STATE_DIR explicitly.`)}}i(Ra,"resolveDefaultStateDir");function he(){nr(process.env),sr(process.env);let n=process.env.PROGON_AGENT_TOKEN;if(n==="")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=n;e!==void 0&&Ge(e);let t=Ue("PROGON_RUNNER_STATE_DIR")??Ra(process.platform,process.env,Sa()),r=_r({envUrl:Ue("PROGON_SERVER_URL"),envTokenPresent:e!==void 0,stateDir:t}),o=Ue("PROGON_AGENT_EXTENSION_DIST");if(o!==void 0&&!Sr(o))throw new p(`[config] PROGON_AGENT_EXTENSION_DIST must be an absolute path, got: ${JSON.stringify(o)}. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`);let s=Ue("PROGON_AGENT_ENROLL_CODE");if(s!==void 0&&s.length<32)throw new p(`[config] PROGON_AGENT_ENROLL_CODE is shorter than the ${32} characters an enrollment code has (got ${s.length}). Copy the whole code from the agent's enrollment dialog. See docs/working/local-agent-v1/CONTRACT-la.md \xA75.1.`);return{serverUrl:r.url,serverUrlSource:r.source,initialToken:e,stateDir:t,extensionDistOverride:o,headfulOverride:Er("PROGON_AGENT_HEADFUL",!1),allowInsecureHttps:Er("PROGON_AGENT_ALLOW_INSECURE_HTTPS",!1),enrollmentCode:s,nodeEnv:Ue("NODE_ENV")??"production"}}i(he,"loadConfig");function Me(n,e,t){process.stderr.write(JSON.stringify({level:n,module:"process-guards",msg:e,...t})+`
|
|
18
|
+
`)}i(Me,"writeLine");function br(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(br,"describeError");function Rr(n,e,t){Me("fatal",`Unhandled ${n} \u2014 terminating the daemon`,{event:n,...br(e),...t})}i(Rr,"writeFatalLine");function kr(){process.on("uncaughtException",(n,e)=>{Rr("uncaughtException",n,{origin:e}),process.exit(1)}),process.on("unhandledRejection",n=>{Rr("unhandledRejection",n,{}),process.exit(1)})}i(kr,"installProcessGuards");function vr(n){let e=!1,t=i(r=>{if(e){Me("info","Shutdown already in progress \u2014 signal ignored",{signal:r});return}e=!0,Me("info","Signal received \u2014 shutting down",{signal:r}),(async()=>{try{await n(r)}catch(o){Me("fatal","Shutdown hook failed \u2014 the daemon may leave resources behind",{signal:r,...br(o)}),process.exit(1)}Me("info","Shutdown complete",{signal:r}),process.exit(0)})()},"handle");process.on("SIGTERM",t),process.on("SIGINT",t)}i(vr,"installShutdownHandlers");import{chmodSync as ba,cpSync as ka,mkdirSync as va,readdirSync as Ta,renameSync as Ia,rmSync as nn,statSync as Tr,writeFileSync as xa}from"node:fs";import{dirname as Aa,join as fe}from"node:path";import{fileURLToPath as Oa}from"node:url";var ot=m("extension-dist"),Na="extension-dist",xr="extension-dist",Ar=`${xr}.tmp-`,rn="agent-manifest.json",Ir="manifest.json";function Pa(){return Ze(Aa(Oa(import.meta.url)))}i(Pa,"packageRoot");function Ca(){return Da(fe(Pa(),Na))}i(Ca,"resolveBundledExtensionSource");function Da(n){let e;try{e=Tr(n)}catch(r){throw te(r)?new Error(tn(n,"the directory does not exist"),{cause:r}):r}if(!e.isDirectory())throw new Error(tn(n,"that path is not a directory"));let t=fe(n,Ir);try{Tr(t)}catch(r){throw te(r)?new Error(tn(n,`it holds no ${Ir}`),{cause:r}):r}return n}i(Da,"assertBundledExtensionSource");function tn(n,e){return`[extension-dist] No extension dist is bundled in this package (${n}): ${e}.
|
|
19
19
|
This package was built WITHOUT the bundling step. Run 'npm run bundle:extension' in the agent package (it copies a built qa-extension dist in; set PROGON_EXTENSION_DIST_SRC to point at that dist if it is not the sibling checkout), then reinstall or restart the daemon.
|
|
20
|
-
For a dev or E2E stand you can instead set PROGON_AGENT_EXTENSION_DIST to an already agent-mode dist, which bypasses the bundled copy entirely (CONTRACT-la \xA78).`}i(
|
|
21
|
-
`,"utf8")}i(
|
|
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 ds({stateDir:t.stateDir,agentId:t.agentId})}i(Sr,"resolveExtensionDist");import{fetch as hs}from"undici";var k=class extends Error{static{i(this,"GatewayError")}operation;constructor(e,n,r){super(n,{cause:r}),this.name=new.target.name,this.operation=e}},j=class extends k{static{i(this,"GatewayTransportError")}constructor(e,n,r){super(e,`[gateway] ${e} failed before a response was received: ${n}`,r)}},b=class extends k{static{i(this,"GatewayHttpError")}status;errorCode;params;constructor(e,n,r,o,a){super(e,`[gateway] ${e} refused with HTTP ${n}: ${a}`),this.status=n,this.errorCode=r,this.params=o}},pe=class extends b{static{i(this,"GatewayUnauthorizedError")}},T=class extends b{static{i(this,"TokenSupersededError")}},E=class extends k{static{i(this,"TerminalSignalError")}signal;constructor(e,n,r){super(e,`[gateway] agent revoked (${n}) during ${e}: ${r}`),this.signal=n}},et=class extends b{static{i(this,"EnrollmentCodeRejectedError")}},Ce=class extends b{static{i(this,"ProtocolVersionMismatchError")}},he=class extends b{static{i(this,"RunNotClaimableError")}},te=class extends b{static{i(this,"RunNotFoundError")}},B=class extends k{static{i(this,"GatewayResponseSchemaError")}constructor(e,n,r){super(e,`[gateway] ${e} returned a body that violates the contract: ${n}`,r)}};var Rr=u("gateway-http");async function ne(t){let e={accept:"application/json"};t.agentToken!==null&&(e.authorization=`Bearer ${t.agentToken}`),t.body!==null&&(e["content-type"]="application/json"),Rr.debug("Gateway request",{operation:t.operation,method:t.method,url:t.url.toString()});let n;try{n=await t.fetchImpl(t.url,{method:t.method,headers:e,body:t.body===null?void 0:JSON.stringify(t.body),signal:t.signal})}catch(o){throw new j(t.operation,br(o),o)}let r;try{r=await n.text()}catch(o){throw new j(t.operation,br(o),o)}if(!n.ok){let o=ms(n.status,r);throw Rr.debug("Gateway request refused",{operation:t.operation,status:o.status,errorCode:o.errorCode}),t.mapHttpError(o)}try{return JSON.parse(r)}catch(o){throw new B(t.operation,`the ${n.status} response body is not valid JSON`,o)}}i(ne,"executeGatewayRequest");function C(t,e){if(e.success)return e.data;throw new B(t,ps(e.error),e.error)}i(C,"parseGatewayBody");function ms(t,e){let n;try{n=JSON.parse(e)}catch{return{status:t,errorCode:null,params:null,message:zt}}if(typeof n!="object"||n===null||Array.isArray(n))return{status:t,errorCode:null,params:null,message:zt};let r=n,o=r.error_code,a=r.params,s=r.message;return{status:t,errorCode:typeof o=="string"?o:null,params:typeof a=="object"&&a!==null&&!Array.isArray(a)?a:null,message:typeof s=="string"?$(s):zt}}i(ms,"readErrorEnvelope");var zt="the response body carried no Progon error envelope";function br(t){return $(t instanceof Error?t.message:String(t))}i(br,"describeCause");function ps(t){let e=t.issues;if(!Array.isArray(e)||e.length===0)return"the response body failed schema validation (the validator reported no issue list)";let n=e.map(r=>{let o=r.path;return!Array.isArray(o)||o.length===0?"<root>":o.map(a=>String(a)).join(".")});return`${e.length} schema violation(s) at: ${n.join(", ")}`}i(ps,"summarizeSchemaViolation");var fe=class extends b{static{i(this,"EnrollmentSlowDownError")}retryAfterSec;constructor(e,n,r,o,a,s){super(e,n,r,o,a),this.retryAfterSec=s}},ge=class extends b{static{i(this,"EnrollmentAccessDeniedError")}},we=class extends b{static{i(this,"EnrollmentRequestExpiredError")}},ye=class extends b{static{i(this,"EnrollmentAlreadyCompletedError")}},_e=class extends b{static{i(this,"EnrollmentRequestInvalidError")}};function kr(t){return t.status===401&&t.errorCode==="agent_enroll.invalid_code"?N(et,"enroll",t):t.status===409&&t.errorCode==="agent_enroll.protocol_version"?N(Ce,"enroll",t):G("enroll",t)}i(kr,"mapEnrollError");function Tr(t){return t.status===409&&t.errorCode==="agent_enroll.protocol_version"?N(Ce,"enrollment_request_create",t):G("enrollment_request_create",t)}i(Tr,"mapEnrollmentRequestCreateError");function vr(t){if(t.status===429&&t.errorCode==="agent_enroll.slow_down"){let e=t.params===null?void 0:t.params.retryAfterSeconds,n=typeof e=="number"&&Number.isFinite(e)&&e>0?e:null;return new fe("enrollment_request_poll",t.status,t.errorCode,t.params,t.message,n)}return t.status===403&&t.errorCode==="agent_enroll.access_denied"?N(ge,"enrollment_request_poll",t):t.status===410&&t.errorCode==="agent_enroll.expired"?N(we,"enrollment_request_poll",t):t.status===410&&t.errorCode==="agent_enroll.already_completed"?N(ye,"enrollment_request_poll",t):t.status===401&&t.errorCode==="agent_enroll.invalid_request"?N(_e,"enrollment_request_poll",t):G("enrollment_request_poll",t)}i(vr,"mapEnrollmentRequestPollError");function Ar(t){return G("enrollment_request_cancel",t)}i(Ar,"mapEnrollmentRequestCancelError");function xr(t){return Ee("poll_desired_state",t,()=>G("poll_desired_state",t))}i(xr,"mapPollDesiredStateError");function Ir(t){return Ee("claim",t,()=>t.status===409&&t.errorCode==="run.not_claimable"?N(he,"claim",t):t.status===404?N(te,"claim",t):G("claim",t))}i(Ir,"mapClaimError");function Or(t){return Ee("fail",t,()=>t.status===404?N(te,"fail",t):G("fail",t))}i(Or,"mapFailError");function Nr(t){return Ee("token_status",t,()=>G("token_status",t))}i(Nr,"mapTokenStatusError");function Pr(t){return Ee("token_rotate",t,()=>G("token_rotate",t))}i(Pr,"mapTokenRotateError");function Cr(t){return Ee("declare_capabilities",t,()=>G("declare_capabilities",t))}i(Cr,"mapDeclareCapabilitiesError");function Ee(t,e,n){return e.status===403&&e.errorCode==="agents.revoked"?new E(t,"http_403_agents_revoked",e.message):e.status===401&&e.errorCode==="agents.token_superseded"?N(T,t,e):e.status===401?N(pe,t,e):n()}i(Ee,"bearerRoute");function N(t,e,n){return new t(e,n.status,n.errorCode,n.params,n.message)}i(N,"named");function G(t,e){return N(b,t,e)}i(G,"generic");var tt=[...fn,gn,yn,wn,_n,En];import{z as re}from"zod";var Dr=re.object({rotationDue:re.boolean(),tokenRotatedAt:re.string().nullable(),anchorAt:re.string(),intervalDays:re.number().int()}),Lr=re.object({agentToken:re.string().regex(ae)});var nt=u("gateway-client"),fs="/api/agent-gateway";function D(t,e){return new URL(`${t.replace(/\/+$/,"")}${fs}${e}`)}i(D,"buildGatewayUrl");var Gr=3e5,Mr=1e4,Ur={headersTimeout:Gr,bodyTimeout:Gr,connect:{timeout:Mr}};function gs(){let t=Xn(process.env);return Hn(Vt(process.env),t===void 0?Ur:{...Ur,connect:{timeout:Mr,ca:t}},t)}i(gs,"buildGatewayDispatcher");var Zt,it=i((t,e)=>{if(Zt===void 0){let n=gs();Zt=i((r,o)=>hs(r,{...o,dispatcher:n}),"defaultGatewayFetch")}return Zt(t,e)},"pinnedGatewayFetch"),rt=class{static{i(this,"GatewayEnrollmentClient")}serverUrl;machine;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.machine=e.machine,this.fetchImpl=e.fetchImpl??it}async enroll(e){let n={...this.machine,enrollmentCode:e,protocolVersion:1},r=await ne({operation:"enroll",method:"POST",url:D(this.serverUrl,"/enroll"),agentToken:null,body:n,signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:kr}),o=C("enroll",je.safeParse(r));return nt.info("Agent enrolled",{agentId:o.agentId,pollWaitSec:o.pollWaitSec,protocolVersion:o.protocolVersion}),o}},ot=class{static{i(this,"GatewayClient")}serverUrl;agentToken;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.agentToken=e.agentToken,this.fetchImpl=e.fetchImpl??it}async authenticatedRequest(e){return ne({operation:e.operation,method:e.method,url:e.url,agentToken:this.agentToken,body:e.body,signal:e.signal,fetchImpl:this.fetchImpl,mapHttpError:e.mapHttpError})}async pollDesiredState(e){let n=D(this.serverUrl,"/state");e?.waitSec!==void 0&&n.searchParams.set("waitSec",String(e.waitSec));let r=await this.authenticatedRequest({operation:"poll_desired_state",method:"GET",url:n,body:null,signal:e?.signal,mapHttpError:xr}),o=C("poll_desired_state",Nn.safeParse(r));if(o.agent.revoked)throw new E("poll_desired_state","desired_state_snapshot","the desired-state snapshot reports this agent as revoked");return o}async claimRun(e){let n=await this.authenticatedRequest({operation:"claim",method:"POST",url:D(this.serverUrl,`/runs/${encodeURIComponent(e)}/claim`),body:{capabilities:tt},signal:void 0,mapHttpError:Ir});return C("claim",Ln.safeParse(n))}async failRun(e,n){let r=await this.authenticatedRequest({operation:"fail",method:"POST",url:D(this.serverUrl,`/runs/${encodeURIComponent(e)}/fail`),body:n,signal:void 0,mapHttpError:Or}),o=C("fail",Dn.safeParse(r));return nt.info("Reported run failure to the gateway",{runId:e,reason:n.reason,status:o.status}),o}async getTokenRotationStatus(e){let n=await this.authenticatedRequest({operation:"token_status",method:"GET",url:D(this.serverUrl,"/token"),body:null,signal:e?.signal,mapHttpError:Nr});return C("token_status",Dr.safeParse(n))}async rotateToken(e){let n=await this.authenticatedRequest({operation:"token_rotate",method:"POST",url:D(this.serverUrl,"/token/rotate"),body:null,signal:e?.signal,mapHttpError:Pr});return C("token_rotate",Lr.safeParse(n))}async declareCapabilities(e){await this.authenticatedRequest({operation:"declare_capabilities",method:"POST",url:D(this.serverUrl,"/capabilities"),body:{capabilities:tt},signal:e?.signal,mapHttpError:Cr}),nt.info("Capabilities declared",{capabilities:tt})}useAgentToken(e){this.agentToken=e,nt.info("Adopted a rotated agent token for all subsequent gateway requests")}};var ws=u("debug-env-guard"),ys=["pw:protocol","pw:api"];function _s(t){return t.replace(/[\\^$.|?+()[\]{}]/g,"\\$&")}i(_s,"escapeRegExp");function $r(t){if(t.startsWith("-"))return!1;let e=`^${t.split("*").map(_s).join(".*?")}$`,n=new RegExp(e);return ys.some(r=>n.test(r))}i($r,"enablesPlaywright");function Es(){let t=process.env.DEBUG;if(t===void 0||t==="")return[];let e=t.split(/[\s,]+/).map(o=>o.trim()).filter(o=>o!==""),n=e.filter(o=>$r(o));if(n.length===0)return[];let r=e.filter(o=>!$r(o));return r.length===0?delete process.env.DEBUG:process.env.DEBUG=r.join(","),ws.warn("Playwright debug namespaces removed from DEBUG before playwright-core loaded",{removed:n,kept:r,debugFile:process.env.DEBUG_FILE??null,reason:"pw: namespaces write raw CDP messages \u2014 including the per-run session tokens sent to chrome.storage.local \u2014 to a sink that bypasses log redaction (CONTRACT-la \xA79, \xA711.10)"}),n}i(Es,"sanitizePlaywrightDebugEnv");Es();import{statSync as Br}from"node:fs";import{isAbsolute as Rs,join as bs}from"node:path";import{createRequire as Ss}from"node:module";var W=Ss(import.meta.url)("playwright-core"),at=W.chromium,ip=W.firefox,ap=W.webkit,sp=W.selectors,lp=W.devices,Fr=W.errors,dp=W.request,cp=W._electron,up=W._android;var st="chromium";var jr="instances",lt="instance.json";var ks=["--disable-backgrounding-occluded-windows","--disable-renderer-backgrounding"];async function Wr(t){return at.launchPersistentContext(t.userDataDir,{headless:!t.headful,channel:st,ignoreHTTPSErrors:t.allowInsecureHttps,args:[`--disable-extensions-except=${t.extensionDist}`,`--load-extension=${t.extensionDist}`,"--no-first-run","--no-default-browser-check",...t.keepBackgroundWindowsRendering?ks:[]]})}i(Wr,"launchExtensionContext");function Ts(t){let e=t.browser();if(e===null)throw new Error("context.browser() returned null for a persistent context \u2014 the browser handle is unusable, so neither its PID nor its version can be read");return e}i(Ts,"requireBrowser");function qr(t){return Ts(t).version()}i(qr,"readChromeVersion");async function Vr(t,e){let n,r=new Promise(o=>{n=setTimeout(()=>o({settled:"timeout"}),e)});try{return await Promise.race([t.close().then(()=>({settled:"closed"}),o=>({settled:"rejected",error:o})),r])}finally{n!==void 0&&clearTimeout(n)}}i(Vr,"raceClose");function Hr(t){if(!Rs(t))throw new Error(`[runtime] The extension dist path must be absolute, got ${JSON.stringify(t)}. A relative path would be resolved against the daemon's working directory.`);let e;try{e=Br(t)}catch(r){throw new Error(`[runtime] The extension dist directory ${t} cannot be read. Chromium does NOT fail on a bad --load-extension: it would start without the extension and every run would time out in the readiness probe. Check PROGON_AGENT_EXTENSION_DIST (CONTRACT-la \xA78).`,{cause:r})}if(!e.isDirectory())throw new Error(`[runtime] The extension dist path ${t} is not a directory.`);let n=bs(t,"manifest.json");try{Br(n)}catch(r){throw new Error(`[runtime] ${n} is missing, so ${t} is not a built extension. Build qa-extension, or point PROGON_AGENT_EXTENSION_DIST at a real dist.`,{cause:r})}}i(Hr,"assertUsableExtensionDist");var vs=u("worker-evaluate"),Qt=class extends Error{static{i(this,"EvaluateDeadlineError")}operation;timeoutMs;constructor(e,n){super(`[runtime] ${e}: the extension service worker did not answer worker.evaluate within ${n}ms \u2014 the worker is wedged or gone`),this.name="EvaluateDeadlineError",this.operation=e,this.timeoutMs=n}};async function H(t){let e=t.evaluate(),n=!1;e.catch(a=>{n&&vs.warn("An abandoned worker.evaluate rejected after its deadline had passed",{operation:t.operation,timeoutMs:t.timeoutMs,err:a instanceof Error?a.message:String(a)})});let r,o=new Promise((a,s)=>{r=setTimeout(()=>{n=!0,s(new Qt(t.operation,t.timeoutMs))},t.timeoutMs)});try{return await Promise.race([e,o])}finally{r!==void 0&&clearTimeout(r)}}i(H,"evaluateWithDeadline");var Kr="accessToken",Jr="refreshToken";async function Xr(t,e){await H({operation:"write the run session into chrome.storage.local",timeoutMs:1e4,evaluate:i(()=>t.evaluate(([r,o,a,s])=>new Promise(d=>chrome.storage.local.set({[r]:a,[o]:s},()=>d())),[Kr,Jr,e.accessToken,e.refreshToken]),"evaluate")});let n=await H({operation:"read the run session back out of chrome.storage.local",timeoutMs:1e4,evaluate:i(()=>t.evaluate(([r,o])=>new Promise(a=>chrome.storage.local.get([r,o],s=>{let d=s[r],c=s[o];a({accessTokenLength:typeof d=="string"?d.length:null,refreshTokenLength:typeof c=="string"?c.length:null})})),[Kr,Jr]),"evaluate")});if(n.accessTokenLength!==e.accessToken.length||n.refreshTokenLength!==e.refreshToken.length)throw new Error(`run-session read-back mismatch: chrome.storage.local holds accessToken(len=${String(n.accessTokenLength)}), refreshToken(len=${String(n.refreshTokenLength)}) but ${e.accessToken.length}/${e.refreshToken.length} were written`);return n}i(Xr,"seedRunSession");function Yr(t){return JSON.stringify(Object.keys(t).sort().map(e=>[e,t[e]]))}i(Yr,"canonicalise");async function zr(t,e){await H({operation:`write the command envelope to chrome.storage.local['${Ie}']`,timeoutMs:1e4,evaluate:i(()=>t.evaluate(([a,s])=>new Promise(d=>chrome.storage.local.set({[a]:s},()=>d())),[Ie,e]),"evaluate")});let n=await H({operation:"read the command envelope back out of chrome.storage.local",timeoutMs:1e4,evaluate:i(()=>t.evaluate(a=>new Promise(s=>chrome.storage.local.get([a],d=>{let c=d[a];s(c===void 0?null:c)})),Ie),"evaluate")});if(typeof n!="object"||n===null)throw new Error(`command envelope read-back returned ${JSON.stringify(n)} \u2014 chrome.storage.local['${Ie}'] does not hold the envelope`);let r=Yr({...e}),o=Yr(n);if(r!==o)throw new Error(`command envelope read-back mismatch: wrote ${r}, read ${o}`)}i(zr,"seedCommandEnvelope");async function xs(t,e,n){let r=await H({operation:`read chrome.storage.local['${$e}']`,timeoutMs:n,evaluate:i(()=>t.evaluate(a=>new Promise(s=>chrome.storage.local.get([a],d=>{let c=d[a];s(c===void 0?null:c)})),$e),"evaluate")});if(r===null)return{kind:"absent"};let o=Pn.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(xs,"pollCommandAck");async function Zr(t,e,n){let r=Date.now()+n,o="no ack was written";for(;;){let a=r-Date.now();if(a<=0)throw new Error(`no command ack for run ${e} within ${n}ms \u2014 ${o}. chrome.storage.local['${$e}'] is the only success signal (CONTRACT-la \xA75.4).`);let s=t.serviceWorkers()[0];if(s===void 0)o="the context exposed no service worker while polling (evicted, restarting)";else{let d;try{d=await xs(s,e,a)}catch(c){o=`the last poll failed: ${c instanceof Error?c.message:String(c)}`,d={kind:"invalid",detail:o}}if(d.kind==="ack")return d.ack;d.kind!=="absent"&&(o=d.detail)}await new Promise(d=>setTimeout(d,250))}}i(Zr,"waitForCommandAck");import ct from"node:os";import{createRequire as Is}from"node:module";var Qr=Is(import.meta.url);function Os(){let t=Qr.resolve("playwright-core/package.json"),e=Qr(t);if(typeof e!="object"||e===null)throw new Error(`[runtime] ${t} did not parse into an object.`);let n=e.version;if(typeof n!="string"||n==="")throw new Error(`[runtime] ${t} declares no version string.`);return n}i(Os,"readPlaywrightCoreVersion");function eo(t){return{node:process.version,platform:`${ct.platform()} ${ct.release()} ${ct.arch()}`,cpus:ct.cpus().length,playwrightCore:Os(),chromiumExecutable:at.executablePath(),channel:st,extensionDist:t}}i(eo,"buildEnvFingerprint");import{mkdirSync as so,readdirSync as Js,readFileSync as Ys,renameSync as Xs,rmSync as nn,writeFileSync as zs}from"node:fs";import{join as De}from"node:path";var K=class extends Error{static{i(this,"RuntimeLaunchError")}runId;stage;failReason="launch_error";constructor(e,n,r,o){super(`[runtime] launch failed at stage ${n} for run ${e}: ${r}`,{cause:o}),this.name="RuntimeLaunchError",this.runId=e,this.stage=n}};function en(t){let e=new Set,n=t;for(;n instanceof Error&&!e.has(n)&&(e.add(n),n.cause!==void 0);)n=n.cause;return n instanceof Error?n.message:String(n)}i(en,"deepestCauseMessage");var Ns=new Set(["ERR_CONNECTION_REFUSED","ERR_CONNECTION_RESET","ERR_CONNECTION_CLOSED","ERR_CONNECTION_FAILED","ERR_CONNECTION_TIMED_OUT","ERR_ADDRESS_UNREACHABLE","ERR_TIMED_OUT"]),Ps=/\bnet::(ERR_[A-Z0-9_]+)\b/;function to(t){if(Cs(t))return"timeout";let e=Ps.exec(en(t))?.[1];return e===void 0?"other":e==="ERR_NAME_NOT_RESOLVED"?"name_not_resolved":Ns.has(e)?"unreachable":e.startsWith("ERR_CERT_")?"certificate":"other"}i(to,"entryFailureOf");function Cs(t){let e=new Set,n=t;for(;n instanceof Error&&!e.has(n);){if(n instanceof Fr.TimeoutError)return!0;e.add(n),n=n.cause}return!1}i(Cs,"causeChainHasTimeout");var J=class extends Error{static{i(this,"InstanceAlreadyRegisteredError")}runId;userDataDir;constructor(e,n,r){super(`[runtime] refusing to launch run ${e}: instance directory already exists at ${n}. Either this run is already live, or a previous daemon left it behind (the startup sweep clears leftovers \u2014 CONTRACT-la \xA715 A3, gate G-3).`,{cause:r}),this.name="InstanceAlreadyRegisteredError",this.runId=e,this.userDataDir=n}},ut=class extends Error{static{i(this,"RuntimeBusyError")}requestedRunId;activeRunId;constructor(e,n){super(`[runtime] refusing to launch run ${e}: this runtime already owns the browser instance for run ${n}. An agent runs at most one run at a time (CONTRACT-la \xA73.1, \xA715 A3).`),this.name="RuntimeBusyError",this.requestedRunId=e,this.activeRunId=n}};import{execFile as Ls}from"node:child_process";import{promisify as Gs}from"node:util";import{setTimeout as io}from"node:timers/promises";var mt=Gs(Ls),pt={timeout:5e3};function ao(t){if(typeof t!="object"||t===null)return null;let e=t;return typeof e.code!="number"?null:{code:e.code,stdout:typeof e.stdout=="string"?e.stdout:"",stderr:typeof e.stderr=="string"?e.stderr:""}}i(ao,"asExecFailure");function Us(t){let e=[];for(let n of t.split(`
|
|
23
|
-
`)){let r=
|
|
24
|
-
`)){let s
|
|
25
|
-
`)){let r=n.trim().split(/\s+/);if(r.length<3)continue;let[o,a,s]=r,d=Number(o),c=Number(a),g=Number(s);!Number.isInteger(d)||!Number.isInteger(c)||!Number.isInteger(g)||e.push({pid:d,ppid:c,pgid:g})}return e}i(ro,"readProcessTable");function qs(t,e){let n=new Map;for(let c of t){let g=n.get(c.ppid);g===void 0?n.set(c.ppid,[c.pid]):g.push(c.pid)}let r=new Set(e),o=[...e];for(let c=o.pop();c!==void 0;c=o.pop()){let g=n.get(c);if(g!==void 0)for(let y of g)r.has(y)||(r.add(y),o.push(y))}let a=t.find(c=>c.pid===process.pid),s=a===void 0?null:a.pgid,d=new Set;for(let c of t)r.has(c.pid)&&(c.pgid<=0||s!==null&&c.pgid===s||d.add(c.pgid));return r.delete(process.pid),{members:[...r],groups:[...d]}}i(qs,"expandTree");function Vs(t){try{return process.kill(t,"SIGKILL"),"signalled"}catch(e){if(typeof e=="object"&&e!==null&&e.code==="ESRCH")return"already_gone";throw e}}i(Vs,"sigkill");async function ht(t){return process.platform==="win32"?Ks(t):Hs(t)}i(ht,"killProcessTree");async function Hs(t){let e=await Ws(t);if(e.length===0)return{platform:process.platform,userDataDir:t,discoveredPids:[],signalledPids:[],survivorPids:[]};let n=await ro(),{members:r,groups:o}=qs(n,e),a=[];for(let c of r)Vs(c)==="signalled"&&a.push(c);for(let c of o)try{process.kill(-c,"SIGKILL")}catch(g){if(typeof g!="object"||g===null||g.code!=="ESRCH")throw g}await io(500);let s=await ro(),d=new Set(s.map(c=>c.pid));return{platform:process.platform,userDataDir:t,discoveredPids:e,signalledPids:a,survivorPids:r.filter(c=>d.has(c))}}i(Hs,"killProcessTreePosix");async function Ks(t){let e=await no(t),n=[];for(let o of e)try{await mt("taskkill.exe",["/T","/F","/PID",String(o)],pt),n.push(o)}catch(a){let s=ao(a);if(s===null||s.code!==128)throw a}await io(500);let r=await no(t);return{platform:"win32",userDataDir:t,discoveredPids:e,signalledPids:n,survivorPids:r}}i(Ks,"killProcessTreeWin32");var oe=u("instance-registry");function ft(t){return typeof t=="string"&&t!==""}i(ft,"isNonEmptyString");function Zs(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(!ft(n.runId))throw new Error(`[instance-registry] ${e} has a missing or empty runId.`);if(!ft(n.userDataDir))throw new Error(`[instance-registry] ${e} has a missing or empty userDataDir.`);if(!ft(n.startedAt)||!ft(n.deadlineAt))throw new Error(`[instance-registry] ${e} has a missing or empty timestamp field.`);if(typeof n.agentPid!="number"||!Number.isInteger(n.agentPid))throw new Error(`[instance-registry] ${e} has a non-integer agentPid.`);return{v:1,runId:n.runId,agentPid:n.agentPid,userDataDir:n.userDataDir,startedAt:n.startedAt,deadlineAt:n.deadlineAt}}i(Zs,"parseInstanceRecord");function Qs(t,e){let n=`${t}.tmp`;zs(n,JSON.stringify(e,null,2),{encoding:"utf8",mode:384}),Xs(n,t)}i(Qs,"writeMarkerAtomically");var gt=class{static{i(this,"InstanceRegistry")}#e;constructor(e){this.#e=De(e,jr)}get instancesRoot(){return this.#e}userDataDirFor(e){return De(this.#e,e)}reserve(e,n){so(this.#e,{recursive:!0,mode:448});let r=this.userDataDirFor(e);try{so(r,{recursive:!1,mode:448})}catch(a){throw typeof a=="object"&&a!==null&&a.code==="EEXIST"?new J(e,r,a):a}let o=new Date().toISOString();try{Qs(De(r,lt),{v:1,runId:e,agentPid:process.pid,userDataDir:r,startedAt:o,deadlineAt:n})}catch(a){try{nn(r,{recursive:!0,force:!0})}catch(s){oe.error("Failed to roll back the instance directory after a failed reservation",{runId:e,userDataDir:r,err:s instanceof Error?s.message:String(s)})}throw a}return oe.info("Instance reserved",{runId:e,userDataDir:r,deadlineAt:n}),{runId:e,userDataDir:r,startedAt:o,deadlineAt:n}}read(e){return this.#n(De(this.userDataDirFor(e),lt))}release(e){let n=this.userDataDirFor(e);nn(n,{recursive:!0,force:!0}),oe.info("Instance released",{runId:e,userDataDir:n})}listRunIds(){let e;try{e=Js(this.#e,{withFileTypes:!0})}catch(n){if(typeof n=="object"&&n!==null&&n.code==="ENOENT")return[];throw n}return e.filter(n=>n.isDirectory()).map(n=>n.name)}async sweepOrphans(){let e=new Date().toISOString(),n=[];for(let r of this.listRunIds())n.push(await this.#t(r));return n.length>0?oe.warn("Startup sweep found leftover browser instances",{instancesRoot:this.#e,count:n.length,outcomes:n}):oe.info("Startup sweep found no leftover browser instances",{instancesRoot:this.#e}),{scannedAt:e,instancesRoot:this.#e,outcomes:n}}async#t(e){let n=this.userDataDirFor(e),r=De(n,lt),o=null,a;try{o=this.#n(r),a="valid"}catch(d){a=(typeof d=="object"&&d!==null?d.code:null)==="ENOENT"?"missing":"unreadable",oe.warn("Leftover instance marker is unusable \u2014 killing by directory path anyway",{runId:e,userDataDir:n,marker:a,err:d instanceof Error?d.message:String(d)})}let s=await ht(n);return oe.warn("Leftover browser instance swept",{runId:e,userDataDir:n,marker:a,kill:s}),nn(n,{recursive:!0,force:!0}),{runId:e,userDataDir:n,marker:a,record:o,kill:s,removed:!0}}#n(e){let n=Ys(e,"utf8");return Zs(JSON.parse(n),e)}};async function lo(t){let e=new Date().toISOString(),r=t.serviceWorkers()[0];if(r===void 0)return{ok:!1,observedAt:e,reason:"service_worker_absent",detail:"the browser context exposes no service worker \u2014 the extension is not running"};try{let o=await H({operation:`read chrome.storage.session['tabStates'] and ['${Nt}']`,timeoutMs:1e4,evaluate:i(()=>r.evaluate(async a=>{let s=await new Promise(w=>chrome.storage.session.get(["tabStates",a],w)),d=s.tabStates,c=typeof d!="object"||d===null?[]:Object.entries(d).map(([w,p])=>{let R=typeof p=="object"&&p!==null?p.playback:null;if(typeof R!="object"||R===null)return{tabId:w,playback:null};let v=R;return{tabId:w,playback:{runId:typeof v.runId=="string"?v.runId:null,status:typeof v.status=="string"?v.status:null,currentStepIndex:typeof v.currentStepIndex=="number"?v.currentStepIndex:null}}}),g=s[a],y=typeof g!="object"||g===null?null:(()=>{let w=g;return{agentJobId:typeof w.agentJobId=="string"?w.agentJobId:null,updatedAt:typeof w.updatedAt=="string"?w.updatedAt:null}})();return{tabs:c,agentJob:y}},Nt),"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(lo,"probePlaybackSession");async function co(t,e){let r=t.serviceWorkers()[0];return r!==void 0?r:t.waitForEvent("serviceworker",{timeout:e})}i(co,"waitForServiceWorker");async function uo(t,e){let n,r=new Promise((o,a)=>{n=setTimeout(()=>a(new Error(`chrome.runtime.id did not resolve within ${e}ms \u2014 the extension's service worker is not executing`)),e)});try{let o=await Promise.race([t.evaluate(()=>chrome.runtime.id),r]);if(typeof o!="string"||o==="")throw new Error(`chrome.runtime.id returned ${JSON.stringify(o)} \u2014 expected a non-empty extension id`);return o}finally{n!==void 0&&clearTimeout(n)}}i(uo,"readRuntimeId");function wt(t,e){let n=t-Date.now();if(n<=0)throw new Error(`the ${45e3}ms extension readiness budget was already spent before ${e} could run`);return n}i(wt,"remainingBudgetMs");async function po(t){let e=Date.now(),n=e+45e3,r=n-5e3,o=await co(t,Math.min(5e3,wt(r,"the service-worker target wait")));try{let a=await uo(o,wt(r,"the first readiness evaluate"));return{worker:o,extensionId:a,serviceWorkerUrl:o.url(),attempts:1,readyAfterMs:Date.now()-e}}catch(a){let s=await t.newPage();try{let d=await co(t,Math.min(5e3,wt(n,"the retry service-worker target wait"))),c=await uo(d,wt(n,"the retry readiness evaluate"));return{worker:d,extensionId:c,serviceWorkerUrl:d.url(),attempts:2,readyAfterMs:Date.now()-e}}catch(d){let c=a instanceof Error?a.message:String(a),g=d instanceof Error?d.message:String(d);throw new Error(`extension readiness probe failed on both exp5 lanes. Direct attempt: ${c}. Page-open retry: ${g}.`,{cause:d})}finally{await s.close()}}}i(po,"probeExtensionReadiness");var S=u("playwright-execution-runtime"),an=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}},yt=class{static{i(this,"PlaywrightExecutionRuntime")}#e;#t;#n;#o;#a;#s;#r=null;#i=null;#m=!1;#c=null;#l=null;constructor(e){Hr(e.extensionDist),this.#e=e.extensionDist,this.#t=e.headfulOverride,this.#n=e.allowInsecureHttps,this.#o=e.onInstanceLost,this.#a=new gt(e.stateDir),this.#s=eo(e.extensionDist),S.info("Execution runtime constructed",{stateDir:e.stateDir,instancesRoot:this.#a.instancesRoot,headfulOverride:e.headfulOverride,allowInsecureHttps:e.allowInsecureHttps,envFingerprint:this.#s})}getActiveInstance(){let e=this.#r;return e===null?null:{runId:e.runId,userDataDir:e.userDataDir,headful:e.headful,extensionId:e.extensionId,chromeVersion:e.chromeVersion,startedAt:e.startedAt,deadlineAt:e.deadlineAt}}async sweepOrphanInstances(){return this.#a.sweepOrphans()}async probePlaybackSession(){let e=this.#r;return e===null?{ok:!1,observedAt:new Date().toISOString(),reason:"service_worker_absent",detail:"the runtime owns no browser instance"}:lo(e.context)}async startRun(e){let n=this.#r;if(n!==null)throw new ut(e.runId,n.runId);let r=Date.now(),o=new Date(r+e.maxRunDurationSec*1e3).toISOString(),a=await Y(e.runId,"instance_reserve",()=>this.#a.reserve(e.runId,o));this.#l?.runId===e.runId&&(this.#l=null);let s={runId:e.runId,userDataDir:a.userDataDir,context:null,disposeRequested:!1};this.#i=s;let d=this.#h(e),c=e.command.kind==="swarm";S.info("Launching browser for run",{runId:e.runId,headful:d,requestHeadful:e.headful,headfulOverride:this.#t,keepBackgroundWindowsRendering:c,userDataDir:a.userDataDir,maxRunDurationSec:e.maxRunDurationSec,deadlineAt:o,envFingerprint:this.#s});let g=null;try{let y=await Y(e.runId,"browser_launch",()=>Wr({userDataDir:a.userDataDir,extensionDist:this.#e,headful:d,allowInsecureHttps:this.#n,keepBackgroundWindowsRendering:c}));g=y,s.context=y,this.#d(s);let w=await Y(e.runId,"browser_version",()=>qr(y)),p=await Y(e.runId,"readiness_probe",()=>po(y));await this.#f(e,p.worker),await Y(e.runId,"entry_navigation",()=>nl(y,e)),await this.#p(e,y);let R={runId:e.runId,context:g,userDataDir:a.userDataDir,headful:d,extensionId:p.extensionId,chromeVersion:w,startedAt:a.startedAt,deadlineAt:o};this.#d(s),this.#u(R),this.#r=R,this.#i===s&&(this.#i=null),S.info("Run launched",{runId:e.runId,chromeVersion:w,extensionId:p.extensionId,readinessAttempts:p.attempts,readyAfterMs:p.readyAfterMs,launchDurationMs:Date.now()-r})}catch(y){throw this.#i===s&&(this.#i=null),await this.#g({runId:e.runId,context:g,userDataDir:a.userDataDir,timeoutMs:2e4,trigger:s.disposeRequested?"dispose_during_launch":"launch_failure"}),y}finally{this.#i===s&&(this.#i=null)}}async cancelRun(e){await this.disposeRun(e)}async disposeRun(e,n=2e4){let r=this.#c;if(r!==null&&r.runId===e)return S.info("Dispose requested for a lost instance \u2014 joining the teardown already running",{runId:e}),r.promise;let o=this.#i;if(o!==null&&o.runId===e)return o.disposeRequested=!0,S.warn("Dispose requested for a run that is still launching \u2014 aborting the launch",{runId:e,userDataDir:o.userDataDir,contextPresent:o.context!==null}),this.#g({runId:e,context:o.context,userDataDir:o.userDataDir,timeoutMs:n,trigger:"dispose_during_launch"});let a=this.#r;return a===null||a.runId!==e?this.#w(e):(this.#r=null,this.#g({runId:e,context:a.context,userDataDir:a.userDataDir,timeoutMs:n,trigger:"dispose"}))}#h(e){return e.headful||this.#t}async#f(e,n){let r=await Y(e.runId,"token_seed",()=>Xr(n,e.extensionSession));S.info("Run session seeded into the browser profile",{runId:e.runId,accessTokenLength:r.accessTokenLength,refreshTokenLength:r.refreshTokenLength}),await Y(e.runId,"command_seed",()=>zr(n,e.command)),S.info("Command envelope seeded",{runId:e.runId,command:e.command})}async#p(e,n){let r=await Y(e.runId,"command_ack",()=>Zr(n,e.runId,15e3));if(r.outcome==="rejected")throw new K(e.runId,"command_ack",`the extension refused the command envelope: ${r.reason}`);S.info("Command envelope dispatched by the extension",{runId:e.runId})}#d(e){if(e.disposeRequested)throw new an(e.runId)}#u(e){let n=i(o=>{if(this.#m||this.#r?.runId!==e.runId)return;this.#r=null;let a=this.#g({runId:e.runId,context:e.context,userDataDir:e.userDataDir,timeoutMs:2e4,trigger:"instance_lost"});this.#c={runId:e.runId,promise:a},a.catch(d=>{S.error("Teardown after a lost browser instance failed",{runId:e.runId,userDataDir:e.userDataDir,err:d instanceof Error?d.message:String(d)})}).finally(()=>{this.#c?.promise===a&&(this.#c=null)});let s={runId:e.runId,at:new Date().toISOString(),source:o};S.error("Browser instance disappeared without a dispose",{...s}),this.#o(s)},"report");e.context.on("close",()=>n("context_closed"));let r=e.context.browser();r!==null&&r.on("disconnected",()=>n("browser_disconnected"))}#w(e){let n=this.#l;if(n===null||n.runId!==e)return S.info("Dispose requested for a run this runtime does not own \u2014 no-op",{requestedRunId:e,activeRunId:this.#r===null?null:this.#r.runId,disposeOutcome:"closed"}),{runId:e,outcome:"closed",kill:null,instanceReleased:!1,durationMs:0};if(n.result.instanceReleased)return S.info("Dispose repeated for a run already torn down \u2014 replaying its outcome",{runId:e,disposeOutcome:n.result.outcome,instanceReleased:!0}),n.result;if(!n.killConfirmed)throw S.error("Dispose repeated for a run whose force-kill was never confirmed \u2014 the instance directory stays for the startup sweep",{runId:e,disposeOutcome:n.result.outcome,kill:n.result.kill,instanceReleased:!1}),new Error(`[runtime] the instance directory for run ${e} is deliberately retained: the force-kill of its process tree was never confirmed, and this runtime does not retry it. The startup sweep (CONTRACT-la \xA715 A3 rule 2) is the next eraser.`);let r=Date.now();S.warn("Dispose repeated for a run whose instance directory survived \u2014 retrying",{runId:e,disposeOutcome:n.result.outcome}),this.#a.release(e);let o={...n.result,instanceReleased:!0,durationMs:Date.now()-r};return this.#l={runId:e,result:o,killConfirmed:!0},S.info("Instance released on a repeated dispose",{runId:e,disposeOutcome:o.outcome,instanceReleased:!0,durationMs:o.durationMs}),o}async#g(e){let n=Date.now();this.#m=!0;let r="closed",o=null,a=null;try{if(e.context!==null){let p=await Vr(e.context,e.timeoutMs);p.settled==="closed"?r="closed":p.settled==="timeout"?(r="timeout-force-killed",S.error("context.close() did not settle before the deadline \u2014 force-killing",{runId:e.runId,timeoutMs:e.timeoutMs,userDataDir:e.userDataDir})):(r="close-failed-force-killed",S.error("context.close() rejected \u2014 force-killing",{runId:e.runId,userDataDir:e.userDataDir,err:p.error instanceof Error?p.error.message:String(p.error)}))}if(r!=="closed"||e.trigger==="instance_lost"||e.trigger==="dispose_during_launch")try{o=await ht(e.userDataDir)}catch(p){a=p,S.error("Force-kill of the run process tree failed",{runId:e.runId,userDataDir:e.userDataDir,trigger:e.trigger,disposeOutcome:r,err:p instanceof Error?p.message:String(p)})}let d=a===null&&(o===null||o.survivorPids.length===0),c=null,g=!1;if(d)try{this.#a.release(e.runId),g=!0}catch(p){c=p,S.error("Failed to remove the instance directory after teardown",{runId:e.runId,userDataDir:e.userDataDir,err:p instanceof Error?p.message:String(p)})}else S.error("Instance directory KEPT \u2014 the force-kill is unconfirmed and the startup sweep must still be able to find this tree",{runId:e.runId,userDataDir:e.userDataDir,disposeOutcome:r,killFailed:a!==null,survivorPids:o===null?null:o.survivorPids});let y={runId:e.runId,outcome:r,kill:o,instanceReleased:g,durationMs:Date.now()-n};this.#l={runId:e.runId,result:y,killConfirmed:d};let w={runId:y.runId,disposeOutcome:y.outcome,trigger:e.trigger,contextPresent:e.context!==null,kill:y.kill,killFailed:a!==null,instanceReleased:y.instanceReleased,durationMs:y.durationMs};if(a!==null||c!==null?S.error("Instance disposed with a failed cleanup step",w):S.info("Instance disposed",w),c!==null)throw c;if(a!==null)throw a;if(o!==null&&o.survivorPids.length>0)throw new Error(`[runtime] force-kill for run ${e.runId} left ${o.survivorPids.length} process(es) alive after the settle delay (${o.survivorPids.join(", ")}). The instance directory ${e.userDataDir} is kept so the startup sweep can re-discover them (CONTRACT-la \xA715 A3 rule 2).`);return y}finally{this.#m=!1}}};async function Y(t,e,n){try{return await n()}catch(r){throw r instanceof K||r instanceof J?r:new K(t,e,r instanceof Error?r.message:String(r),r)}}i(Y,"stage");async function nl(t,e){let n=t.pages()[0];await(n===void 0?await t.newPage():n).goto(e.entryUrl,{waitUntil:"domcontentloaded"})}i(nl,"navigateToEntry");import{setTimeout as ol}from"node:timers/promises";function ie(t,e=Math.random){if(t<0)throw new Error(`[backoff] attempt must be >= 0, got ${t}. Pass 0 for the first reconnect after a disconnect.`);let n=Math.min(6e4,1e3*Math.pow(2,Math.min(t,26)));return Math.floor(e()*n)}i(ie,"computeBackoffDelayMs");function Se(t){let e=rl(t.error);return e!==null?{retry:!1,reason:e}:{retry:!0,delayMs:ie(t.attempt,t.rng)}}i(Se,"decideGatewayRetry");function rl(t){if(t instanceof E)return"terminal_signal";if(t instanceof B)return"contract_breach";if(t instanceof T)return"semantic_refusal";if(t.operation==="claim"||t.operation==="token_rotate")return"one_shot_operation";if(t instanceof j||t instanceof pe)return null;if(t instanceof b)return t.status===429?"rate_limited":t.status>=500?null:"semantic_refusal";throw new Error(`[backoff-policy] No retry row for ${t.name} on operation '${t.operation}'. A new GatewayError subclass was added without extending the decision table in src/gateway/backoff-policy.ts.`)}i(rl,"classifyFailure");var X=u("supervisor-identity");async function Re(t){let{config:e}=t;if(e.initialToken!==void 0)return il(e,e.initialToken);let n=F(e.stateDir);if(n!==null)return dl(n.serverUrl,e.serverUrl),X.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 sl(t,e.enrollmentCode);throw new m(`[progon-agent] This machine has no agent identity, so the daemon cannot start.
|
|
20
|
+
For a dev or E2E stand you can instead set PROGON_AGENT_EXTENSION_DIST to an already agent-mode dist, which bypasses the bundled copy entirely (CONTRACT-la \xA78).`}i(tn,"bundledMissingMessage");function La(n){let{stateDir:e,agentId:t}=n;if(t==="")throw new Error(`[extension-dist] agentId is required: ${rn} carries it (CONTRACT-la \xA71 D-C) and this module does not invent identity.`);let r=n.sourceDir??Ca(),o=fe(e,xr),s=fe(e,`${Ar}${process.pid}`);return va(e,{recursive:!0,mode:448}),Ua(e),nn(s,{recursive:!0,force:!0}),ka(r,s,{recursive:!0}),ba(s,448),Ga(s,t),nn(o,{recursive:!0,force:!0}),Ia(s,o),ot.info("Agent-mode extension dist prepared",{extensionDist:o,sourceDir:r,agentId:t,protocolVersion:1}),o}i(La,"prepareAgentExtensionDist");function Ga(n,e){let t={agentMode:!0,agentId:e,protocolVersion:1};xa(fe(n,rn),JSON.stringify(t,null,2)+`
|
|
21
|
+
`,"utf8")}i(Ga,"writeAgentManifest");function Ua(n){let e;try{e=Ta(n,{withFileTypes:!0})}catch(t){if(typeof t=="object"&&t!==null&&t.code==="ENOENT")return;throw t}for(let t of e){if(!t.name.startsWith(Ar))continue;let r=fe(n,t.name);try{nn(r,{recursive:!0,force:!0}),ot.warn("Removed a leftover extension-dist staging directory",{leftover:r})}catch(o){ot.error("Failed to remove a leftover extension-dist staging directory",{leftover:r,err:o instanceof Error?o.message:String(o)})}}}i(Ua,"removeLeftoverStagingDirs");function Or(n){if(n.overridePath!==void 0)return ot.info("Using the PROGON_AGENT_EXTENSION_DIST override as built",{extensionDist:n.overridePath}),n.overridePath;if(n.agentId===null)throw new Error(`[extension-dist] Cannot prepare the agent-mode extension dist: this daemon authenticated with PROGON_AGENT_TOKEN, which carries no agentId, and ${rn} must name the agent the browser reports as (CONTRACT-la \xA71 D-C).
|
|
22
|
+
Either enroll the agent ('progon-agent enroll <code>'), which persists the identity the server issued, or set PROGON_AGENT_EXTENSION_DIST to a dist that is already in agent mode (dev/E2E path, \xA78).`);return La({stateDir:n.stateDir,agentId:n.agentId})}i(Or,"resolveExtensionDist");import{fetch as Fa}from"undici";var b=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 b{static{i(this,"GatewayTransportError")}constructor(e,t,r){super(e,`[gateway] ${e} failed before a response was received: ${t}`,r)}},R=class extends b{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}},ge=class extends R{static{i(this,"GatewayUnauthorizedError")}},S=class extends R{static{i(this,"TokenSupersededError")}},E=class extends b{static{i(this,"TerminalSignalError")}signal;constructor(e,t,r){super(e,`[gateway] agent revoked (${t}) during ${e}: ${r}`),this.signal=t}},it=class extends R{static{i(this,"EnrollmentCodeRejectedError")}},$e=class extends R{static{i(this,"ProtocolVersionMismatchError")}},we=class extends R{static{i(this,"RunNotClaimableError")}},ne=class extends R{static{i(this,"RunNotFoundError")}},W=class extends b{static{i(this,"GatewayResponseSchemaError")}constructor(e,t,r){super(e,`[gateway] ${e} returned a body that violates the contract: ${t}`,r)}};var Nr=m("gateway-http");async function re(n){let e={accept:"application/json"};n.agentToken!==null&&(e.authorization=`Bearer ${n.agentToken}`),n.body!==null&&(e["content-type"]="application/json"),Nr.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,Pr(o),o)}let r;try{r=await t.text()}catch(o){throw new j(n.operation,Pr(o),o)}if(!t.ok){let o=Ma(t.status,r);throw Nr.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 W(n.operation,`the ${t.status} response body is not valid JSON`,o)}}i(re,"executeGatewayRequest");function P(n,e){if(e.success)return e.data;throw new W(n,$a(e.error),e.error)}i(P,"parseGatewayBody");function Ma(n,e){let t;try{t=JSON.parse(e)}catch{return{status:n,errorCode:null,params:null,message:on}}if(typeof t!="object"||t===null||Array.isArray(t))return{status:n,errorCode:null,params:null,message:on};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):on}}i(Ma,"readErrorEnvelope");var on="the response body carried no Progon error envelope";function Pr(n){return $(n instanceof Error?n.message:String(n))}i(Pr,"describeCause");function $a(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($a,"summarizeSchemaViolation");var ye=class extends R{static{i(this,"EnrollmentSlowDownError")}retryAfterSec;constructor(e,t,r,o,s,a){super(e,t,r,o,s),this.retryAfterSec=a}},_e=class extends R{static{i(this,"EnrollmentAccessDeniedError")}},Ee=class extends R{static{i(this,"EnrollmentRequestExpiredError")}},Se=class extends R{static{i(this,"EnrollmentAlreadyCompletedError")}},Re=class extends R{static{i(this,"EnrollmentRequestInvalidError")}};function Cr(n){return n.status===401&&n.errorCode==="agent_enroll.invalid_code"?O(it,"enroll",n):n.status===409&&n.errorCode==="agent_enroll.protocol_version"?O($e,"enroll",n):L("enroll",n)}i(Cr,"mapEnrollError");function Dr(n){return n.status===409&&n.errorCode==="agent_enroll.protocol_version"?O($e,"enrollment_request_create",n):L("enrollment_request_create",n)}i(Dr,"mapEnrollmentRequestCreateError");function Lr(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 ye("enrollment_request_poll",n.status,n.errorCode,n.params,n.message,t)}return n.status===403&&n.errorCode==="agent_enroll.access_denied"?O(_e,"enrollment_request_poll",n):n.status===410&&n.errorCode==="agent_enroll.expired"?O(Ee,"enrollment_request_poll",n):n.status===410&&n.errorCode==="agent_enroll.already_completed"?O(Se,"enrollment_request_poll",n):n.status===401&&n.errorCode==="agent_enroll.invalid_request"?O(Re,"enrollment_request_poll",n):L("enrollment_request_poll",n)}i(Lr,"mapEnrollmentRequestPollError");function Gr(n){return L("enrollment_request_cancel",n)}i(Gr,"mapEnrollmentRequestCancelError");function Ur(n){return oe("poll_desired_state",n,()=>L("poll_desired_state",n))}i(Ur,"mapPollDesiredStateError");function Mr(n){return oe("claim",n,()=>n.status===409&&n.errorCode==="run.not_claimable"?O(we,"claim",n):n.status===404?O(ne,"claim",n):L("claim",n))}i(Mr,"mapClaimError");function $r(n){return oe("fail",n,()=>n.status===404?O(ne,"fail",n):L("fail",n))}i($r,"mapFailError");function Fr(n){return oe("token_status",n,()=>L("token_status",n))}i(Fr,"mapTokenStatusError");function jr(n){return oe("token_rotate",n,()=>L("token_rotate",n))}i(jr,"mapTokenRotateError");function Wr(n){return oe("declare_capabilities",n,()=>L("declare_capabilities",n))}i(Wr,"mapDeclareCapabilitiesError");function Br(n){return oe("identity_session",n,()=>L("identity_session",n))}i(Br,"mapIdentitySessionError");function oe(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"?O(S,n,e):e.status===401?O(ge,n,e):t()}i(oe,"bearerRoute");function O(n,e,t){return new n(e,t.status,t.errorCode,t.params,t.message)}i(O,"named");function L(n,e){return O(R,n,e)}i(L,"generic");var st=[...Rn,bn,kn,Tn,vn];import{z as ie}from"zod";var Kr=ie.object({rotationDue:ie.boolean(),tokenRotatedAt:ie.string().nullable(),anchorAt:ie.string(),intervalDays:ie.number().int()}),qr=ie.object({agentToken:ie.string().regex(le)});var at=m("gateway-client"),ja="/api/agent-gateway";function C(n,e){return new URL(`${n.replace(/\/+$/,"")}${ja}${e}`)}i(C,"buildGatewayUrl");var Hr=3e5,Jr=1e4,Vr={headersTimeout:Hr,bodyTimeout:Hr,connect:{timeout:Jr}};function Wa(){let n=ir(process.env);return tr(Zt(process.env),n===void 0?Vr:{...Vr,connect:{timeout:Jr,ca:n}},n)}i(Wa,"buildGatewayDispatcher");var sn,ct=i((n,e)=>{if(sn===void 0){let t=Wa();sn=i((r,o)=>Fa(r,{...o,dispatcher:t}),"defaultGatewayFetch")}return sn(n,e)},"pinnedGatewayFetch"),lt=class{static{i(this,"GatewayEnrollmentClient")}serverUrl;machine;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.machine=e.machine,this.fetchImpl=e.fetchImpl??ct}async enroll(e){let t={...this.machine,enrollmentCode:e,protocolVersion:1},r=await re({operation:"enroll",method:"POST",url:C(this.serverUrl,"/enroll"),agentToken:null,body:t,signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:Cr}),o=P("enroll",Ve.safeParse(r));return at.info("Agent enrolled",{agentId:o.agentId,pollWaitSec:o.pollWaitSec,protocolVersion:o.protocolVersion}),o}},dt=class{static{i(this,"GatewayClient")}serverUrl;agentToken;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.agentToken=e.agentToken,this.fetchImpl=e.fetchImpl??ct}async authenticatedRequest(e){return re({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=C(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:Ur}),o=P("poll_desired_state",Mn.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:C(this.serverUrl,`/runs/${encodeURIComponent(e)}/claim`),body:{capabilities:st},signal:void 0,mapHttpError:Mr});return P("claim",Kn.safeParse(t))}async issueIdentitySession(e,t){let r=await this.authenticatedRequest({operation:"identity_session",method:"POST",url:C(this.serverUrl,`/runs/${encodeURIComponent(e)}/identities/${encodeURIComponent(t)}/session`),body:null,signal:void 0,mapHttpError:Br});return P("identity_session",Bn.safeParse(r)).extensionSession}async failRun(e,t){let r=await this.authenticatedRequest({operation:"fail",method:"POST",url:C(this.serverUrl,`/runs/${encodeURIComponent(e)}/fail`),body:t,signal:void 0,mapHttpError:$r}),o=P("fail",jn.safeParse(r));return at.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:C(this.serverUrl,"/token"),body:null,signal:e?.signal,mapHttpError:Fr});return P("token_status",Kr.safeParse(t))}async rotateToken(e){let t=await this.authenticatedRequest({operation:"token_rotate",method:"POST",url:C(this.serverUrl,"/token/rotate"),body:null,signal:e?.signal,mapHttpError:jr});return P("token_rotate",qr.safeParse(t))}async declareCapabilities(e){await this.authenticatedRequest({operation:"declare_capabilities",method:"POST",url:C(this.serverUrl,"/capabilities"),body:{capabilities:st},signal:e?.signal,mapHttpError:Wr}),at.info("Capabilities declared",{capabilities:st})}useAgentToken(e){this.agentToken=e,at.info("Adopted a rotated agent token for all subsequent gateway requests")}};var Ba=m("debug-env-guard"),Ka=["pw:protocol","pw:api"];function qa(n){return n.replace(/[\\^$.|?+()[\]{}]/g,"\\$&")}i(qa,"escapeRegExp");function Yr(n){if(n.startsWith("-"))return!1;let e=`^${n.split("*").map(qa).join(".*?")}$`,t=new RegExp(e);return Ka.some(r=>t.test(r))}i(Yr,"enablesPlaywright");function Ha(){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=>Yr(o));if(t.length===0)return[];let r=e.filter(o=>!Yr(o));return r.length===0?delete process.env.DEBUG:process.env.DEBUG=r.join(","),Ba.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(Ha,"sanitizePlaywrightDebugEnv");Ha();import{statSync as Zr}from"node:fs";import{isAbsolute as Ja,join as Ya}from"node:path";import{createRequire as Va}from"node:module";var B=Va(import.meta.url)("playwright-core"),ut=B.chromium,Qp=B.firefox,eh=B.webkit,th=B.selectors,nh=B.devices,Xr=B.errors,rh=B.request,oh=B._electron,ih=B._android;var mt="chromium";var zr="instances",pt="instance.json";var Xa=["--disable-backgrounding-occluded-windows","--disable-renderer-backgrounding"];async function Qr(n){return ut.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?Xa:[]]})}i(Qr,"launchExtensionContext");function za(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(za,"requireBrowser");function eo(n){return za(n).version()}i(eo,"readChromeVersion");async function to(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(to,"raceClose");function no(n){if(!Ja(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=Zr(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=Ya(n,"manifest.json");try{Zr(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(no,"assertUsableExtensionDist");var Za=m("worker-evaluate"),an=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 J(n){let e=n.evaluate(),t=!1;e.catch(s=>{t&&Za.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 an(n.operation,n.timeoutMs))},n.timeoutMs)});try{return await Promise.race([e,o])}finally{r!==void 0&&clearTimeout(r)}}i(J,"evaluateWithDeadline");var ro="accessToken",oo="refreshToken";async function so(n,e){await J({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())),[ro,oo,e.accessToken,e.refreshToken]),"evaluate")});let t=await J({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})})),[ro,oo]),"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(so,"seedRunSession");function io(n){return JSON.stringify(Object.keys(n).sort().map(e=>[e,n[e]]))}i(io,"canonicalise");async function ao(n,e){await J({operation:`write the command envelope to chrome.storage.local['${Le}']`,timeoutMs:1e4,evaluate:i(()=>n.evaluate(([s,a])=>new Promise(l=>chrome.storage.local.set({[s]:a},()=>l())),[Le,e]),"evaluate")});let t=await J({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)})),Le),"evaluate")});if(typeof t!="object"||t===null)throw new Error(`command envelope read-back returned ${JSON.stringify(t)} \u2014 chrome.storage.local['${Le}'] does not hold the envelope`);let r=io({...e}),o=io(t);if(r!==o)throw new Error(`command envelope read-back mismatch: wrote ${r}, read ${o}`)}i(ao,"seedCommandEnvelope");async function el(n,e,t){let r=await J({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=$n.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(el,"pollCommandAck");async function lo(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 el(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(lo,"waitForCommandAck");import{execFile as nl}from"node:child_process";import{promisify as rl}from"node:util";import{setTimeout as po}from"node:timers/promises";var ft=rl(nl),gt={timeout:5e3};function ho(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(ho,"asExecFailure");function ol(n){let e=[];for(let t of n.split(`
|
|
23
|
+
`)){let r=t.trim();if(r==="")continue;let o=Number(r);!Number.isInteger(o)||o===process.pid||e.push(o)}return e}i(ol,"parsePidLines");var ln="--user-data-dir=",il=new Set([" "," ",'"',"'"]),sl=new Set([" "," ",'"',"'"]);function al(n){return n.replace(/[\\^$.|?*+()[\]{}]/g,"\\$&")}i(al,"escapeEre");function ll(n){return`(^|[[:space:]'"])${al(`${ln}${n}`)}([[:space:]'"]|$)`}i(ll,"buildAnchorPattern");function dl(n,e){let t=n.toLowerCase(),r=`${ln}${e}`.toLowerCase();for(let o=t.indexOf(r);o!==-1;o=t.indexOf(r,o+1)){let s=o===0?void 0:t[o-1],a=t[o+r.length],l=s===void 0||il.has(s),c=a===void 0||sl.has(a);if(l&&c)return!0}return!1}i(dl,"matchesAnchor");async function cl(n){try{let{stdout:e}=await ft("pgrep",["-f",ll(n)],gt);return ol(e)}catch(e){let t=ho(e);if(t!==null&&t.code===1&&t.stdout.trim()==="")return[];throw e}}i(cl,"discoverPosix");async function co(n){let t=`Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Where-Object { $_.ProcessId -ne $PID -and $_.CommandLine -and $_.CommandLine.Contains('${`${ln}${n}`.replace(/'/g,"''")}') } | ForEach-Object { "$($_.ProcessId)\`t$($_.CommandLine)" }`,{stdout:r}=await ft("powershell.exe",["-NoProfile","-NonInteractive","-Command",t],gt),o=[];for(let s of r.split(`
|
|
24
|
+
`)){let a=s.indexOf(" ");if(a===-1)continue;let l=Number(s.slice(0,a).trim()),c=s.slice(a+1);!Number.isInteger(l)||l===process.pid||dl(c,n)&&o.push(l)}return o}i(co,"discoverWin32");async function uo(){let{stdout:n}=await ft("ps",["-A","-o","pid=,ppid=,pgid="],gt),e=[];for(let t of n.split(`
|
|
25
|
+
`)){let r=t.trim().split(/\s+/);if(r.length<3)continue;let[o,s,a]=r,l=Number(o),c=Number(s),w=Number(a);!Number.isInteger(l)||!Number.isInteger(c)||!Number.isInteger(w)||e.push({pid:l,ppid:c,pgid:w})}return e}i(uo,"readProcessTable");function ul(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(ul,"expandTree");function ml(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(ml,"sigkill");async function wt(n){return process.platform==="win32"?hl(n):pl(n)}i(wt,"killProcessTree");async function pl(n){let e=await cl(n);if(e.length===0)return{platform:process.platform,userDataDir:n,discoveredPids:[],signalledPids:[],survivorPids:[]};let t=await uo(),{members:r,groups:o}=ul(t,e),s=[];for(let c of r)ml(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 po(500);let a=await uo(),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(pl,"killProcessTreePosix");async function hl(n){let e=await co(n),t=[];for(let o of e)try{await ft("taskkill.exe",["/T","/F","/PID",String(o)],gt),t.push(o)}catch(s){let a=ho(s);if(a===null||a.code!==128)throw s}await po(500);let r=await co(n);return{platform:"win32",userDataDir:n,discoveredPids:e,signalledPids:t,survivorPids:r}}i(hl,"killProcessTreeWin32");async function fo(n,e){let r=n.serviceWorkers()[0];return r!==void 0?r:n.waitForEvent("serviceworker",{timeout:e})}i(fo,"waitForServiceWorker");async function go(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(go,"readRuntimeId");function yt(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(yt,"remainingBudgetMs");async function yo(n){let e=Date.now(),t=e+45e3,r=t-5e3,o=await fo(n,Math.min(5e3,yt(r,"the service-worker target wait")));try{let s=await go(o,yt(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 fo(n,Math.min(5e3,yt(t,"the retry service-worker target wait"))),c=await go(l,yt(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(yo,"probeExtensionReadiness");var Y=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 cn(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(cn,"deepestCauseMessage");var fl=new Set(["ERR_CONNECTION_REFUSED","ERR_CONNECTION_RESET","ERR_CONNECTION_CLOSED","ERR_CONNECTION_FAILED","ERR_CONNECTION_TIMED_OUT","ERR_ADDRESS_UNREACHABLE","ERR_TIMED_OUT"]),gl=/\bnet::(ERR_[A-Z0-9_]+)\b/;function _o(n){if(wl(n))return"timeout";let e=gl.exec(cn(n))?.[1];return e===void 0?"other":e==="ERR_NAME_NOT_RESOLVED"?"name_not_resolved":fl.has(e)?"unreachable":e.startsWith("ERR_CERT_")?"certificate":"other"}i(_o,"entryFailureOf");function wl(n){let e=new Set,t=n;for(;t instanceof Error&&!e.has(t);){if(t instanceof Xr.TimeoutError)return!0;e.add(t),t=t.cause}return!1}i(wl,"causeChainHasTimeout");var X=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}},_t=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 N=m("browser-instance");async function Et(n){let e=await G(n.runId,"browser_launch",()=>Qr({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",()=>eo(e)),r=await G(n.runId,"readiness_probe",()=>yo(e));return await _l(n,r.worker),await G(n.runId,"entry_navigation",()=>Rl(e,n.entryUrl)),await El(n,e),{context:e,chromeVersion:t,extensionId:r.extensionId,readinessAttempts:r.attempts,readyAfterMs:r.readyAfterMs}}i(Et,"bringUpBrowser");async function _l(n,e){let t=await G(n.runId,"token_seed",()=>so(e,n.extensionSession));N.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",()=>ao(e,n.command)),N.info("Command envelope seeded",{runId:n.runId,userDataDir:n.userDataDir,command:n.command})}i(_l,"seed");async function El(n,e){let t=await G(n.runId,"command_ack",()=>lo(e,n.runId,15e3));if(t.outcome==="rejected")throw new Y(n.runId,"command_ack",`the extension refused the command envelope: ${t.reason}`);N.info("Command envelope dispatched by the extension",{runId:n.runId,userDataDir:n.userDataDir,kind:n.command.kind})}i(El,"awaitDispatchAck");async function Fe(n,e){let t=Date.now(),r="closed",o=null,s=null;if(e.context!==null){let h=await to(e.context,e.timeoutMs);h.settled==="closed"?r="closed":h.settled==="timeout"?(r="timeout-force-killed",N.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",N.error("context.close() rejected \u2014 force-killing",{runId:e.instanceKey,userDataDir:e.userDataDir,err:h.error instanceof Error?h.error.message:String(h.error)}))}if(r!=="closed"||e.trigger==="instance_lost"||e.trigger==="dispose_during_launch")try{o=await wt(e.userDataDir)}catch(h){s=h,N.error("Force-kill of the run process tree failed",{runId:e.instanceKey,userDataDir:e.userDataDir,trigger:e.trigger,disposeOutcome:r,err:h instanceof Error?h.message:String(h)})}let l=s===null&&(o===null||o.survivorPids.length===0),c=null,w=!1;if(l)try{n.release(e.instanceKey),w=!0}catch(h){c=h,N.error("Failed to remove the instance directory after teardown",{runId:e.instanceKey,userDataDir:e.userDataDir,err:h instanceof Error?h.message:String(h)})}else N.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?N.error("Instance disposed with a failed cleanup step",g):N.info("Instance disposed",g),{result:f,killConfirmed:l,failure:Sl(e,o,s,c)}}i(Fe,"tearDownBrowser");function St(n,e){let{instanceKey:t}=e;if(!e.killConfirmed)throw N.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();N.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 N.info("Instance released on a repeated dispose",{runId:t,disposeOutcome:o.outcome,instanceReleased:!0,durationMs:o.durationMs}),o}i(St,"retryRetainedRelease");function Sl(n,e,t,r){return r!==null?Eo(r):t!==null?Eo(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(Sl,"teardownFailure");function Eo(n){return n instanceof Error?n:new Error(String(n))}i(Eo,"asError");async function G(n,e,t){try{return await t()}catch(r){throw r instanceof Y||r instanceof X?r:new Y(n,e,r instanceof Error?r.message:String(r),r)}}i(G,"stage");async function Rl(n,e){let t=n.pages()[0];await(t===void 0?await n.newPage():t).goto(e,{waitUntil:"domcontentloaded"})}i(Rl,"navigateToEntry");import Rt from"node:os";import{createRequire as bl}from"node:module";var So=bl(import.meta.url);function kl(){let n=So.resolve("playwright-core/package.json"),e=So(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(kl,"readPlaywrightCoreVersion");function Ro(n){return{node:process.version,platform:`${Rt.platform()} ${Rt.release()} ${Rt.arch()}`,cpus:Rt.cpus().length,playwrightCore:kl(),chromiumExecutable:ut.executablePath(),channel:mt,extensionDist:n}}i(Ro,"buildEnvFingerprint");async function bt(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 J({operation:`read chrome.storage.session['tabStates'] and ['${Ft}']`,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,h])=>{let v=typeof h=="object"&&h!==null?h.playback:null;if(typeof v!="object"||v===null)return{tabId:g,playback:null};let k=v;return{tabId:g,playback:{runId:typeof k.runId=="string"?k.runId:null,status:typeof k.status=="string"?k.status:null,currentStepIndex:typeof k.currentStepIndex=="number"?k.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}},Ft),"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(bt,"probePlaybackSession");var be=m("identity-instances"),un=class extends Error{static{i(this,"IdentityLaunchAbortedError")}identityId;constructor(e){super(`[runtime] launch of the instance of identity ${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="IdentityLaunchAbortedError",this.identityId=e}},kt=class{static{i(this,"IdentityInstances")}#e;#t;#n;#r;#o=new Map;#a=new Map;constructor(e){this.#e=e.registry,this.#t=e.extensionDist,this.#n=e.allowInsecureHttps,this.#r=e.onLost}identityIdsWithInstance(){return[...this.#o.keys()]}async start(e,t,r){let o=this.#o.get(t);if(o!==void 0)throw new Error(`[runtime] identity ${t} already has an instance in state ${o.state}`);let s=bo(e.jobId,t),a=await G(e.jobId,"instance_reserve",()=>{let f=this.#a.get(s);return f!==void 0&&this.#d(f),this.#e.reserve(s,e.deadlineAt)}),l={identityId:t,jobId:e.jobId,instanceKey:s,userDataDir:a.userDataDir,state:"launching",context:null,contextAtTeardown:null,teardown:null};this.#o.set(t,l);let c={v:1,kind:"task_identity",runId:e.jobId,issuedAt:new Date().toISOString(),workflowId:e.workflowId,identityId:t};be.info("Launching the browser instance of an identity",{runId:e.jobId,workflowId:e.workflowId,identityId:t,headful:e.headful,userDataDir:a.userDataDir,deadlineAt:e.deadlineAt});let w=Date.now();try{let f=await Et({runId:e.jobId,userDataDir:a.userDataDir,extensionDist:this.#t,headful:e.headful,allowInsecureHttps:this.#n,keepBackgroundWindowsRendering:!0,extensionSession:r,command:c,entryUrl:e.entryUrl,onContext:i(g=>{l.context=g},"onContext"),assertNotAborted:i(()=>this.#i(l),"assertNotAborted")});this.#i(l),l.state="active",this.#s(l,f.context),be.info("Identity instance launched",{runId:e.jobId,identityId:t,chromeVersion:f.chromeVersion,extensionId:f.extensionId,readinessAttempts:f.readinessAttempts,readyAfterMs:f.readyAfterMs,launchDurationMs:Date.now()-w})}catch(f){let g=i(h=>{be.error("Teardown after a failed identity launch did not finish",{runId:e.jobId,identityId:t,err:h instanceof Error?h.message:String(h)})},"logTeardownFailure");if(l.teardown===null)await this.#l(l,"launch_failure").catch(g);else if(await l.teardown.catch(g),l.context!==null&&l.context!==l.contextAtTeardown){let h=await Fe(this.#e,{instanceKey:l.instanceKey,context:l.context,userDataDir:l.userDataDir,timeoutMs:2e4,trigger:"dispose_during_launch"});this.#c(l,h),h.failure!==null&&g(h.failure)}throw f}}async dispose(e,t){let r=this.#o.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.#l(r,s)}let o=this.#a.get(bo(e,t));return o!==void 0?this.#d(o):null}async disposeAll(e){let t=new Set;for(let s of this.#o.values())s.jobId===e&&t.add(s.identityId);for(let s of this.#a.values())s.jobId===e&&t.add(s.identityId);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.#o.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 identity ${e}`}:bt(t.context)}#i(e){if(e.teardown!==null)throw new un(e.identityId)}#s(e,t){let r=i(s=>{if(e.state!=="active"||e.teardown!==null)return;let a=this.#l(e,"instance_lost"),l={jobId:e.jobId,identityId:e.identityId,at:new Date().toISOString(),source:s};be.warn("Identity instance disappeared without a dispose",{...l}),a.catch(c=>{be.error("Teardown after a lost identity instance failed",{runId:e.jobId,identityId:e.identityId,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"))}#l(e,t){e.state="tearing_down",e.contextAtTeardown=e.context;let r=(async()=>{try{let o=await Fe(this.#e,{instanceKey:e.instanceKey,context:e.context,userDataDir:e.userDataDir,timeoutMs:2e4,trigger:t});if(be.info("Identity instance closed",{runId:e.jobId,identityId:e.identityId,trigger:t,disposeOutcome:o.result.outcome,instanceReleased:o.result.instanceReleased}),this.#c(e,o),o.failure!==null)throw o.failure;return o.result}finally{this.#o.get(e.identityId)===e&&this.#o.delete(e.identityId)}})();return e.teardown=r,r}#c(e,t){if(t.result.instanceReleased){this.#a.delete(e.instanceKey);return}this.#a.set(e.instanceKey,{instanceKey:e.instanceKey,jobId:e.jobId,identityId:e.identityId,result:t.result,killConfirmed:t.killConfirmed})}#d(e){let t=St(this.#e,e);return this.#a.delete(e.instanceKey),t}};function bo(n,e){return`${n}~${e}`}i(bo,"identityInstanceKey");import{mkdirSync as ko,readdirSync as Tl,readFileSync as Il,renameSync as xl,rmSync as mn,writeFileSync as Al}from"node:fs";import{join as je}from"node:path";var se=m("instance-registry");function vt(n){return typeof n=="string"&&n!==""}i(vt,"isNonEmptyString");function Ol(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(!vt(t.runId))throw new Error(`[instance-registry] ${e} has a missing or empty runId.`);if(!vt(t.userDataDir))throw new Error(`[instance-registry] ${e} has a missing or empty userDataDir.`);if(!vt(t.startedAt)||!vt(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(Ol,"parseInstanceRecord");function Nl(n,e){let t=`${n}.tmp`;Al(t,JSON.stringify(e,null,2),{encoding:"utf8",mode:384}),xl(t,n)}i(Nl,"writeMarkerAtomically");var Tt=class{static{i(this,"InstanceRegistry")}#e;constructor(e){this.#e=je(e,zr)}get instancesRoot(){return this.#e}userDataDirFor(e){return je(this.#e,e)}reserve(e,t){ko(this.#e,{recursive:!0,mode:448});let r=this.userDataDirFor(e);try{ko(r,{recursive:!1,mode:448})}catch(s){throw typeof s=="object"&&s!==null&&s.code==="EEXIST"?new X(e,r,s):s}let o=new Date().toISOString();try{Nl(je(r,pt),{v:1,runId:e,agentPid:process.pid,userDataDir:r,startedAt:o,deadlineAt:t})}catch(s){try{mn(r,{recursive:!0,force:!0})}catch(a){se.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 se.info("Instance reserved",{runId:e,userDataDir:r,deadlineAt:t}),{runId:e,userDataDir:r,startedAt:o,deadlineAt:t}}read(e){return this.#n(je(this.userDataDirFor(e),pt))}release(e){let t=this.userDataDirFor(e);mn(t,{recursive:!0,force:!0}),se.info("Instance released",{runId:e,userDataDir:t})}listRunIds(){let e;try{e=Tl(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?se.warn("Startup sweep found leftover browser instances",{instancesRoot:this.#e,count:t.length,outcomes:t}):se.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=je(t,pt),o=null,s;try{o=this.#n(r),s="valid"}catch(l){s=(typeof l=="object"&&l!==null?l.code:null)==="ENOENT"?"missing":"unreadable",se.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 wt(t);return se.warn("Leftover browser instance swept",{runId:e,userDataDir:t,marker:s,kill:a}),mn(t,{recursive:!0,force:!0}),{runId:e,userDataDir:t,marker:s,record:o,kill:a,removed:!0}}#n(e){let t=Il(e,"utf8");return Ol(JSON.parse(t),e)}};var K=m("playwright-execution-runtime"),pn=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}},It=class{static{i(this,"PlaywrightExecutionRuntime")}#e;#t;#n;#r;#o;#a;#i;#s=null;#l=null;#c=!1;#d=null;#m=null;constructor(e){no(e.extensionDist),this.#e=e.extensionDist,this.#t=e.headfulOverride,this.#n=e.allowInsecureHttps,this.#r=e.onInstanceLost,this.#o=new Tt(e.stateDir),this.#a=Ro(e.extensionDist),this.#i=new kt({registry:this.#o,extensionDist:e.extensionDist,allowInsecureHttps:e.allowInsecureHttps,onLost:e.onIdentityInstanceLost}),K.info("Execution runtime constructed",{stateDir:e.stateDir,instancesRoot:this.#o.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){let o=this.#s;if(o===null||o.runId!==e)throw new Error(`[runtime] cannot launch the instance of identity ${t}: job ${e} is not the running instance (running: ${o===null?"none":o.runId})`);if(o.identityInputs===null)throw new Error(`[runtime] cannot launch the instance of identity ${t}: job ${e} is not a task job (only a swarm job hosts a task's identities)`);await this.#i.start(o.identityInputs,t,r)}async disposeIdentityInstance(e,t){return this.#i.dispose(e,t)}async probeIdentityInstance(e){return this.#i.probe(e)}identityIdsWithInstance(){return this.#i.identityIdsWithInstance()}async sweepOrphanInstances(){return this.#o.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"}:bt(e.context)}async startRun(e){let t=this.#s;if(t!==null)throw new _t(e.runId,t.runId);let r=Date.now(),o=new Date(r+e.maxRunDurationSec*1e3).toISOString(),s=await G(e.runId,"instance_reserve",()=>this.#o.reserve(e.runId,o));this.#m?.runId===e.runId&&(this.#m=null);let a={runId:e.runId,userDataDir:s.userDataDir,context:null,disposeRequested:!1};this.#l=a;let l=this.#p(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 Et({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(h=>{w=h,a.context=h},"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.#l===a&&(this.#l=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.#l===a&&(this.#l=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.#l===a&&(this.#l=null)}}async cancelRun(e){await this.disposeRun(e)}async disposeRun(e,t=2e4){let[r,o]=await Promise.allSettled([this.#i.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.#d;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.#l;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"}))}#p(e){return e.headful||this.#t}#u(e){if(e.disposeRequested)throw new pn(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.#d={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.#d?.promise===s&&(this.#d=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.#m;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=St(this.#o,{instanceKey:e,result:t.result,killConfirmed:t.killConfirmed});return this.#m={runId:e,result:r,killConfirmed:!0},r}async#g(e){this.#c=!0;try{let t=await Fe(this.#o,{instanceKey:e.runId,context:e.context,userDataDir:e.userDataDir,timeoutMs:e.timeoutMs,trigger:e.trigger});if(this.#m={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 Cl}from"node:timers/promises";function ae(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(ae,"computeBackoffDelayMs");function ve(n){let e=Pl(n.error);return e!==null?{retry:!1,reason:e}:{retry:!0,delayMs:ae(n.attempt,n.rng)}}i(ve,"decideGatewayRetry");function Pl(n){if(n instanceof E)return"terminal_signal";if(n instanceof W)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 ge)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(Pl,"classifyFailure");var z=m("supervisor-identity");async function Te(n){let{config:e}=n;if(e.initialToken!==void 0)return Dl(e,e.initialToken);let t=F(e.stateDir);if(t!==null)return Ml(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 Gl(n,e.enrollmentCode);throw new p(`[progon-agent] This machine has no agent identity, so the daemon cannot start.
|
|
26
26
|
There is no state file in ${e.stateDir} and neither PROGON_AGENT_TOKEN nor PROGON_AGENT_ENROLL_CODE is set.
|
|
27
|
-
To enroll: create the agent in Progon (Settings \u2192 Agents), mint its enrollment code, then start the daemon once with PROGON_AGENT_ENROLL_CODE=<code>. The code is one-shot and expires in 15 minutes (CONTRACT-la \xA75.1); the minted pgat_ token is persisted to the state file, so later starts need neither variable.`)}i(
|
|
28
|
-
Mint a fresh code in Progon (Settings \u2192 Agents) once the server is reachable, then run 'progon-agent enroll <code>' again.`,{cause:
|
|
27
|
+
To enroll: create the agent in Progon (Settings \u2192 Agents), mint its enrollment code, then start the daemon once with PROGON_AGENT_ENROLL_CODE=<code>. The code is one-shot and expires in 15 minutes (CONTRACT-la \xA75.1); the minted pgat_ token is persisted to the state file, so later starts need neither variable.`)}i(Te,"resolveAgentIdentity");function Dl(n,e){return n.enrollmentCode!==void 0&&z.warn("Both PROGON_AGENT_TOKEN and PROGON_AGENT_ENROLL_CODE are set \u2014 the token wins and the enrollment code is NOT redeemed (it stays valid until it expires)"),z.info("Agent identity taken from PROGON_AGENT_TOKEN",{stateFile:Ll(n.stateDir)}),{agentToken:e,agentId:null,pollWaitSec:void 0,source:"env_token"}}i(Dl,"identityFromEnvToken");function Ll(n){try{return F(n)===null?"absent":"present"}catch(e){return z.warn("The state file could not be read \u2014 continuing on PROGON_AGENT_TOKEN, which does not need it. The persisted credential is NOT usable: once this variable is unset, the daemon will refuse to start until the file is removed and the machine re-enrolled",{stateDir:n,err:e instanceof Error?e.message:String(e)}),"unreadable"}}i(Ll,"describeStateFile");async function Gl(n,e){let{config:t,machine:r}=n;z.info("No agent identity found \u2014 redeeming the enrollment code",{hostname:r.hostname,platform:r.platform,arch:r.arch,agentVersion:r.agentVersion});let o=new lt(n.fetchImpl===void 0?{serverUrl:t.serverUrl,machine:r}:{serverUrl:t.serverUrl,machine:r,fetchImpl:n.fetchImpl}),s=await Ul(o,e,n.rng);return pe(t.stateDir,{agentId:s.agentId,agentToken:s.agentToken,protocolVersion:s.protocolVersion,serverUrl:t.serverUrl,tokenRotatedAt:null}),z.info("Agent identity persisted \u2014 PROGON_AGENT_ENROLL_CODE is no longer needed",{agentId:s.agentId,stateDir:t.stateDir}),{agentToken:s.agentToken,agentId:s.agentId,pollWaitSec:s.pollWaitSec,source:"enrollment"}}i(Gl,"enrollThisMachine");var vo=900*1e3;async function Ul(n,e,t){let r=Date.now()+vo;for(let o=0;;o+=1)try{return await n.enroll(e)}catch(s){if(!(s instanceof b))throw s;let a=ve({attempt:o,error:s,rng:t});if(!a.retry)throw z.warn("Enrollment refused definitively \u2014 not retrying",{attempt:o,reason:a.reason,err:s.message}),s;if(Date.now()+a.delayMs>=r)throw new p(`[progon-agent] Enrollment kept failing for the ${vo/6e4} minutes an enrollment code stays valid (CONTRACT-la \xA75.1), so this code can no longer be redeemed. Last failure: ${s.message}
|
|
28
|
+
Mint a fresh code in Progon (Settings \u2192 Agents) once the server is reachable, then run 'progon-agent enroll <code>' again.`,{cause:s});z.warn("Enrollment attempt failed \u2014 backing off and retrying",{attempt:o,retryInMs:a.delayMs,err:s.message}),await Cl(a.delayMs)}}i(Ul,"enrollWithRetry");function xt(n,e){if(n.source==="enrollment")return;let t=" The code itself was not spent and stays valid until it expires.";throw n.source==="env_token"?new 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
29
|
Unset PROGON_AGENT_TOKEN, then run the same command again. A separate state directory does NOT help here: the variable is read before any state file and wins wherever that file lives.
|
|
30
|
-
`+
|
|
30
|
+
`+t):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
31
|
To enroll this machine as a SECOND agent \u2014 for another deployment, or as another agent record \u2014 give it its own state directory: PROGON_RUNNER_STATE_DIR=<dir> progon-agent enroll <code> --server <url> (and give 'progon-agent start' the same variable).
|
|
32
32
|
To REPLACE the credential it already holds, remove the state file in ${e.stateDir}, then run: progon-agent enroll <code> --server ${e.serverUrl} \u2014 with that file gone this machine no longer names that deployment itself, and --server is what keeps the new enrollment pointed at it.
|
|
33
|
-
`+
|
|
34
|
-
Either point PROGON_SERVER_URL back at ${t} \u2014 or unset it entirely, since an enrolled machine reads the server from its own state file (CONTRACT-la \xA78) \u2014 or enroll this machine against ${e} instead: remove the state file, then run 'progon-agent enroll <code> --server ${e}'. To keep BOTH, enroll the second one under its own PROGON_RUNNER_STATE_DIR rather than replacing this credential.`)}i(dl,"assertServerMatchesEnrollment");import{createRequire as cl}from"node:module";import{hostname as ul}from"node:os";var fo=["darwin","linux","win32"],go=["x64","arm64"];function ml(t){return fo.includes(t)}i(ml,"isSupportedPlatform");function pl(t){return go.includes(t)}i(pl,"isSupportedArch");function hl(){let e=cl(import.meta.url)("../../package.json"),n=typeof e=="object"&&e!==null?e.version:void 0;if(typeof n!="string"||n==="")throw new Error('[supervisor] The agent package.json has no usable "version" field, so the agent cannot state its version on the enroll wire (CONTRACT-la \xA75.1). This is a packaging defect \u2014 the daemon must not enroll under an invented version.');if(n.length>30)throw new Error(`[supervisor] The agent package version ${JSON.stringify(n)} is longer than the 30 characters CONTRACT-la \xA75.1 allows for agentVersion.`);return n}i(hl,"readAgentVersion");function be(){let t=process.platform;if(!ml(t))throw new Error(`[supervisor] Unsupported platform ${JSON.stringify(t)}. The local agent runs on ${fo.join(", ")} (CONTRACT-la \xA75.1, \xA710.3).`);let e=process.arch;if(!pl(e))throw new Error(`[supervisor] Unsupported CPU architecture ${JSON.stringify(e)}. The local agent runs on ${go.join(", ")} (CONTRACT-la \xA75.1).`);let n=ul();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:hl()}}i(be,"describeAgentMachine");var wo=i(()=>{},"noop"),Et=class{static{i(this,"ActionQueue")}#e=Promise.resolve();run(e){let n=this.#e.then(e,e);return this.#e=n.then(wo,wo),n}};var yo=u("supervisor-deadline"),Le=class extends Error{static{i(this,"DeadlineExceededError")}operation;timeoutMs;constructor(e,n){super(`[supervisor] ${e} did not settle within ${n}ms`),this.name="DeadlineExceededError",this.operation=e,this.timeoutMs=n}};async function St(t){let e=t.work(),n=!1;e.then(()=>{n&&yo.warn("Abandoned work settled successfully after its deadline had passed",{operation:t.operation,timeoutMs:t.timeoutMs})},a=>{n&&yo.warn("Abandoned work rejected after its deadline had passed",{operation:t.operation,timeoutMs:t.timeoutMs,err:a instanceof Error?a.message:String(a)})});let r,o=new Promise((a,s)=>{r=setTimeout(()=>{n=!0,s(new Le(t.operation,t.timeoutMs))},t.timeoutMs)});try{return await Promise.race([e,o])}finally{r!==void 0&&clearTimeout(r)}}i(St,"withDeadline");function Ge(t,e){return new Promise(n=>{if(e.aborted){n();return}let r=setTimeout(()=>{e.removeEventListener("abort",o),n()},t);function o(){clearTimeout(r),n()}i(o,"onAbort"),e.addEventListener("abort",o,{once:!0})})}i(Ge,"sleep");var z=u("fail-reporter"),Rt=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){z.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&&z.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,z.error("Reporting run failure to the gateway",{runId:e.runId,...e.body}),await this.#o()}async retryPending(){let e=this.#t;e!==null&&(Date.now()<e.nextAttemptAtMs||await this.#o())}discardIfNotPublished(e){let n=this.#t;n!==null&&n.runId!==e&&(z.info("Undelivered fail verdict discarded \u2014 its run is already terminal server-side",{runId:n.runId,reason:n.body.reason,publishedRunId:e}),this.#t=null)}async#o(){let e=this.#t;if(e!==null)try{let n=await this.#e.failRun(e.runId,e.body);z.info("Fail verdict delivered",{runId:e.runId,reason:e.body.reason,status:n.status,attempts:e.attempt+1}),this.#t=null}catch(n){if(n instanceof E)throw n;if(n instanceof T)throw z.error("Fail verdict abandoned \u2014 the gateway no longer accepts this credential as current",{runId:e.runId,reason:e.body.reason,err:n.message}),this.#t=null,n;if(!(n instanceof k))throw n;let r=Se({attempt:e.attempt,error:n});if(!r.retry){z.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},z.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 bt=120,_o=bt*1e3,sn=3e4,ke=3,ln=45*1e3,dn="agent shutdown";var U=u("launch-run");async function Ro(t){let e;try{e=await gl(t)}finally{t.onClaimAnswered()}return e.kind!=="claimed"?e:yl(t,e.payload)}i(Ro,"claimAndLaunch");async function gl(t){try{let e=await t.client.claimRun(t.runId);return U.info("Run claimed",wl(e)),{kind:"claimed",payload:e}}catch(e){if(e instanceof E)throw e;if(e instanceof T)throw U.error("Claim refused as superseded \u2014 not launching, leaving it to the sweep",{runId:t.runId,err:e.message}),e;if(e instanceof he||e instanceof te)return U.info("Claim refused \u2014 the desired-state snapshot was stale, not launching",{runId:t.runId,err:e.message}),{kind:"claim_refused"};if(!(e instanceof k))throw e;return U.error("Claim produced no usable answer \u2014 not launching, leaving it to the sweep",{runId:t.runId,err:e.message}),{kind:"claim_unavailable"}}}i(gl,"claimRun");function wl(t){return"kind"in t?t.kind==="make_auto"?{kind:t.kind,runId:t.runId,projectId:t.command.projectId,queueId:t.command.queueId,headful:t.headful,maxRunDurationSec:t.maxRunDurationSec}:t.kind==="swarm"?{kind:t.kind,runId:t.runId,workflowId:t.command.workflowId,headful:t.headful,maxRunDurationSec:t.maxRunDurationSec}:{kind:t.kind,runId:t.runId,projectId:t.command.projectId,maxRunDurationSec:t.maxRunDurationSec}:{kind:"playback",runId:t.runId,scenarioId:t.scenarioId,projectId:t.projectId,runPurpose:t.runPurpose,headful:t.headful,maxRunDurationSec:t.maxRunDurationSec}}i(wl,"describeClaim");async function yl(t,e){try{await St({operation:`startRun(${e.runId})`,timeoutMs:_o,work:i(()=>t.runtime.startRun({runId:e.runId,entryUrl:e.entryUrl,headful:e.headful,maxRunDurationSec:e.maxRunDurationSec,extensionSession:e.extensionSession,command:e.command}),"work")})}catch(r){return{kind:"failed",body:El(t.runId,r)}}let n=t.runtime.getActiveInstance();return n===null||n.runId!==e.runId?(U.error("The launched instance was already gone when the supervisor read it back",{runId:e.runId,activeRunId:n===null?null:n.runId}),{kind:"instance_lost_immediately",runId:e.runId}):{kind:"launched",instance:n}}i(yl,"launchClaimedRun");var Eo=500,So="\u2026";function _l(t){return t.length<=Eo?t:t.slice(0,Eo-So.length)+So}i(_l,"fitFailMessageToWire");function El(t,e){if(e instanceof K){let n=_l(`stage ${e.stage}: ${en(e)}`);if(e.stage==="entry_navigation"){let r=to(e);return U.error("Launch failed",{runId:t,stage:e.stage,failReason:e.failReason,entryFailure:r,err:e.message}),{reason:e.failReason,message:n,entryFailure:r}}return U.error("Launch failed",{runId:t,stage:e.stage,failReason:e.failReason,err:e.message}),{reason:e.failReason,message:n}}return e instanceof Le?(U.error("Launch exceeded the agent-side launch deadline \u2014 disposing and failing",{runId:t,launchTimeoutSec:bt,err:e.message}),{reason:"launch_error",message:`launch did not complete within ${bt}s`}):e instanceof J?(U.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"}):(U.error("Launch failed with an unexpected error class",{runId:t,errName:e instanceof Error?e.name:typeof e,err:e instanceof Error?e.message:String(e)}),{reason:"launch_error",message:"launch failed with an unexpected error"})}i(El,"describeLaunchFailure");var Te=u("run-monitor");function Sl(t,e){let n=Date.now();return e.ok?e.tabs.some(o=>o.playback!==null&&o.playback.runId===t)?{healthy:!0}:Rl(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 (${bl(e.tabs)}; ${kl(e.agentJob,n)})`}:{healthy:!1,reason:e.reason,detail:e.detail}}i(Sl,"judgeProbe");function Rl(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<=ln}i(Rl,"isJobPulseStanding");function bl(t){if(t.length===0)return"tabStates is empty";let e=t.map(n=>n.playback===null?"none":n.playback.runId);return`${t.length} tab(s), playback run ids: ${e.join(", ")}`}i(bl,"describeTabs");function kl(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(ln)}ms)`}i(kl,"describeJobMarker");var kt=class{static{i(this,"RunMonitor")}#e;#t;#n=null;#o=null;#a=0;#s=!1;constructor(e){this.#e=e;let n=Date.parse(e.deadlineAt);if(Number.isNaN(n))throw new Error(`[run-monitor] run ${e.runId} has an unparseable deadlineAt ${JSON.stringify(e.deadlineAt)} \u2014 the run deadline (CONTRACT-la \xA715 A7) cannot be armed.`);this.#t=n}get runId(){return this.#e.runId}start(){let e=Math.max(0,this.#t-Date.now());Te.info("Monitoring launched run",{runId:this.#e.runId,deadlineAt:this.#e.deadlineAt,deadlineInMs:e,probeIntervalMs:sn,probeStrikeLimit:ke}),this.#n=setInterval(()=>{this.#r()},sn),this.#n.unref(),this.#o=setTimeout(()=>{this.#s||(this.stop(),Te.error("Run reached its server-authored deadline",{runId:this.#e.runId,deadlineAt:this.#e.deadlineAt}),this.#e.onDeadline())},e),this.#o.unref()}stop(){this.#s=!0,this.#n!==null&&(clearInterval(this.#n),this.#n=null),this.#o!==null&&(clearTimeout(this.#o),this.#o=null)}async#r(){if(this.#s)return;let e=Sl(this.#e.runId,await this.#i());if(this.#s)return;if(e.healthy){this.#a>0&&Te.info("Liveness probe recovered",{runId:this.#e.runId,clearedStrikes:this.#a}),this.#a=0;return}this.#a+=1;let n=`${e.reason}: ${e.detail}`;Te.warn("Liveness probe failed",{runId:this.#e.runId,strike:this.#a,strikeLimit:ke,reason:e.reason,detail:e.detail}),!(this.#a<ke)&&(this.stop(),Te.error("Liveness probe failed the strike limit \u2014 the browser is gone",{runId:this.#e.runId,strikes:ke,detail:n}),this.#e.onBrowserGone(`${ke} consecutive liveness probes failed (${n})`))}async#i(){try{return await this.#e.probe()}catch(e){let n=e instanceof Error?e.message:String(e);return Te.error("Liveness probe threw instead of reporting an observation",{runId:this.#e.runId,err:n}),{ok:!1,observedAt:new Date().toISOString(),reason:"evaluate_failed",detail:n}}}};var M=u("instance-reconciler");function Tl(t){let e=i(()=>{},"markSettled"),n=new Promise(s=>{e=s}),r=i(()=>{},"resolveClaimAnswer"),o=new Promise(s=>{r=s}),a={runId:t,cancelledBy:null,claimAnswered:!1,claimAnswer:o,markClaimAnswered:i(()=>{a.claimAnswered=!0,r()},"markClaimAnswered"),settled:n,markSettled:e};return a}i(Tl,"createPendingLaunch");var q={kind:"reconciled"},Tt=class{static{i(this,"InstanceReconciler")}#e;#t;#n;#o;#a=new Set;#s=null;#r=null;#i=null;constructor(e){this.#e=e.client,this.#t=e.runtime,this.#n=e.reporter,this.#o=e.detach}get activeRunId(){let e=this.#t.getActiveInstance();return e===null?null:e.runId}async sweepAtStartup(){let e=await this.#t.sweepOrphanInstances();this.#a=new Set(e.outcomes.map(n=>n.runId)),M.info("Startup sweep finished",{instancesRoot:e.instancesRoot,leftoverCount:e.outcomes.length,sweptRunIds:[...this.#a]})}async reconcile(e){let n=e.run;this.#n.discardIfNotPublished(n===null?null:n.runId);let r=this.#r;if(r!==null)return n!==null&&n.runId===r.runId?n.phase!=="queued"?q:{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"),q);let o=this.#t.getActiveInstance();return n===null?(o!==null&&await this.dispose(o.runId,"desired_state_run_absent"),q):o!==null?(o.runId===n.runId||await this.dispose(o.runId,"desired_state_runid_mismatch"),q):this.#n.hasVerdictFor(n.runId)?q:n.phase==="queued"?this.#i===n.runId?(M.info("Not re-claiming a run this agent has already attempted (one-shot CAS)",{runId:n.runId}),{kind:"claim_issued",runId:n.runId,claimAnswer:null}):(this.#i=n.runId,this.#m(n.runId),q):(await this.#d(n.runId,n.phase),q)}async cancelLaunchAndSettle(e){let n=this.#r;return n===null?null:(M.warn("Stopping a launch that is still in flight",{runId:n.runId,trigger:e}),n.cancelledBy=e,this.#o(()=>this.dispose(n.runId,e)),await n.settled,n.runId)}async handleInstanceLost(e){M.error("The runtime reported a lost browser instance",{...e}),await this.#u(e.runId,"browser_gone",`the browser instance disappeared (${e.source})`,"browser_gone")}async dispose(e,n){this.stopMonitor();try{let r=await this.#t.disposeRun(e);M.info("Instance disposed",{runId:e,trigger:n,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:n,err:r instanceof Error?r.message:String(r)})}}stopMonitor(){this.#s?.stop(),this.#s=null}#m(e){let n=Tl(e);this.#r=n,this.#c(n)}async#c(e){try{let n=await this.#l(e);await this.#o(()=>this.#h(e,n))}finally{e.markSettled()}}async#l(e){try{return{kind:"outcome",outcome:await Ro({client:this.#e,runtime:this.#t,runId:e.runId,onClaimAnswered:e.markClaimAnswered})}}catch(n){return{kind:"thrown",error:n}}}async#h(e,n){if(this.#r===e&&(this.#r=null),n.kind==="thrown")throw n.error;let r=n.outcome;switch(r.kind){case"launched":if(e.cancelledBy!==null){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.#p(r.instance.runId,r.instance.deadlineAt);return;case"claim_refused":case"claim_unavailable":case"instance_lost_immediately":return;case"failed":if(await this.dispose(e.runId,"launch_failure"),e.cancelledBy!==null){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,n){M.warn("The desired state withdrew a run that is still launching \u2014 disposing",{runId:e.runId,trigger:n}),e.cancelledBy=n,await this.dispose(e.runId,n)}#p(e,n){this.#s=new kt({runId:e,deadlineAt:n,probe:i(()=>this.#t.probePlaybackSession(),"probe"),onBrowserGone:i(r=>{this.#o(()=>this.#u(e,"browser_gone",r,"browser_gone"))},"onBrowserGone"),onDeadline:i(()=>{this.#o(()=>this.#u(e,"max_duration","the run reached its server-authored deadline","max_duration"))},"onDeadline")}),this.#s.start()}async#d(e,n){let r=this.#a.has(e),o=r?"browser_gone":"launch_error";M.error("The server publishes a run this agent is not carrying \u2014 reporting it",{runId:e,phase:n,sweptAtStartup:r,reason:o}),await this.#n.report({runId:e,body:{reason:o,message:r?"a leftover browser instance for this run was killed by the agent startup sweep":"this agent holds no browser instance for the run"}})}async#u(e,n,r,o){await this.dispose(e,o),await this.#n.report({runId:e,body:{reason:n,message:r}})}};var bo="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>.",ko={revoked:{exitCode:1,level:"error",message:"progon-agent stopped: this agent was revoked and its credential has been wiped. "+bo},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. "+bo},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"}},To={revoked:"agent_revoked",reenroll_required:"agent_superseded",credential_unusable:"agent_superseded",fatal:"shutdown",stopped:"shutdown"};var I=u("token-rotation"),vo=1440*60*1e3,vt=class{static{i(this,"TokenRotationCoordinator")}#e;#t;#n;#o=null;#a=!1;#s=!1;constructor(e){this.#e=e.client,this.#t=e.stateDir,this.#n=e.identitySource}async runCycle(e){let n=this.#o;if(n!==null)return n;let r=this.#r(e);this.#o=r;try{return await r}finally{this.#o=null}}get canDiagnoseFromTheWire(){return this.#n!=="env_token"}async diagnoseSuperseded(e){if(this.#n==="env_token")return I.error("The agent token in PROGON_AGENT_TOKEN has been superseded and the server no longer accepts it. This daemon owns no copy of it and will not touch the state directory: set PROGON_AGENT_TOKEN to a current token and restart, or unset it and enroll this machine so the daemon can rotate on its own."),"alive";try{return await this.#e.getTokenRotationStatus({signal:e}),"alive"}catch(n){if(n instanceof T)return"reenroll_required";if(n instanceof E)throw n;if(n instanceof k)return I.warn("The superseded probe could not be answered \u2014 treating the credential as still usable, because only an explicit agents.token_superseded ends this identity",{operation:n.operation,err:n.message}),"alive";throw n}}async settle(){let e=this.#o;e!==null&&await e.then(()=>{},()=>{})}async#r(e){if(this.#n==="env_token")return this.#a||(this.#a=!0,I.warn("Agent token rotation is not available: this daemon runs on PROGON_AGENT_TOKEN, so the operator owns the credential and there is nowhere to persist a replacement. Rotate it by setting PROGON_AGENT_TOKEN to a new token and restarting, or enroll this machine so the daemon can rotate on its own.")),{kind:"unsupported_env_token"};if(this.#s)return{kind:"superseded_in_grace"};let n=this.#d();if(n.kind!=="identity")return this.#u(n);let r=n.identity,o=await this.#i(e);return o.kind!=="status"?o.outcome:o.value.rotationDue?await this.#c(r,o.value.tokenRotatedAt,e):this.#m(r,o.value.tokenRotatedAt)}async#i(e){try{return{kind:"status",value:e===void 0?await this.#e.getTokenRotationStatus():await this.#e.getTokenRotationStatus({signal:e})}}catch(n){if(n instanceof T)return I.error("This agent token has been superseded and no longer authenticates \u2014 the token family is dead and this machine must be enrolled again"),{kind:"outcome",outcome:{kind:"reenroll_required"}};if(n instanceof E)throw n;if(n instanceof k)return I.warn("The rotation status check failed \u2014 retrying on the next scheduled cycle",{operation:n.operation,err:n.message}),{kind:"outcome",outcome:{kind:"status_unavailable"}};throw n}}#m(e,n){return e.tokenRotatedAt===n?{kind:"not_due"}:e.tokenRotatedAt===null?(this.#p({...e,tokenRotatedAt:n},"first observed rotation marker"),{kind:"not_due"}):(this.#s=!0,I.error("The server reports a newer generation of this agent token than this daemon holds \u2014 either a rotation response was lost before it could be persisted, or another process rotated this identity. The current token keeps working until the server closes its rotation grace window; after that this machine must be enrolled again. No further rotation will be attempted with the current credential.",{observedTokenRotatedAt:e.tokenRotatedAt,serverTokenRotatedAt:n}),{kind:"superseded_in_grace"})}async#c(e,n,r){let o;try{o=(await this.#e.rotateToken()).agentToken}catch(s){if(s instanceof E)throw s;if(s instanceof T)return await this.#l(r);if(s instanceof k)return I.warn("The rotation request produced no usable answer \u2014 probing what the server actually committed",{operation:s.operation,err:s.message}),await this.#h(n);throw s}this.#p({...e,agentToken:o,tokenRotatedAt:null},"rotated agent token"),this.#e.useAgentToken(o);let a=await this.#f();return a.kind==="reenroll_required"?a:(a.kind==="observed"&&this.#p({...e,agentToken:o,tokenRotatedAt:a.tokenRotatedAt},"rotation marker of the new agent token"),I.info("Agent token rotated"),{kind:"rotated"})}async#l(e){return await this.diagnoseSuperseded(e)==="reenroll_required"?{kind:"reenroll_required"}:(this.#s=!0,I.error("This agent token is no longer the current generation, so it could not be rotated. It still authenticates for now \u2014 the server closes its rotation grace window shortly after, and this machine must then be enrolled again. No further rotation will be attempted with the current credential."),{kind:"superseded_in_grace"})}async#h(e){let n=await this.#i(void 0);return n.kind!=="status"?n.outcome:n.value.tokenRotatedAt===e?(I.warn("The rotation request never reached the server \u2014 nothing was committed and the current token is unchanged. The next scheduled check will try again."),{kind:"not_committed"}):(this.#s=!0,I.error("The rotation was committed by the server but its response was lost, so the new token cannot be recovered \u2014 the server hands out the plaintext exactly once. The current token keeps working until the server closes its rotation grace window; after that this machine must be enrolled again.",{anchorTokenRotatedAt:e,serverTokenRotatedAt:n.value.tokenRotatedAt}),{kind:"superseded_in_grace"})}async#f(){let e=await this.#i(void 0);return e.kind==="status"?{kind:"observed",tokenRotatedAt:e.value.tokenRotatedAt}:e.outcome.kind==="reenroll_required"?{kind:"reenroll_required"}:(I.warn("The rotated token could not be confirmed against the server, so its generation marker was not recorded. The next scheduled check re-establishes it."),{kind:"unconfirmed"})}#p(e,n){try{return ce(this.#t,e),!0}catch(r){return I.error(`The ${n} could not be written to the state directory. This process keeps using the credential it holds, but a restart would fall back to the token on disk, which the server will refuse once its rotation grace window closes. Fix the permissions on the state directory BEFORE restarting the daemon; if it has already been restarted, enroll this machine again.`,{stateDir:this.#t,err:r instanceof Error?r.message:String(r)}),!1}}#d(){let e;try{e=F(this.#t)}catch(n){return{kind:"unreadable",err:n instanceof Error?n.message:String(n)}}return e===null?{kind:"absent"}:{kind:"identity",identity:e}}#u(e){return e.kind==="unreadable"?(I.error("The agent identity in the state directory cannot be read, so the credential this daemon is running on can neither be rotated nor replaced. The daemon keeps working on the token it holds in memory and will look again on the next scheduled check \u2014 restore the state directory from a backup, or enroll this machine again before restarting the daemon.",{stateDir:this.#t,identitySource:this.#n,err:e.err}),{kind:"identity_unavailable"}):(I.error("The agent identity is no longer in the state directory, so the credential this daemon is running on can neither be rotated nor replaced. The daemon keeps working on the token it holds in memory and will look again on the next scheduled check \u2014 restore the state directory, or enroll this machine again before restarting the daemon.",{stateDir:this.#t,identitySource:this.#n}),{kind:"identity_unavailable"})}};var O=u("run-supervisor"),cn=i(()=>Promise.resolve(),"noVerdictOwed"),At=class{static{i(this,"RunSupervisor")}#e;#t;#n;#o=new Et;#a;#s;#r=null;#i=0;#m=0;#c=!1;#l=new AbortController;#h=null;#f=!1;#p=!1;#d;#u=null;#w=null;constructor(e){this.#e=e.client,this.#a=e.stateDir,this.#s=e.pollWaitSec,this.#d=e.tokenRotation,this.#t=new Rt(e.client),this.#l.signal.addEventListener("abort",()=>this.#L(),{once:!0});let n=e.createRuntime(r=>{this.#x(()=>this.#n.handleInstanceLost(r))});this.#n=new Tt({client:e.client,runtime:n,reporter:this.#t,detach:i(r=>this.#x(r),"detach")})}async run(){await this.#o.run(()=>this.#n.sweepAtStartup());let e=await this.#C();if(e!==null)return e;for(this.#T(),await this.#N();!this.#c;){let n=this.#h;if(n!==null)return await this.#S(n),"revoked";if(this.#f)return await this.#R(),"reenroll_required";if(this.#p)return await this.#A(),"credential_unusable";try{await this.#o.run(()=>this.#t.retryPending());let r=await this.#G();this.#i=0;let o=await this.#o.run(()=>this.#n.reconcile(r));await this.#U(o)}catch(r){if(r instanceof E)return await this.#S(r),"revoked";if(r instanceof T&&await this.#v(r))return await this.#R(),"reenroll_required";if(this.#c)break;if(this.#_())continue;let o=await this.#F(r);if(o!==null)return o==="credential_unusable"?await this.#A():await this.#$(),o}}return this.#g()}async#g(){let e=this.#w;if(e===null)throw new Error("run-supervisor: the loop ended as stopped, but no shutdown() was ever started");return await e,"stopped"}async#N(){try{await this.#e.declareCapabilities({signal:this.#l.signal})}catch(e){if(await this.#O(e),this.#_())return;if(!(e instanceof k))throw e;O.error("Could not declare capabilities \u2014 job kinds this build supports will not be published to this agent until the next start; playback is unaffected",{err:e.message})}}async shutdown(e){let n=this.#w;if(n!==null)return O.info("A shutdown is already in progress \u2014 joining it",{cause:e}),n;let r=this.#P(e);return this.#w=r,r}async#P(e){O.info("Shutting down",{cause:e}),await this.#y(e==="fatal"?"fatal":"stopped",n=>this.#k(n))}async#y(e,n){this.#c=!0,this.#r?.abort(),this.#l.abort();let r=To[e],o=await this.#n.cancelLaunchAndSettle(r);await this.#o.run(async()=>{this.#n.stopMonitor();let a=this.#n.activeRunId;a!==null&&await this.#n.dispose(a,r),await n({activeRunId:a,launchingRunId:o})}),await this.#d.settle()}async#k(e){let{activeRunId:n,launchingRunId:r}=e;if(n!==null){await this.#b(()=>this.#t.report({runId:n,body:{reason:"browser_gone",message:dn}}));return}if(r!==null){await this.#b(()=>this.#t.report({runId:r,body:{reason:"browser_gone",message:dn}}));return}await this.#b(()=>this.#t.retryPending())}async#C(){try{if((await this.#d.runCycle(this.#l.signal)).kind!=="reenroll_required")return null}catch(e){if(e instanceof E)return await this.#S(e),"revoked";throw e}return await this.#R(),"reenroll_required"}#T(){if(this.#c||this.#l.signal.aborted)return;let e=setTimeout(()=>{this.#u=null,this.#D().finally(()=>{this.#T()})},vo);e.unref(),this.#u=e}async#D(){try{if((await this.#d.runCycle(this.#l.signal)).kind!=="reenroll_required")return;this.#f=!0,this.#r?.abort()}catch(e){await this.#I(e)}}#L(){this.#u!==null&&(clearTimeout(this.#u),this.#u=null)}async#v(e){O.warn("A gateway call was refused as superseded \u2014 diagnosing the credential",{operation:e.operation});try{return await this.#d.diagnoseSuperseded(this.#l.signal)==="reenroll_required"}catch(n){if(n instanceof E)return this.#h=n,!1;throw n}}async#G(){let e=new AbortController;this.#r=e;try{return await this.#e.pollDesiredState({waitSec:this.#s,signal:e.signal})}finally{this.#r=null}}async#U(e){if(e.kind==="reconciled"){this.#m=0;return}await this.#M(e.runId,e.claimAnswer)}async#M(e,n){let r=ie(this.#m);O.info("The desired state still names a run whose claim this agent already issued \u2014 pausing before the next poll",{runId:e,attempt:this.#m,waitMs:r,claimOnTheWire:n!==null}),this.#m+=1;let o=new AbortController;if(this.#r=o,this.#l.signal.aborted||this.#_()){this.#r=null;return}n?.then(()=>o.abort());try{await Ge(r,o.signal)}finally{this.#r=null}}async#E(){await this.#d.settle(),sr(this.#a)}async#S(e){O.error("This agent has been revoked \u2014 disposing, wiping the credential and stopping",{signal:e.signal}),await this.#y("revoked",cn),await this.#E()}async#A(){O.error("The server refuses the credential this daemon runs on as superseded, and this daemon has no way to replace it \u2014 disposing the browser and stopping so the operator, and the process supervisor, both learn it now. The state directory is left untouched: this credential did not come from there."),await this.#y("credential_unusable",cn)}async#$(){await this.#y("fatal",e=>this.#k(e))}async#R(){O.error("This agent token has been superseded and its family is no longer accepted \u2014 disposing, wiping the credential and stopping"),await this.#y("reenroll_required",cn),await this.#E()}async#F(e){if(!(e instanceof k))throw e;let n=this.#j(e);return n.kind==="exit"?n.exit:(this.#i+=1,await Ge(n.delayMs,this.#l.signal),null)}#j(e){if(e instanceof T){if(!this.#d.canDiagnoseFromTheWire)return{kind:"exit",exit:"credential_unusable"};let r=ie(this.#i);return O.error("The server refused this credential as superseded, but the probe did not confirm the token family is dead \u2014 the daemon keeps polling on the credential it holds. If this repeats, create a new enrollment code in Progon (Settings \u2192 Agents) and enroll this machine again.",{operation:e.operation,attempt:this.#i,retryInMs:r}),{kind:"retry",delayMs:r}}let n=Se({attempt:this.#i,error:e});return n.retry?(O.warn("Desired-state poll failed \u2014 backing off",{attempt:this.#i,retryInMs:n.delayMs,err:e.message}),{kind:"retry",delayMs:n.delayMs}):(O.error("The desired-state poll was refused definitively and no repetition can change that \u2014 the daemon cannot reconcile without a snapshot, so it is disposing its browser and stopping. Restart duty belongs to the process supervisor.",{reason:n.reason,operation:e.operation,err:e.message}),{kind:"exit",exit:"fatal"})}#x(e){return this.#o.run(e).catch(n=>this.#I(n))}async#I(e){await this.#O(e)||O.error("A background supervisor action failed",{err:e instanceof Error?e.message:String(e)})}async#O(e){if(e instanceof E)return this.#h=e,this.#r?.abort(),!0;if(!(e instanceof T))return!1;try{await this.#v(e)?this.#f=!0:this.#d.canDiagnoseFromTheWire||(this.#p=!0)}catch(n){return O.error("The superseded diagnosis failed after a gateway refusal off the poll",{operation:e.operation,err:n instanceof Error?n.message:String(n)}),!0}return this.#_()&&this.#r?.abort(),!0}#_(){return this.#h!==null||this.#f||this.#p}async#b(e){try{await e()}catch(n){if(n instanceof T){O.error("This agent token is no longer accepted as current, so the run could not be reported. The credential on disk is left alone \u2014 the next start diagnoses it and will say whether this machine has to be enrolled again.",{operation:n.operation});return}if(n instanceof E){await this.#E(),O.error("This agent was revoked, so the run could not be reported and the credential has been wiped. Create a new enrollment code in Progon (Settings \u2192 Agents) and start the daemon once with PROGON_AGENT_ENROLL_CODE=<code> to enroll this machine again.",{signal:n.signal});return}throw n}}};var Ao=u("supervisor-boot");async function xo(){let t=ue();Ao.info("Config loaded",{serverUrlOrigin:new URL(t.serverUrl).origin,serverUrlSource:t.serverUrlSource,stateDir:t.stateDir,headfulOverride:t.headfulOverride,allowInsecureHttps:t.allowInsecureHttps});let e=be(),n=await Re({config:t,machine:e});Ao.info("Agent identity resolved",{source:n.source,agentId:n.agentId,hostname:e.hostname,platform:e.platform,arch:e.arch,agentVersion:e.agentVersion});let r=Sr({overridePath:t.extensionDistOverride,stateDir:t.stateDir,agentId:n.agentId});await qe({stdio:"pipe"});let o=new ot({serverUrl:t.serverUrl,agentToken:n.agentToken}),a=new vt({client:o,stateDir:t.stateDir,identitySource:n.source});return new At({client:o,stateDir:t.stateDir,pollWaitSec:n.pollWaitSec,tokenRotation:a,createRuntime:i(s=>new yt({stateDir:t.stateDir,extensionDist:r,headfulOverride:t.headfulOverride,allowInsecureHttps:t.allowInsecureHttps,onInstanceLost:s}),"createRuntime")})}i(xo,"bootRunSupervisor");var un=u("daemon");async function Oo(){fr(),un.info("progon-agent starting");let t=await xo();gr(async r=>{await t.shutdown(r)});let e;try{e=await t.run()}catch(r){throw await t.shutdown("fatal").catch(o=>{throw new AggregateError([r,o],`${Io(r)} \u2014 and the teardown after it failed too, so the browser may still be running: ${Io(o)}`)}),r}let n=ko[e];return n.level==="error"?un.error(n.message):un.info(n.message),n.exitCode}i(Oo,"runDaemon");function Io(t){return t instanceof Error?t.message:String(t)}i(Io,"describe");import{createHash as Dl,randomBytes as Ll}from"node:crypto";import{z as x}from"zod";var No=x.object({requestId:x.uuid(),mode:x.literal("device"),userCode:x.string().min(1),verificationUrl:x.url(),expiresAt:x.iso.datetime({offset:!0}),pollIntervalSec:x.number().int().positive()}),Po=x.object({status:x.literal("authorization_pending"),expiresAt:x.iso.datetime({offset:!0}),pollIntervalSec:x.number().int().positive()}),vl=x.object({companyName:x.string(),approvedByEmail:x.string(),approvedAt:x.string()}),Co=x.object({credential:je,approval:vl});var Do=u("gateway-enrollment-request"),xt=class{static{i(this,"GatewayEnrollmentRequestClient")}serverUrl;machine;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.machine=e.machine,this.fetchImpl=e.fetchImpl??it}async create(e){let n=await ne({operation:"enrollment_request_create",method:"POST",url:D(this.serverUrl,"/enrollment-requests"),agentToken:null,body:{deviceSecretHash:e,protocolVersion:1,...this.machine},signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:Tr}),r=C("enrollment_request_create",No.safeParse(n));return Do.info("Enrollment request opened",{requestId:r.requestId,mode:r.mode,pollIntervalSec:r.pollIntervalSec,expiresAt:r.expiresAt}),r}async poll(e){let n=await ne({operation:"enrollment_request_poll",method:"POST",url:D(this.serverUrl,"/enrollment-requests/poll"),agentToken:null,body:{deviceSecret:e},signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:vr}),r=typeof n=="object"&&n!==null?n:null;if(r!==null&&"credential"in r){let o=C("enrollment_request_poll",Co.safeParse(n));return Do.info("Enrollment request approved",{agentId:o.credential.agentId}),{kind:"enrolled",credential:o.credential,approval:o.approval}}if(r!==null&&"status"in r){let o=C("enrollment_request_poll",Po.safeParse(n));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 ne({operation:"enrollment_request_cancel",method:"POST",url:D(this.serverUrl,"/enrollment-requests/cancel"),agentToken:null,body:{deviceSecret:e},signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:Ar})}};import{spawn as Al}from"node:child_process";var Ue=u("browser-open");function It(t){return t!==void 0&&t!==""}i(It,"isSet");function xl(t,e){return!(It(t.SSH_CONNECTION)||It(t.SSH_TTY)||e==="linux"&&!It(t.DISPLAY)&&!It(t.WAYLAND_DISPLAY))}i(xl,"shouldAttemptBrowserOpen");var Il=/[&|^<>"'` ]/;function Ol(t){let e;try{e=new URL(t)}catch{return!1}return e.protocol!=="http:"&&e.protocol!=="https:"||t!==e.href?!1:!Il.test(t)}i(Ol,"isSpawnSafeUrl");function Nl(t,e){switch(e){case"darwin":return{command:"open",args:[t]};case"linux":return{command:"xdg-open",args:[t]};case"win32":return{command:"cmd",args:["/d","/s","/c","start","",t]};default:return null}}i(Nl,"browserOpenCommand");function Lo(t,e,n){if(!xl(e,n)){Ue.debug("Not opening a browser: this host has no desktop to open one on",{platform:n});return}if(!Ol(t)){Ue.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=Nl(t,n);if(r===null){Ue.debug("Not opening a browser: no opener is defined for this platform",{platform:n});return}try{let o=Al(r.command,[...r.args],{detached:!0,stdio:"ignore"});o.on("error",a=>{Ue.debug("Could not start the browser; the approval URL was printed instead",{platform:n,command:r.command,err:a.message})}),o.unref()}catch(o){Ue.debug("Could not start the browser; the approval URL was printed instead",{platform:n,command:r.command,err:o instanceof Error?o.message:String(o)})}}i(Lo,"openVerificationUrl");var Pl=30,Cl=5;function Go(t){return{intervalSec:t.pollIntervalSec,deadlineMs:t.timeoutSec===null?t.expiresAtMs:Math.min(t.expiresAtMs,t.nowMs+t.timeoutSec*1e3)}}i(Go,"initialPollSchedule");function Ot(t,e){if(e.kind==="pending")return{state:t,delayMs:t.intervalSec*1e3};if(e.kind==="slow_down"){let r=t.intervalSec+Cl,o=e.retryAfterSec!==null&&e.retryAfterSec>r?e.retryAfterSec:r,a=Math.min(o,Pl);return{state:{intervalSec:a,deadlineMs:t.deadlineMs},delayMs:a*1e3}}let n=ie(e.attempt,e.rng);return{state:t,delayMs:Math.max(t.intervalSec*1e3,n)}}i(Ot,"nextPollDelayMs");function Uo(t,e){return e>=t.deadlineMs}i(Uo,"isDeadlinePassed");function Mo(t,e,n){return Math.max(0,Math.min(e,t.deadlineMs-n))}i(Mo,"clampDelayToDeadline");var Ae=u("device-enrollment"),Gl=24,Ul=2e3,mn=0,ve=1,Fo=130,Ml="This machine is already enrolled. Start the daemon with: progon-agent start",$l="Enrollment was denied in the browser. Nothing was created on this machine.",Fl="Cancelled. Nothing was saved on this machine.",jl="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 $o(t){return`Enrollment request expired. Run: progon-agent enroll --server ${t}`}i($o,"expiredLine");function Bl(t,e,n){return`This machine is already enrolled against ${t}, not ${e}. An agent credential is only valid at the deployment that issued it, so nothing was requested from ${e}.
|
|
33
|
+
`+t)}i(xt,"assertEnrollmentCodeWasRedeemed");function Ml(n,e){if(!tt(n,e))throw new p(`[progon-agent] The persisted agent credential was enrolled against ${n}, but PROGON_SERVER_URL is ${e}. A pgat_ token is meaningless at a different deployment (CONTRACT-la \xA78), so the daemon refuses to authenticate blind.
|
|
34
|
+
Either point PROGON_SERVER_URL back at ${n} \u2014 or unset it entirely, since an enrolled machine reads the server from its own state file (CONTRACT-la \xA78) \u2014 or enroll this machine against ${e} instead: remove the state file, then run 'progon-agent enroll <code> --server ${e}'. To keep BOTH, enroll the second one under its own PROGON_RUNNER_STATE_DIR rather than replacing this credential.`)}i(Ml,"assertServerMatchesEnrollment");import{createRequire as $l}from"node:module";import{hostname as Fl}from"node:os";var To=["darwin","linux","win32"],Io=["x64","arm64"];function jl(n){return To.includes(n)}i(jl,"isSupportedPlatform");function Wl(n){return Io.includes(n)}i(Wl,"isSupportedArch");function Bl(){let e=$l(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(Bl,"readAgentVersion");function Ie(){let n=process.platform;if(!jl(n))throw new Error(`[supervisor] Unsupported platform ${JSON.stringify(n)}. The local agent runs on ${To.join(", ")} (CONTRACT-la \xA75.1, \xA710.3).`);let e=process.arch;if(!Wl(e))throw new Error(`[supervisor] Unsupported CPU architecture ${JSON.stringify(e)}. The local agent runs on ${Io.join(", ")} (CONTRACT-la \xA75.1).`);let t=Fl();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:Bl()}}i(Ie,"describeAgentMachine");var xo=i(()=>{},"noop"),At=class{static{i(this,"ActionQueue")}#e=Promise.resolve();run(e){let t=this.#e.then(e,e);return this.#e=t.then(xo,xo),t}};var Ao=m("supervisor-deadline"),We=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 xe(n){let e=n.work(),t=!1;e.then(()=>{t&&Ao.warn("Abandoned work settled successfully after its deadline had passed",{operation:n.operation,timeoutMs:n.timeoutMs})},s=>{t&&Ao.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 We(n.operation,n.timeoutMs))},n.timeoutMs)});try{return await Promise.race([e,o])}finally{r!==void 0&&clearTimeout(r)}}i(xe,"withDeadline");function Be(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(Be,"sleep");var Z=m("fail-reporter"),Ot=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){Z.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&&Z.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,Z.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&&(Z.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);Z.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 Z.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 b))throw t;let r=ve({attempt:e.attempt,error:t});if(!r.retry){Z.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},Z.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 Nt=120,Pt=Nt*1e3,hn=3e4,Ae=3,fn=45*1e3,gn="agent shutdown";var Oe=m("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}:Hl(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 (${Vl(e.tabs)}; ${Jl(e.agentJob,t)})`}:{healthy:!1,reason:e.reason,detail:e.detail}}i(ql,"judgeProbe");function Hl(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<=fn}i(Hl,"isJobPulseStanding");function Vl(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(Vl,"describeTabs");function Jl(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(fn)}ms)`}i(Jl,"describeJobMarker");var Ne=class{static{i(this,"RunMonitor")}#e;#t;#n=null;#r=null;#o=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());Oe.info("Monitoring launched run",{runId:this.#e.runId,identityId:this.#e.identityId,deadlineAt:this.#e.deadlineAt,deadlineInMs:e,probeIntervalMs:hn,probeStrikeLimit:Ae}),this.#n=setInterval(()=>{this.#i()},hn),this.#n.unref(),this.#r=setTimeout(()=>{this.#a||(this.stop(),Oe.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#i(){if(this.#a)return;let e=ql(this.#e.runId,await this.#s());if(this.#a)return;if(e.healthy){this.#o>0&&Oe.info("Liveness probe recovered",{runId:this.#e.runId,identityId:this.#e.identityId,clearedStrikes:this.#o}),this.#o=0;return}this.#o+=1;let t=`${e.reason}: ${e.detail}`;Oe.warn("Liveness probe failed",{runId:this.#e.runId,identityId:this.#e.identityId,strike:this.#o,strikeLimit:Ae,reason:e.reason,detail:e.detail}),!(this.#o<Ae)&&(this.stop(),Oe.error("Liveness probe failed the strike limit \u2014 the browser is gone",{runId:this.#e.runId,identityId:this.#e.identityId,strikes:Ae,detail:t}),this.#e.onBrowserGone(`${Ae} 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 Oe.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 q=m("identity-reconciler"),Ct=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&&q.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.#d(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.#o(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){q.info("An identity instance of a finished job went away \u2014 nothing to relaunch",{...e});return}this.#p(t,e.identityId),this.#c(t,e.identityId,`the instance disappeared (${e.source})`)}#o(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 xe({operation:`startIdentityInstance(${e.jobId}, ${t})`,timeoutMs:Pt,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.#i(e,t,r))}async#i(e,t,r){e.launching.delete(t);let o=this.#r===e;if(r!==null){if(q.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.#d(e,t,"identity_left_run_block");return}this.#s(e,t)}#s(e,t){let r=new Ne({runId:e.jobId,identityId:t,deadlineAt:e.deadlineAt,probe:i(()=>this.#e.probeIdentityInstance(t),"probe"),onBrowserGone:i(o=>{this.#n(()=>this.#l(e,t,o))},"onBrowserGone"),onDeadline:i(()=>{this.#n(()=>this.#h(e,t,"max_duration"))},"onDeadline")});e.monitors.set(t,r),r.start(),q.info("Identity instance is up and monitored",{runId:e.jobId,identityId:t})}async#l(e,t,r){this.#r===e&&(e.monitors.delete(t),q.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)){q.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)||(q.warn("Relaunching the instance of an identity that is still in the run block",{runId:e.jobId,identityId:t,cause:r}),this.#o(e,t))}}#d(e,t,r){e.closing.has(t)||(e.closing.add(t),this.#p(e,t),this.#m(e,t,r))}async#m(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.#p(e,t),await this.#u(e,t,r)}#p(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;q.info("Identity instance disposed",{runId:e.jobId,identityId:t,trigger:r,disposeOutcome:o.outcome,instanceReleased:o.instanceReleased,durationMs:o.durationMs})}catch(o){q.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=m("launch-run");async function Po(n){let e;try{e=await Yl(n)}finally{n.onClaimAnswered()}return e.kind!=="claimed"?e:zl(n,e.payload)}i(Po,"claimAndLaunch");async function Yl(n){try{let e=await n.client.claimRun(n.runId);return U.info("Run claimed",Xl(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 we||e instanceof ne)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 b))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(Yl,"claimRun");function Xl(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(Xl,"describeClaim");async function zl(n,e){try{await xe({operation:`startRun(${e.runId})`,timeoutMs:Pt,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:Ql(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(zl,"launchClaimedRun");var Oo=500,No="\u2026";function Zl(n){return n.length<=Oo?n:n.slice(0,Oo-No.length)+No}i(Zl,"fitFailMessageToWire");function Ql(n,e){if(e instanceof Y){let t=Zl(`stage ${e.stage}: ${cn(e)}`);if(e.stage==="entry_navigation"){let r=_o(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 We?(U.error("Launch exceeded the agent-side launch deadline \u2014 disposing and failing",{runId:n,launchTimeoutSec:Nt,err:e.message}),{reason:"launch_error",message:`launch did not complete within ${Nt}s`}):e instanceof X?(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(Ql,"describeLaunchFailure");var M=m("instance-reconciler");function ed(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(ed,"createPendingLaunch");var H={kind:"reconciled"},Dt=class{static{i(this,"InstanceReconciler")}#e;#t;#n;#r;#o=new Set;#a=null;#i=null;#s=null;#l;#c=null;constructor(e){this.#e=e.client,this.#t=e.runtime,this.#n=e.reporter,this.#r=e.detach,this.#l=new Ct({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.#o=new Set(e.outcomes.map(t=>t.runId)),M.info("Startup sweep finished",{instancesRoot:e.instancesRoot,leftoverCount:e.outcomes.length,sweptRunIds:[...this.#o]})}async reconcile(e){let t=e.run;this.#n.discardIfNotPublished(t===null?null:t.runId),this.#c=t===null?null:{runId:t.runId,identityIds:Co(t)};let r=this.#i;if(r!==null)return t!==null&&t.runId===r.runId?t.phase!=="queued"?H:{kind:"claim_issued",runId:t.runId,claimAnswer:r.claimAnswered?null:r.claimAnswer}:(r.cancelledBy!==null||await this.#u(r,t===null?"desired_state_run_absent":"desired_state_runid_mismatch"),H);let o=this.#t.getActiveInstance();return t===null?(o!==null&&await this.dispose(o.runId,"desired_state_run_absent"),H):o!==null?o.runId===t.runId?(await this.#l.apply(o.runId,o.deadlineAt,Co(t)),H):(await this.dispose(o.runId,"desired_state_runid_mismatch"),H):this.#n.hasVerdictFor(t.runId)?H: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.#d(t.runId),H):(await this.#w(t.runId,t.phase),H)}async cancelLaunchAndSettle(e){let t=this.#i;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.#l.handleLost(e)}async handleInstanceLost(e){M.error("The runtime reported a lost browser instance",{...e}),await this.#g(e.runId,"browser_gone",`the browser instance disappeared (${e.source})`,"browser_gone")}async dispose(e,t){this.stopMonitor(),this.#l.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}#d(e){let t=ed(e);this.#i=t,this.#m(t)}async#m(e){try{let t=await this.#h(e);await this.#r(()=>this.#p(e,t))}finally{e.markSettled()}}async#h(e){try{return{kind:"outcome",outcome:await Po({client:this.#e,runtime:this.#t,runId:e.runId,onClaimAnswered:e.markClaimAnswered})}}catch(t){return{kind:"thrown",error:t}}}async#p(e,t){if(this.#i===e&&(this.#i=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.#f(r.instance.runId,r.instance.deadlineAt),this.#c?.runId===r.instance.runId&&await this.#l.apply(r.instance.runId,r.instance.deadlineAt,this.#c.identityIds);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#u(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)}#f(e,t){this.#a=new Ne({runId:e,identityId:null,deadlineAt:t,probe:i(()=>this.#t.probePlaybackSession(),"probe"),onBrowserGone:i(r=>{this.#r(()=>this.#g(e,"browser_gone",r,"browser_gone"))},"onBrowserGone"),onDeadline:i(()=>{this.#r(()=>this.#g(e,"max_duration","the run reached its server-authored deadline","max_duration"))},"onDeadline")}),this.#a.start()}async#w(e,t){let r=this.#o.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#g(e,t,r,o){await this.dispose(e,o),await this.#n.report({runId:e,body:{reason:t,message:r}})}};function Co(n){return n.identities===void 0?[]:n.identities.map(e=>e.identityId)}i(Co,"identityIdsOf");var Do="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>.",Lo={revoked:{exitCode:1,level:"error",message:"progon-agent stopped: this agent was revoked and its credential has been wiped. "+Do},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. "+Do},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"}},Go={revoked:"agent_revoked",reenroll_required:"agent_superseded",credential_unusable:"agent_superseded",fatal:"shutdown",stopped:"shutdown"};var x=m("token-rotation"),Uo=1440*60*1e3,Lt=class{static{i(this,"TokenRotationCoordinator")}#e;#t;#n;#r=null;#o=!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.#i(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 b)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#i(e){if(this.#n==="env_token")return this.#o||(this.#o=!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.#l(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 b)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}}#l(e,t){return e.tokenRotatedAt===t?{kind:"not_due"}:e.tokenRotatedAt===null?(this.#p({...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.#d(r);if(a instanceof b)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.#m(t);throw a}this.#p({...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.#p({...e,agentToken:o,tokenRotatedAt:s.tokenRotatedAt},"rotation marker of the new agent token"),x.info("Agent token rotated"),{kind:"rotated"})}async#d(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#m(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"})}#p(e,t){try{return pe(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=m("run-supervisor"),wn=i(()=>Promise.resolve(),"noVerdictOwed"),Gt=class{static{i(this,"RunSupervisor")}#e;#t;#n;#r=new At;#o;#a;#i=null;#s=0;#l=0;#c=!1;#d=new AbortController;#m=null;#h=!1;#p=!1;#u;#f=null;#w=null;constructor(e){this.#e=e.client,this.#o=e.stateDir,this.#a=e.pollWaitSec,this.#u=e.tokenRotation,this.#t=new Ot(e.client),this.#d.signal.addEventListener("abort",()=>this.#L(),{once:!0});let t=e.createRuntime({onInstanceLost:i(r=>{this.#b(()=>this.#n.handleInstanceLost(r))},"onInstanceLost"),onIdentityInstanceLost:i(r=>{this.#b(()=>this.#n.handleIdentityInstanceLost(r))},"onIdentityInstanceLost")});this.#n=new Dt({client:e.client,runtime:t,reporter:this.#t,detach:i(r=>this.#b(r),"detach")})}async run(){await this.#r.run(()=>this.#n.sweepAtStartup());let e=await this.#C();if(e!==null)return e;for(this.#T(),await this.#N();!this.#c;){let t=this.#m;if(t!==null)return await this.#S(t),"revoked";if(this.#h)return await this.#R(),"reenroll_required";if(this.#p)return await this.#x(),"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.#S(r),"revoked";if(r instanceof S&&await this.#I(r))return await this.#R(),"reenroll_required";if(this.#c)break;if(this.#_())continue;let o=await this.#F(r);if(o!==null)return o==="credential_unusable"?await this.#x():await this.#$(),o}}return this.#g()}async#g(){let e=this.#w;if(e===null)throw new Error("run-supervisor: the loop ended as stopped, but no shutdown() was ever started");return await e,"stopped"}async#N(){try{await this.#e.declareCapabilities({signal:this.#d.signal})}catch(e){if(await this.#O(e),this.#_())return;if(!(e instanceof b))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.#y(e==="fatal"?"fatal":"stopped",t=>this.#v(t))}async#y(e,t){this.#c=!0,this.#i?.abort(),this.#d.abort();let r=Go[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#v(e){let{activeRunId:t,launchingRunId:r}=e;if(t!==null){await this.#k(()=>this.#t.report({runId:t,body:{reason:"browser_gone",message:gn}}));return}if(r!==null){await this.#k(()=>this.#t.report({runId:r,body:{reason:"browser_gone",message:gn}}));return}await this.#k(()=>this.#t.retryPending())}async#C(){try{if((await this.#u.runCycle(this.#d.signal)).kind!=="reenroll_required")return null}catch(e){if(e instanceof E)return await this.#S(e),"revoked";throw e}return await this.#R(),"reenroll_required"}#T(){if(this.#c||this.#d.signal.aborted)return;let e=setTimeout(()=>{this.#f=null,this.#D().finally(()=>{this.#T()})},Uo);e.unref(),this.#f=e}async#D(){try{if((await this.#u.runCycle(this.#d.signal)).kind!=="reenroll_required")return;this.#h=!0,this.#i?.abort()}catch(e){await this.#A(e)}}#L(){this.#f!==null&&(clearTimeout(this.#f),this.#f=null)}async#I(e){A.warn("A gateway call was refused as superseded \u2014 diagnosing the credential",{operation:e.operation});try{return await this.#u.diagnoseSuperseded(this.#d.signal)==="reenroll_required"}catch(t){if(t instanceof E)return this.#m=t,!1;throw t}}async#G(){let e=new AbortController;this.#i=e;try{return await this.#e.pollDesiredState({waitSec:this.#a,signal:e.signal})}finally{this.#i=null}}async#U(e){if(e.kind==="reconciled"){this.#l=0;return}await this.#M(e.runId,e.claimAnswer)}async#M(e,t){let r=ae(this.#l);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.#l,waitMs:r,claimOnTheWire:t!==null}),this.#l+=1;let o=new AbortController;if(this.#i=o,this.#d.signal.aborted||this.#_()){this.#i=null;return}t?.then(()=>o.abort());try{await Be(r,o.signal)}finally{this.#i=null}}async#E(){await this.#u.settle(),gr(this.#o)}async#S(e){A.error("This agent has been revoked \u2014 disposing, wiping the credential and stopping",{signal:e.signal}),await this.#y("revoked",wn),await this.#E()}async#x(){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.#y("credential_unusable",wn)}async#$(){await this.#y("fatal",e=>this.#v(e))}async#R(){A.error("This agent token has been superseded and its family is no longer accepted \u2014 disposing, wiping the credential and stopping"),await this.#y("reenroll_required",wn),await this.#E()}async#F(e){if(!(e instanceof b))throw e;let t=this.#j(e);return t.kind==="exit"?t.exit:(this.#s+=1,await Be(t.delayMs,this.#d.signal),null)}#j(e){if(e instanceof S){if(!this.#u.canDiagnoseFromTheWire)return{kind:"exit",exit:"credential_unusable"};let r=ae(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=ve({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"})}#b(e){return this.#r.run(e).catch(t=>this.#A(t))}async#A(e){await this.#O(e)||A.error("A background supervisor action failed",{err:e instanceof Error?e.message:String(e)})}async#O(e){if(e instanceof E)return this.#m=e,this.#i?.abort(),!0;if(!(e instanceof S))return!1;try{await this.#I(e)?this.#h=!0:this.#u.canDiagnoseFromTheWire||(this.#p=!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.#_()&&this.#i?.abort(),!0}#_(){return this.#m!==null||this.#h||this.#p}async#k(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.#E(),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 Mo=m("supervisor-boot");async function $o(){let n=he();Mo.info("Config loaded",{serverUrlOrigin:new URL(n.serverUrl).origin,serverUrlSource:n.serverUrlSource,stateDir:n.stateDir,headfulOverride:n.headfulOverride,allowInsecureHttps:n.allowInsecureHttps});let e=Ie(),t=await Te({config:n,machine:e});Mo.info("Agent identity resolved",{source:t.source,agentId:t.agentId,hostname:e.hostname,platform:e.platform,arch:e.arch,agentVersion:e.agentVersion});let r=Or({overridePath:n.extensionDistOverride,stateDir:n.stateDir,agentId:t.agentId});await Ye({stdio:"pipe"});let o=new dt({serverUrl:n.serverUrl,agentToken:t.agentToken}),s=new Lt({client:o,stateDir:n.stateDir,identitySource:t.source});return new Gt({client:o,stateDir:n.stateDir,pollWaitSec:t.pollWaitSec,tokenRotation:s,createRuntime:i(({onInstanceLost:a,onIdentityInstanceLost:l})=>new It({stateDir:n.stateDir,extensionDist:r,headfulOverride:n.headfulOverride,allowInsecureHttps:n.allowInsecureHttps,onInstanceLost:a,onIdentityInstanceLost:l}),"createRuntime")})}i($o,"bootRunSupervisor");var yn=m("daemon");async function jo(){kr(),yn.info("progon-agent starting");let n=await $o();vr(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],`${Fo(r)} \u2014 and the teardown after it failed too, so the browser may still be running: ${Fo(o)}`)}),r}let t=Lo[e];return t.level==="error"?yn.error(t.message):yn.info(t.message),t.exitCode}i(jo,"runDaemon");function Fo(n){return n instanceof Error?n.message:String(n)}i(Fo,"describe");import{createHash as dd,randomBytes as cd}from"node:crypto";import{z as I}from"zod";var Wo=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()}),Bo=I.object({status:I.literal("authorization_pending"),expiresAt:I.iso.datetime({offset:!0}),pollIntervalSec:I.number().int().positive()}),td=I.object({companyName:I.string(),approvedByEmail:I.string(),approvedAt:I.string()}),Ko=I.object({credential:Ve,approval:td});var qo=m("gateway-enrollment-request"),Ut=class{static{i(this,"GatewayEnrollmentRequestClient")}serverUrl;machine;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.machine=e.machine,this.fetchImpl=e.fetchImpl??ct}async create(e){let t=await re({operation:"enrollment_request_create",method:"POST",url:C(this.serverUrl,"/enrollment-requests"),agentToken:null,body:{deviceSecretHash:e,protocolVersion:1,...this.machine},signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:Dr}),r=P("enrollment_request_create",Wo.safeParse(t));return qo.info("Enrollment request opened",{requestId:r.requestId,mode:r.mode,pollIntervalSec:r.pollIntervalSec,expiresAt:r.expiresAt}),r}async poll(e){let t=await re({operation:"enrollment_request_poll",method:"POST",url:C(this.serverUrl,"/enrollment-requests/poll"),agentToken:null,body:{deviceSecret:e},signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:Lr}),r=typeof t=="object"&&t!==null?t:null;if(r!==null&&"credential"in r){let o=P("enrollment_request_poll",Ko.safeParse(t));return qo.info("Enrollment request approved",{agentId:o.credential.agentId}),{kind:"enrolled",credential:o.credential,approval:o.approval}}if(r!==null&&"status"in r){let o=P("enrollment_request_poll",Bo.safeParse(t));return{kind:"pending",expiresAt:o.expiresAt,pollIntervalSec:o.pollIntervalSec}}throw new W("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 re({operation:"enrollment_request_cancel",method:"POST",url:C(this.serverUrl,"/enrollment-requests/cancel"),agentToken:null,body:{deviceSecret:e},signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:Gr})}};import{spawn as nd}from"node:child_process";var Ke=m("browser-open");function Mt(n){return n!==void 0&&n!==""}i(Mt,"isSet");function rd(n,e){return!(Mt(n.SSH_CONNECTION)||Mt(n.SSH_TTY)||e==="linux"&&!Mt(n.DISPLAY)&&!Mt(n.WAYLAND_DISPLAY))}i(rd,"shouldAttemptBrowserOpen");var od=/[&|^<>"'` ]/;function id(n){let e;try{e=new URL(n)}catch{return!1}return e.protocol!=="http:"&&e.protocol!=="https:"||n!==e.href?!1:!od.test(n)}i(id,"isSpawnSafeUrl");function sd(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(sd,"browserOpenCommand");function Ho(n,e,t){if(!rd(e,t)){Ke.debug("Not opening a browser: this host has no desktop to open one on",{platform:t});return}if(!id(n)){Ke.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=sd(n,t);if(r===null){Ke.debug("Not opening a browser: no opener is defined for this platform",{platform:t});return}try{let o=nd(r.command,[...r.args],{detached:!0,stdio:"ignore"});o.on("error",s=>{Ke.debug("Could not start the browser; the approval URL was printed instead",{platform:t,command:r.command,err:s.message})}),o.unref()}catch(o){Ke.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(Ho,"openVerificationUrl");var ad=30,ld=5;function Vo(n){return{intervalSec:n.pollIntervalSec,deadlineMs:n.timeoutSec===null?n.expiresAtMs:Math.min(n.expiresAtMs,n.nowMs+n.timeoutSec*1e3)}}i(Vo,"initialPollSchedule");function $t(n,e){if(e.kind==="pending")return{state:n,delayMs:n.intervalSec*1e3};if(e.kind==="slow_down"){let r=n.intervalSec+ld,o=e.retryAfterSec!==null&&e.retryAfterSec>r?e.retryAfterSec:r,s=Math.min(o,ad);return{state:{intervalSec:s,deadlineMs:n.deadlineMs},delayMs:s*1e3}}let t=ae(e.attempt,e.rng);return{state:n,delayMs:Math.max(n.intervalSec*1e3,t)}}i($t,"nextPollDelayMs");function Jo(n,e){return e>=n.deadlineMs}i(Jo,"isDeadlinePassed");function Yo(n,e,t){return Math.max(0,Math.min(e,n.deadlineMs-t))}i(Yo,"clampDelayToDeadline");var Ce=m("device-enrollment"),ud=24,md=2e3,_n=0,Pe=1,zo=130,pd="This machine is already enrolled. Start the daemon with: progon-agent start",hd="Enrollment was denied in the browser. Nothing was created on this machine.",fd="Cancelled. Nothing was saved on this machine.",gd="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 Xo(n){return`Enrollment request expired. Run: progon-agent enroll --server ${n}`}i(Xo,"expiredLine");function wd(n,e,t){return`This machine is already enrolled against ${n}, not ${e}. An agent credential is only valid at the deployment that issued it, so nothing was requested from ${e}.
|
|
35
35
|
To enroll this machine for ${e} as well, give the second agent its own state directory: PROGON_RUNNER_STATE_DIR=<dir> progon-agent enroll --server ${e} \u2014 and give 'progon-agent start' the same variable, since that directory is where the second credential and its server live.
|
|
36
|
-
To move this machine to ${e} instead, remove the state file in ${
|
|
37
|
-
`),
|
|
38
|
-
`),
|
|
39
|
-
`),process.exit(
|
|
40
|
-
`):process.stdout.write(`${
|
|
41
|
-
`),
|
|
42
|
-
`),
|
|
43
|
-
`),
|
|
44
|
-
`),
|
|
45
|
-
`),
|
|
46
|
-
`),
|
|
47
|
-
`),
|
|
48
|
-
Confirmation code: ${
|
|
49
|
-
Approve at: ${
|
|
50
|
-
Waiting for approval (expires in ${
|
|
51
|
-
`)}i(
|
|
36
|
+
To move this machine to ${e} instead, remove the state file in ${t} first, then run: progon-agent enroll --server ${e}`}i(wd,"otherDeploymentLine");function yd(n,e){return`Timed out after ${n}s waiting for approval. The request is still open \u2014 approve at: ${e}`}i(yd,"timedOutLine");function _d(n){return`Enrollment could not be completed: the request was already used and no credential reached this machine. Run: progon-agent enroll --server ${n}`}i(_d,"alreadyCompletedLine");function Ed(n){return`Enrollment request is no longer valid. Run: progon-agent enroll --server ${n}`}i(Ed,"noLongerValidLine");async function Zo(n){let e=n.env??process.env;n.serverUrl!==void 0&&(process.env.PROGON_SERVER_URL=n.serverUrl);let t=he(),r=Ie(),o=e.PROGON_AGENT_ENROLL_CODE;if(o!==void 0&&o!=="")return bd(t,r,n.fetchImpl,n.rng);let s=F(t.stateDir);if(s!==null)return tt(s.serverUrl,t.serverUrl)?(process.stdout.write(`${pd}
|
|
37
|
+
`),_n):(process.stdout.write(`${wd(s.serverUrl,t.serverUrl,t.stateDir)}
|
|
38
|
+
`),Pe);let a=cd(ud).toString("base64url"),l=new Ut(n.fetchImpl===void 0?{serverUrl:t.serverUrl,machine:r}:{serverUrl:t.serverUrl,machine:r,fetchImpl:n.fetchImpl}),c=await l.create(Td(a));return kd(c),n.openBrowser&&Ho(c.verificationUrl,e,process.platform),Sd({client:l,config:t,created:c,deviceSecret:a,timeoutSec:n.timeoutSec,rng:n.rng})}i(Zo,"runDeviceEnrollment");async function Sd(n){let{client:e,config:t,created:r,deviceSecret:o,timeoutSec:s,rng:a}=n,l=Date.parse(r.expiresAt),c=Vo({pollIntervalSec:r.pollIntervalSec,expiresAtMs:l,timeoutSec:s,nowMs:Date.now()}),w=c.intervalSec*1e3,f=0,g={signal:null},h=new AbortController,v=i(k=>{g.signal!==null&&(process.stderr.write(`${gd}
|
|
39
|
+
`),process.exit(zo)),g.signal=k,h.abort()},"onSignal");process.on("SIGINT",v),process.on("SIGTERM",v);try{for(;;){if(await Be(Yo(c,w,Date.now()),h.signal),g.signal!==null)return await Rd(e,o,g.signal);if(Jo(c,Date.now()))return s!==null&&c.deadlineMs<l?process.stdout.write(`${yd(s,r.verificationUrl)}
|
|
40
|
+
`):process.stdout.write(`${Xo(t.serverUrl)}
|
|
41
|
+
`),Pe;let k;try{k=await e.poll(o)}catch(T){if(T instanceof _e)return process.stdout.write(`${hd}
|
|
42
|
+
`),Pe;if(T instanceof Ee)return process.stdout.write(`${Xo(t.serverUrl)}
|
|
43
|
+
`),Pe;if(T instanceof Se)return Ce.warn("The enrollment request was already completed on the server; no credential reached this machine and nothing was saved",{requestId:r.requestId,errorCode:T.errorCode,status:T.status}),process.stdout.write(`${_d(t.serverUrl)}
|
|
44
|
+
`),Pe;if(T instanceof Re)return Ce.warn("The server no longer recognises this enrollment request",{requestId:r.requestId,errorCode:T.errorCode,status:T.status}),process.stdout.write(`${Ed(t.serverUrl)}
|
|
45
|
+
`),Pe;if(T instanceof ye){let De=$t(c,{kind:"slow_down",retryAfterSec:T.retryAfterSec});c=De.state,w=De.delayMs,Ce.warn("The server asked this machine to poll more slowly",{intervalSec:c.intervalSec,retryAfterSec:T.retryAfterSec});continue}if(T instanceof j||T instanceof R&&T.status>=500){let De=$t(c,{kind:"transport_error",attempt:f,rng:a});f+=1,c=De.state,w=De.delayMs,Ce.warn("The enrollment poll failed; retrying until the request expires",{attempt:f,delayMs:w,err:T.message});continue}throw T}if(k.kind==="enrolled")return pe(t.stateDir,{agentId:k.credential.agentId,agentToken:k.credential.agentToken,protocolVersion:k.credential.protocolVersion,serverUrl:t.serverUrl,tokenRotatedAt:null}),process.stdout.write(`Enrolled into ${k.approval.companyName} (approved by ${k.approval.approvedByEmail}). Start the daemon: progon-agent start
|
|
46
|
+
`),_n;f=0;let qe=$t(c,{kind:"pending"});c=qe.state,w=qe.delayMs}}finally{process.off("SIGINT",v),process.off("SIGTERM",v)}}i(Sd,"waitForApproval");async function Rd(n,e,t){try{await xe({operation:"device enrollment cancel",timeoutMs:md,work:i(()=>n.cancel(e),"work")})}catch(r){Ce.warn("The enrollment request could not be withdrawn on the server; it expires on its own within its TTL and no agent was created",{signal:t,err:r instanceof Error?r.message:String(r)})}return process.stdout.write(`${fd}
|
|
47
|
+
`),zo}i(Rd,"cancelRequest");async function bd(n,e,t,r){let o=await Te({config:n,machine:e,fetchImpl:t,rng:r});return xt(o,n),Ce.info("This machine is enrolled \u2014 start the daemon with: progon-agent start",{agentId:o.agentId,hostname:e.hostname,stateDir:n.stateDir}),_n}i(bd,"redeemLegacyEnrollmentCode");function kd(n){process.stdout.write(`Enrollment requested for this machine.
|
|
48
|
+
Confirmation code: ${n.userCode}
|
|
49
|
+
Approve at: ${n.verificationUrl}
|
|
50
|
+
Waiting for approval (expires in ${vd(n.expiresAt)})...
|
|
51
|
+
`)}i(kd,"printRequestOpened");function vd(n){let e=Date.parse(n)-Date.now();return`${Math.ceil(e/6e4)}m`}i(vd,"describeExpiry");function Td(n){return dd("sha256").update(n,"utf8").digest("hex")}i(Td,"sha256Hex");var Ad=m("cli"),Qo=`progon-agent \u2014 the Progon local agent (CONTRACT-la \xA78)
|
|
52
52
|
|
|
53
53
|
Usage:
|
|
54
54
|
progon-agent enroll <code> [--server <url>] Redeem a one-shot enrollment code (\xA75.1) and
|
|
@@ -113,10 +113,10 @@ Environment (see CONTRACT-la \xA78 for the full list):
|
|
|
113
113
|
name one (\xA71 D-C, \xA715 A30.1).
|
|
114
114
|
PROGON_AGENT_TOKEN optional \u2014 an existing credential, takes precedence over the
|
|
115
115
|
state file and over enrollment.
|
|
116
|
-
PROGON_AGENT_HEADFUL optional \u2014 show the browser on this machine's desktop.`;function
|
|
116
|
+
PROGON_AGENT_HEADFUL optional \u2014 show the browser on this machine's desktop.`;function ri(n){let[e,...t]=n;return e===void 0||e==="--help"||e==="-h"||e==="help"?{kind:"usage",reason:null}:e==="start"?t.length>0?{kind:"usage",reason:"'start' takes no arguments"}:{kind:"start"}:e==="install-browser"?t.length>0?{kind:"usage",reason:"'install-browser' takes no arguments"}:{kind:"install-browser"}:e==="enroll"?Nd(t):{kind:"usage",reason:`unknown command '${e}'`}}i(ri,"parseCliArgs");function Od(n){return n.startsWith("-")&&n.length<32}i(Od,"isOptionInCodeSlot");function Nd(n){let[e,...t]=n;if(e===void 0||Od(e))return Pd(n);if(t.length===0)return{kind:"enroll",code:e,serverUrl:void 0};let[r,o,...s]=t;return r!=="--server"?{kind:"usage",reason:`unknown option '${String(r)}' for 'enroll'`}:o===void 0?{kind:"usage",reason:"'--server' needs a URL"}:s.length>0?{kind:"usage",reason:"unexpected arguments after '--server'"}:{kind:"enroll",code:e,serverUrl:o}}i(Nd,"parseEnroll");var ei=1,ti=3600;function Pd(n){let e,t=!0,r=null;for(let o=0;o<n.length;o+=1){let s=n[o];if(s==="--no-open"){t=!1;continue}if(s==="--server"){let a=n[o+1];if(a===void 0)return{kind:"usage",reason:"'--server' needs a URL"};e=a,o+=1;continue}if(s==="--timeout"){let a=n[o+1];if(a===void 0)return{kind:"usage",reason:"'--timeout' needs a number of seconds"};if(!/^[0-9]+$/.test(a))return{kind:"usage",reason:`'--timeout' takes a whole number of seconds, got '${a}'`};let l=Number(a);if(l<ei||l>ti)return{kind:"usage",reason:`'--timeout' must be between ${ei} and ${ti} seconds, got '${a}'`};r=l,o+=1;continue}return{kind:"usage",reason:`unknown option '${String(s)}' for 'enroll'`}}return{kind:"enroll-device",serverUrl:e,openBrowser:t,timeoutSec:r}}i(Pd,"parseEnrollDevice");async function Cd(n){let e=ri(n);switch(e.kind){case"usage":return e.reason===null?(process.stdout.write(`${Qo}
|
|
117
117
|
`),0):(process.stderr.write(`progon-agent: ${e.reason}
|
|
118
118
|
|
|
119
|
-
${
|
|
120
|
-
`),2);case"enroll":return
|
|
121
|
-
`;let o=
|
|
122
|
-
`}i(
|
|
119
|
+
${Qo}
|
|
120
|
+
`),2);case"enroll":return Ld(e.code,e.serverUrl);case"enroll-device":return Zo({serverUrl:e.serverUrl,openBrowser:e.openBrowser,timeoutSec:e.timeoutSec});case"install-browser":return Dd();case"start":return jo()}}i(Cd,"runAgentCli");async function Dd(){return await Ye({stdio:"inherit"}),0}i(Dd,"installBrowser");async function Ld(n,e){process.env.PROGON_AGENT_ENROLL_CODE=n,e!==void 0&&(process.env.PROGON_SERVER_URL=e);let t=he(),r=Ie(),o=await Te({config:t,machine:r});return xt(o,t),Ad.info("This machine is enrolled \u2014 start the daemon with: progon-agent start",{agentId:o.agentId,hostname:r.hostname,stateDir:t.stateDir}),0}i(Ld,"enrollThisMachine");function Gd(n,e){let t=$(n instanceof Error?n.message:String(n));if((e.kind==="enroll"||e.kind==="enroll-device")&&n instanceof p)return`${t}
|
|
121
|
+
`;let o=n instanceof Error?n.stack:void 0;return JSON.stringify({level:"fatal",module:"cli",msg:"progon-agent failed",err:t,stack:o===void 0?void 0:$(o)})+`
|
|
122
|
+
`}i(Gd,"formatCliFailure");function Ud(n){Cd(n).then(e=>{e!==null&&process.exit(e)}).catch(e=>{process.stderr.write(Gd(e,ri(n))),process.exit(1)})}i(Ud,"runAgentCliProcess");var ni=process.argv[1];ni!==void 0&&import.meta.url===xd(Id(ni)).href&&Ud(process.argv.slice(2));export{Gd as formatCliFailure,ri as parseCliArgs,Cd as runAgentCli,Ud as runAgentCliProcess};
|