progon-agent 1.5.2 → 1.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/supervisor/cli.js +75 -75
- package/extension-bundle.json +3 -3
- package/extension-dist/background/background.js +101 -95
- package/extension-dist/card/card.html +10 -9
- package/extension-dist/card/card.js +3 -3
- package/extension-dist/chunks/shared-B3glEBMw.js +1 -0
- package/extension-dist/chunks/shared-B9oC2P3-.js +8 -0
- package/extension-dist/chunks/shared-BByPq6Kh.js +1 -0
- package/extension-dist/chunks/shared-BMIAtDPv.js +45 -0
- package/extension-dist/chunks/shared-BTOXSk0k.js +118 -0
- package/extension-dist/chunks/{shared-VvEftNwZ.js → shared-C-Q9DKcM.js} +1 -1
- package/extension-dist/chunks/shared-C4rk8dhz.js +1 -0
- package/extension-dist/chunks/shared-CHDbyhV4.js +1 -0
- package/extension-dist/chunks/shared-CmGCWsjS.js +15 -0
- package/extension-dist/chunks/shared-D7P2v9Mb.js +372 -0
- package/extension-dist/chunks/shared-DKBOqKL2.css +1 -0
- package/extension-dist/chunks/shared-Dnq0mR_F.css +1 -0
- package/extension-dist/chunks/shared-Dor6Qf-t.js +1 -0
- package/extension-dist/chunks/shared-DwL_iWMx.js +1 -0
- package/extension-dist/chunks/shared-GBy7ssZb.js +1 -0
- package/extension-dist/chunks/shared-gmwevruS.js +159 -0
- package/extension-dist/chunks/shared-iMtAwxmT.js +351 -0
- package/extension-dist/chunks/shared-mCuRTIv8.js +129 -0
- package/extension-dist/chunks/shared-rQyAr3p-.js +1 -0
- package/extension-dist/chunks/shared-yvJVPBBs.css +1 -0
- package/extension-dist/content/content.js +205 -205
- package/extension-dist/content/frame.js +80 -80
- package/extension-dist/manifest.json +32 -29
- package/extension-dist/offscreen/offscreen.html +3 -2
- package/extension-dist/offscreen/offscreen.js +1 -1
- package/extension-dist/popup/popup.css +1 -1
- package/extension-dist/popup/popup.html +9 -8
- package/extension-dist/popup/popup.js +9 -3
- package/extension-dist/sidepanel/sidepanel.css +1 -1
- package/extension-dist/sidepanel/sidepanel.html +12 -11
- package/extension-dist/sidepanel/sidepanel.js +1 -1
- package/extension-dist/workspace/workspace.html +13 -11
- package/extension-dist/workspace/workspace.js +48 -54
- package/npm-shrinkwrap.json +2 -2
- package/package.json +2 -2
- package/extension-dist/chunks/shared--PKAvBPy.js +0 -1
- package/extension-dist/chunks/shared-0jT00uC5.js +0 -317
- package/extension-dist/chunks/shared-8TdX8bnw.js +0 -1
- package/extension-dist/chunks/shared-BBwL-FWr.js +0 -8
- package/extension-dist/chunks/shared-BECVQaqd.js +0 -1
- package/extension-dist/chunks/shared-BYkDbcM2.js +0 -372
- package/extension-dist/chunks/shared-BdaUsVif.css +0 -1
- package/extension-dist/chunks/shared-CDlAJRnF.js +0 -117
- package/extension-dist/chunks/shared-CQ5Ygj2p.js +0 -1
- package/extension-dist/chunks/shared-CnMBv8Ku.js +0 -1
- package/extension-dist/chunks/shared-CyNKhHOY.js +0 -1
- package/extension-dist/chunks/shared-D3X5MuUz.js +0 -1
- package/extension-dist/chunks/shared-D7GfVHk0.js +0 -129
- package/extension-dist/chunks/shared-U9lBnzuH.js +0 -33
- package/extension-dist/chunks/shared-fJPHxpB5.css +0 -1
- package/extension-dist/chunks/shared-o0-3vI--.js +0 -193
- package/extension-dist/chunks/shared-uKTblxo0.js +0 -15
package/dist/supervisor/cli.js
CHANGED
|
@@ -2,18 +2,18 @@
|
|
|
2
2
|
const __runnerRoot = new URL('../../', import.meta.url);
|
|
3
3
|
if ((await import('node:fs')).existsSync(new URL('src/supervisor/cli.ts', __runnerRoot))) {
|
|
4
4
|
const { fingerprint } = await import(new URL('scripts/build-provenance.mjs', __runnerRoot));
|
|
5
|
-
if (fingerprint((await import('node:url')).fileURLToPath(__runnerRoot)) !== "
|
|
5
|
+
if (fingerprint((await import('node:url')).fileURLToPath(__runnerRoot)) !== "b0756d0b7f9c878dd443166f56c19accb413c2290000bfcbb2d1bcada428da92") {
|
|
6
6
|
throw new Error('Runner build is stale. Run npm run build:publish before starting.');
|
|
7
7
|
}
|
|
8
8
|
}
|
|
9
|
-
var su=Object.defineProperty;var o=(t,e)=>su(t,"name",{value:e,configurable:!0});import{realpathSync as FS}from"node:fs";import{pathToFileURL as BS}from"node:url";import{z as es}from"zod";var au=/^[a-z_]{1,32}@\d{1,3}$/,ts=es.array(es.string().regex(au)).min(1).max(32),ns=["playback@1"],rs="swarm@1",os="swarm@2",is="scenario_launch@1",ss="browser_channel@1",as="task_launch@1",ls="conversation@1";import{z as v}from"zod";var vt=/^pgat_[0-9A-Za-z]{43}$/;var Ze="agent:command",Jn="agent:command-ack",cs="agent:active-job";import{z as f}from"zod";import{z as k}from"zod";import{z as y}from"zod";var lu=["running","pausing","paused","stopping","completed","cancelled","failed"],ds=y.enum(lu),us=["completed","cancelled","failed"],rE=y.enum(us),cu=["running","pausing","paused","stopping"],oE=y.enum(cu),du=["running","pausing","stopping"],iE=y.enum(du),uu=["paused",...us],sE=y.enum(uu),pu=["user","credits","user_credit_limit","provider_unavailable"],aE=y.enum(pu),mu=["exploring","curation","done"],lE=y.enum(mu),fu=["queued","running","done","failed","cancelled"],cE=y.enum(fu),hu=["done","failed","cancelled"],dE=y.enum(hu),gu=["lead_finished","user_cancelled","lead_failed"],uE=y.enum(gu);var yu=["none","attached","lost"],pE=y.enum(yu),wu=["idle","active","awaiting_user"],mE=y.enum(wu),Su=["atlas","make_auto","preset"],fE=y.enum(Su),Eu=["extension_atlas_card","extension_make_auto_modal","web_atlas_dialog","web_make_auto_dialog","web_job_repeat","chat","web_workflow_repeat","web_runs_prompt","web_test_run_dialog","web_map_dialog","web_scenarios_dialog","web_launch_request"],hE=y.enum(Eu),vu=["web_runs_prompt","web_test_run_dialog","web_map_dialog","web_scenarios_dialog","extension_atlas_card","extension_make_auto_modal","web_workflow_repeat","web_launch_request"],bu=y.enum(vu),_u=["web_runs_prompt","web_test_run_dialog","web_map_dialog","web_scenarios_dialog","extension_atlas_card","extension_make_auto_modal","web_workflow_repeat"],gE=y.enum(_u),yE=y.union([bu,y.literal("chat")]),ku=["browser","agent","none"],Ru=y.enum(ku),Tu=["browser","agent"],wE=y.enum(Tu),xu=["explore_app","find_bugs","create_tests","automate_scenarios","run_scenarios","custom"],SE=y.enum(xu),Iu=["file_bugs","write_tests","edit_project"],EE=y.enum(Iu),Ou=["text","auto"],vE=y.enum(Ou),Au=["project","scenarios","test_run","test_plan"],bE=y.enum(Au),Cu=["host_lost","awaiting_browser","awaiting_user","paused"],_E=y.enum(Cu),Pu=["window","mcp_agent","agent"],kE=y.enum(Pu),Nu=["opening","idle","busy","closing","closed"],RE=y.enum(Nu),Lu=["lead","user","window_closed","workflow_ended","workflow_paused","unit_ended"],TE=y.enum(Lu),Du=["lead","user","workflow_ended","no_connection","left"],xE=y.enum(Du),$u=["lead","user","workflow_ended","workflow_paused","unit_ended"],IE=y.enum($u),Uu=["lead","user","window_closed","workflow_ended","workflow_paused","no_connection","left","unit_ended"],OE=y.enum(Uu),Mu=["make_auto","atlas","run","agent","mcp_task","check_launch"],AE=y.enum(Mu);var Gu=["starting","running","ended"],CE=y.enum(Gu),Fu=["completed","cancelled","failed","start_failed","lost"],PE=y.enum(Fu),Bu=["user","lead","left","no_connection","workflow_ended","not_taken"],ju=y.enum(Bu);var Wu=["lead","user","window_closed","host_lost","host_refused","workflow_ended","workflow_paused"],NE=y.enum(Wu),Hu=["lead_choice","role_default"],LE=y.enum(Hu),Ku=["observe","main","dangerous"],DE=y.enum(Ku),Ju=["main","dangerous"],ps=y.enum(Ju);var Vu=["workflow.access_hint_lost","workflow.window_refused","workflow.tab_refused","workflow.scenario_needs_conversion","workflow.identity_busy","workflow.identity_not_set"],$E=y.enum(Vu),qu=["workflows.not_found","workflows.not_initiator","workflows.not_initiator_or_admin","workflows.worker_not_found","workflows.not_running","workflows.host_held","workflows.host_mismatch","workflows.host_lost","workflows.host_attached","workflows.identity_delivering","workflows.host_pending","workflows.executor_kind_mismatch","workflows.executor_mismatch","workflows.agent_mismatch","workflows.request_mismatch","workflows.scope_not_found","workflows.scope_forbidden","workflows.conversation_busy","workflows.not_preset","workflows.not_pausable","workflows.not_continuable","workflows.text_not_stored","workflows.last_stage_not_retryable","workflows.not_amendable","workflows.place_mismatch","workflows.auto_requires_browser","workflows.segment_changed","workflows.mcp_join_unavailable","workflows.mcp_code_invalid","workflows.mcp_code_used","workflows.mcp_agent_not_found","workflows.mcp_agent_disconnected","workflows.mcp_inbox_invalid_cursor","workflows.question_not_to_lead","workflows.device_handoff_not_found","workflows.device_step_already_reported","workflows.device_run_ended","workflows.mcp_task_not_found","workflows.mcp_task_ended","workflows.mcp_task_address_required"],UE=y.enum(qu),ME=y.object({status:ds}),Yu=y.object({status:ds}),Xu=["conversation_deleted","text_not_stored"],zu=y.enum(Xu),GE=Yu.extend({reason:zu.extract(["conversation_deleted"]).optional()}),FE=y.object({segment:y.number().int().min(1)}),BE=y.object({executorKind:Ru}),jE=y.object({reason:y.enum(["ended","no_browser"])}),WE=y.object({reason:y.literal("task_paused")}),HE=y.discriminatedUnion("outcome",[y.object({outcome:y.enum(["finished","stopped"]),lostReason:y.null()}),y.object({outcome:y.literal("lost"),lostReason:ju})]),KE=y.object({taskIds:y.array(y.uuid()).min(2)}),JE=y.object({stepNumber:y.number().int().min(1),currentStepNumber:y.number().int().min(1).nullable()}),VE=y.object({leaseExpiresAt:y.iso.datetime()}),qE=y.object({workflowId:y.uuid()}),YE=y.object({agentId:y.uuid()});var ZE=k.object({queueId:k.uuid(),projectId:k.uuid(),projectDomain:k.string().min(1),applicationId:k.uuid().nullable(),entryUrl:k.url({protocol:/^https?$/}),headful:k.boolean()}).strict(),ms=k.object({launchId:k.uuid(),projectId:k.uuid(),projectDomain:k.string().min(1),entryUrl:k.url({protocol:/^https?$/}),headful:k.boolean()}).strict(),fs=k.object({projectId:k.uuid(),projectDomain:k.string().min(1),entryUrl:k.url({protocol:/^https?$/}),standMode:ps,accountLabel:k.string().min(1),role:k.string().min(1),locale:k.string().min(1),viewportWidth:k.number().int().min(1),viewportHeight:k.number().int().min(1)}).strict(),Qu=k.object({...fs.shape,environmentId:k.uuid().nullable()}).strict(),ev=k.union([fs,Qu]),tv=k.object({workflowId:k.uuid(),entryUrl:k.url({protocol:/^https?$/}),headful:k.boolean()}).strict(),nv=k.object({conversationId:k.uuid(),headful:k.boolean()}).strict();import{z as bt}from"zod";import{z as De}from"zod";var hs=["passed","failed","infra","cancelled","abandoned"];var Zu=["queued","launching","in_progress"];var gs=["passed","failed"],ep=["before_hook_failed","no_start_page","no_path_for_page"],tp=["no_route_to_start_page","navigation_service_unavailable","scenario_load_failed","run_policy_unavailable","variables_load_failed","start_failed"],Po=[...ep,...tp],lv=De.enum(Po).exclude(["before_hook_failed"]),cv=De.object({executorFailureReason:De.literal("launch_error").optional()}).strict().default({});var dv=[...hs,...Zu];var uv=De.object({by:De.literal("human"),outcome:De.enum(gs)}).strict(),pv=De.object({outcome:De.enum(gs)}).strict();var np=["queued","launching","in_progress","completed","failed","cancelled"],yv=bt.enum(np);var rp=["queued","launching","in_progress"],ys=bt.enum(rp);var op=["claim_timeout","launch_timeout","launch_error","browser_gone","agent_lost","max_duration","killed","lease_lost","budget_exhausted",...Po,"result_not_saved","mcp_agent_disconnected","agent_revoked"],wv=bt.enum(op),ip=["launch_error","browser_gone","max_duration"],No=bt.enum(ip),sp=["name_not_resolved","unreachable","certificate","timeout","other"],ws=bt.enum(sp);var ap=["claim_timeout","launch_timeout","launch_error","browser_gone","agent_lost","max_duration","killed","stalled","capability_mismatch","subject_rejected","model_timeout","runs_not_started","credits_exhausted","tab_closed","slot_taken","ai_disabled","workflow_host_lost","agent_revoked"],lp=bt.enum(ap),cp=["workflow_host_lost"],Sv=lp.exclude(cp);var dp=f.enum(["darwin","linux","win32"]),up=f.enum(["x64","arm64"]),Es=f.enum(["official","debug"]),Tv=f.object({enrollmentCode:f.string().min(32),hostname:f.string().min(1).max(255),platform:dp,arch:up,agentVersion:f.string().min(1).max(30),protocolVersion:f.number().int().min(1)}).strict(),Vn=f.object({agentId:f.uuid(),agentToken:f.string().regex(vt),pollWaitSec:f.number().int().min(1).max(25),protocolVersion:f.literal(1)}).strict(),xv=f.object({waitSec:f.coerce.number().int().min(0).max(25).optional()}).strict(),vs=f.object({agent:f.object({revoked:f.boolean()}).strict(),run:f.union([f.null(),f.object({runId:f.uuid(),phase:ys,identities:f.array(f.object({identityId:f.uuid()}).strict()).optional(),launches:f.array(f.object({launchId:f.uuid()}).strict()).optional()}).strict()])}).strict(),Lo=f.object({v:f.literal(1),kind:f.literal("playback"),runId:f.uuid(),scenarioId:f.uuid(),projectId:f.uuid(),projectDomain:f.string().min(1),applicationId:f.uuid().nullable(),environmentId:f.uuid().nullable(),executionMode:f.literal("auto"),issuedAt:f.iso.datetime()}).strict(),Do=f.object({v:f.literal(1),kind:f.literal("scenario_launch"),runId:f.uuid(),issuedAt:f.iso.datetime(),...ms.shape}).strict(),$o=f.object({v:f.literal(1),kind:f.literal("swarm"),runId:f.uuid(),issuedAt:f.iso.datetime(),workflowId:f.uuid()}).strict(),pp=f.object({v:f.literal(1),kind:f.literal("task_identity"),runId:f.uuid(),issuedAt:f.iso.datetime(),workflowId:f.uuid(),identityId:f.uuid()}).strict(),mp=f.object({v:f.literal(1),kind:f.literal("task_launch"),runId:f.uuid(),issuedAt:f.iso.datetime(),workflowId:f.uuid(),launchId:f.uuid()}).strict(),Uo=f.object({v:f.literal(1),kind:f.literal("conversation"),runId:f.uuid(),issuedAt:f.iso.datetime(),conversationId:f.uuid()}).strict(),Iv=f.union([Lo,$o,Do,pp,mp,Uo]),fp={playback:!0,swarm:!0,scenario_launch:!0,task_identity:!0,task_launch:!0,conversation:!0},Ov=Object.keys(fp),Av=f.object({agentJobId:f.uuid(),updatedAt:f.iso.datetime()}).strict(),hp=f.enum(["invalid_envelope","dispatch_failed"]),bs=f.discriminatedUnion("outcome",[f.object({runId:f.uuid(),outcome:f.literal("dispatched")}).strict(),f.object({runId:f.uuid(),outcome:f.literal("rejected"),reason:hp}).strict()]),_s=f.object({cancelRequested:f.boolean(),killRequested:f.boolean()}).strict(),gp=2147483646,yp=f.object({stepId:f.uuid(),stepIndex:f.number().int().min(0).max(gp),status:f.enum(["passed","failed","skipped"]),failureCode:f.string().max(64).regex(/^[a-z0-9_]+$/).nullable(),notes:f.string().max(4e3).nullable(),startedAt:f.iso.datetime().nullable(),completedAt:f.iso.datetime().nullable()}).strict(),Cv=f.object({events:f.array(yp).min(1).max(50)}).strict(),Pv=f.object({updated:f.number().int().min(0),control:_s}).strict(),Nv=f.object({phase:f.enum(["running","paused"])}).strict(),Lv=f.object({control:_s}).strict(),Ss=f.string().max(500).optional(),Dv=f.discriminatedUnion("reason",[f.object({reason:f.literal(No.enum.launch_error),message:Ss,entryFailure:ws.optional()}).strict(),f.object({reason:No.exclude(["launch_error"]),message:Ss}).strict()]),ks=f.object({status:f.enum(["failed","already_terminal"])}).strict();var Bv=v.union([v.object({}).strict(),v.object({capabilities:ts}).strict()]);function qn(t){let{value:e}=t;e.command.runId!==e.runId&&t.issues.push({code:"custom",input:e.command.runId,path:["command","runId"],message:"command.runId must be the claimed runId \u2014 the agent and the extension must monitor the same unit of work"})}o(qn,"checkClaimRunIdAgreement");function wp(t){let{value:e}=t;e.command.projectId!==e.projectId&&t.issues.push({code:"custom",input:e.command.projectId,path:["command","projectId"],message:"command.projectId must be the claimed projectId"})}o(wp,"checkPlaybackClaimProjectAgreement");var Sp=v.object({runId:v.uuid(),scenarioId:v.uuid(),projectId:v.uuid(),applicationId:v.uuid().nullable(),projectDomain:v.string().min(1),entryUrl:v.url({protocol:/^https?$/}),environmentId:v.uuid().nullable(),runPurpose:Es,headful:v.boolean(),maxRunDurationSec:v.number().int().min(60).max(3600),extensionSession:v.object({accessToken:v.string().min(1),refreshToken:v.string().min(1)}).strict(),command:Lo}).strict().check(qn).check(wp),Yn=v.object({accessToken:v.string().min(1),refreshToken:v.string().min(1)}).strict(),Go=v.object({extensionSession:Yn}).strict(),Ep=v.object({kind:v.literal("swarm"),runId:v.uuid(),entryUrl:v.url({protocol:/^https?$/}),headful:v.boolean(),maxRunDurationSec:v.number().int().min(60).max(604800),extensionSession:Yn,command:$o}).strict().check(qn),vp=v.object({kind:v.literal("scenario_launch"),runId:v.uuid(),entryUrl:v.url({protocol:/^https?$/}),headful:v.boolean(),maxRunDurationSec:v.number().int().min(60).max(604800),extensionSession:Yn,command:Do}).strict().check(qn),bp=v.object({kind:v.literal("conversation"),runId:v.uuid(),headful:v.boolean(),maxRunDurationSec:v.number().int().min(60).max(604800),extensionSession:Yn,command:Uo}).strict().check(qn),Rs=v.union([Sp,Ep,vp,bp]);import{z as Ts}from"zod";var _p=["finished","cancelled","ai_disabled"],kp=Ts.enum(_p),Kv=Ts.object({outcome:kp}).strict();import{spawn as Np}from"node:child_process";import{existsSync as Lp}from"node:fs";import{createRequire as Dp}from"node:module";import{dirname as Ls,join as $p}from"node:path";var Rp=new Set(["token","agenttoken","accesstoken","refreshtoken","pgrttoken","jobtoken","authorization","secret","password","resolvedvariables","cookie","set-cookie","x-api-key","proxy-authorization","api-key"]),Tp=/\b(?:pgat_|rr_|pgrt_|pgci_|pat_|mcp_at_)[A-Za-z0-9_-]+/g,an="eyJ";function Is(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||t===95}o(Is,"isWordChar");function Os(t,e){let n=e;for(;n<t.length;){let r=t.charCodeAt(n);if(!Is(r)&&r!==45)break;n++}return n}o(Os,"base64UrlRunEnd");function xs(t,e){if(t[e]!==".")return-1;let n=Os(t,e+1);return n===e+1?-1:n}o(xs,"segmentEndAfterDot");function xp(t){let e=[],n=0,r=-1,i=t.indexOf(an);for(;i!==-1;){let s=i+an.length;if(i>0&&Is(t.charCodeAt(i-1))){i=t.indexOf(an,s);continue}r<s&&(r=Os(t,s));let l=r>s?xs(t,r):-1,c=l===-1?-1:xs(t,l);if(c===-1){i=t.indexOf(an,r);continue}e.push(t.slice(n,i),ln),n=c,i=t.indexOf(an,n)}return e.length===0?t:(e.push(t.slice(n)),e.join(""))}o(xp,"redactJwsSpans");var Ip=["token","secret","password","authorization","api_key","api-key","apikey"],Op=new RegExp(`([?&](?:${Ip.join("|")})=)([^&\\s]+)`,"gi"),Ap=/(\bhttps?:\/\/)[^\s/?#]*@/gi,ln="[REDACTED]";function As(t){let e=xp(t);return e=e.replace(Tp,ln),e=e.replace(Op,`$1${ln}`),e=e.replace(Ap,`$1${ln}@`),e}o(As,"redactValueString");function et(t){if(Array.isArray(t))return t.map(et);if(t!==null&&typeof t=="object"){let e=t,n={};for(let r of Object.keys(e))Rp.has(r.toLowerCase())?n[r]=ln:n[r]=et(e[r]);return n}return typeof t=="string"?As(t):t}o(et,"redactSecrets");function C(t){return As(t)}o(C,"redactSensitiveText");import Fo from"pino";var Cs=new Set(["trace","debug","info","warn","error","fatal","silent"]);function Cp(){let t=process.env.PROGON_LOG_LEVEL;return t!==void 0&&Cs.has(t)?t:process.env.NODE_ENV==="production"?"info":"debug"}o(Cp,"resolveLogLevel");function Pp(){if(process.env.NODE_ENV!=="production")return{target:"pino-pretty",options:{translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname"}}}o(Pp,"buildTransport");var Ps={paths:["token","agentToken","accessToken","refreshToken","pgrtToken","jobToken","authorization","secret","password","resolvedVariables","cookie","set-cookie","x-api-key","proxy-authorization","api-key","*.token","*.agentToken","*.accessToken","*.refreshToken","*.secret","*.password","*.authorization","*.cookie","*.set-cookie","*.x-api-key","*.proxy-authorization","*.api-key"],censor:"[REDACTED]"},Ns=Fo({name:"qa-runner",level:Cp(),transport:Pp(),base:{pid:process.pid},redact:Ps}),Bo=null;function jo(t,e){let n=null,r=o(()=>Bo===null?t:(n??=Bo.child(e),n),"sink");return{debug(i,s){s!==void 0?r().debug(et(s),i):r().debug(i)},info(i,s){s!==void 0?r().info(et(s),i):r().info(i)},warn(i,s){s!==void 0?r().warn(et(s),i):r().warn(i)},error(i,s){s!==void 0?r().error(et(s),i):r().error(i)},child(i){return jo(t.child(i),{...e,...i})}}}o(jo,"adaptPino");function w(t){let e={module:t};return jo(Ns.child(e),e)}o(w,"createLogger");var ib=jo(Ns,{});function Xn(){let t=process.env.PROGON_LOG_LEVEL;Bo=Fo({name:"qa-runner",level:t!==void 0&&Cs.has(t)?t:"silent",base:{pid:process.pid},redact:Ps},Fo.destination({dest:2,sync:!0}))}o(Xn,"routeLogsAwayFromStdout");var Wo=w("browser-provision"),Up=60*6e4,Q=class extends Error{static{o(this,"BrowserProvisionError")}exitCode;timedOut;constructor(e,n={}){super(e,{cause:n.cause}),this.name="BrowserProvisionError",this.exitCode=n.exitCode===void 0?null:n.exitCode,this.timedOut=n.timedOut===void 0?!1:n.timedOut}},Ds=[" - Behind a proxy? Set HTTPS_PROXY (and NO_PROXY for internal hosts) before starting the",' agent, as http://host:port or https://host:port \u2014 a scheme-less "host:port" is read as'," HTTP, and a SOCKS proxy is not one this agent can use (gateway/proxy-config.ts)."," - TLS intercepted by a corporate gateway? Point NODE_EXTRA_CA_CERTS at the root certificate."," - CDN blocked? Set PLAYWRIGHT_DOWNLOAD_HOST to an internal Playwright download mirror."," - Out of disk? Chromium needs roughly 500MB unpacked in the Playwright browsers cache"," (PLAYWRIGHT_BROWSERS_PATH, or the per-user default cache)."].join(`
|
|
10
|
-
`);function Ho(){let t=
|
|
9
|
+
var iu=Object.defineProperty;var o=(t,e)=>iu(t,"name",{value:e,configurable:!0});import{realpathSync as GS}from"node:fs";import{pathToFileURL as FS}from"node:url";import{z as es}from"zod";var su=/^[a-z_]{1,32}@\d{1,3}$/,ts=es.array(es.string().regex(su)).min(1).max(32),ns=["playback@1"],rs="swarm@1",os="swarm@2",is="scenario_launch@1",ss="browser_channel@1",as="task_launch@1",ls="conversation@1";import{z as v}from"zod";var vt=/^pgat_[0-9A-Za-z]{43}$/;var Ze="agent:command",Vn="agent:command-ack",cs="agent:active-job";import{z as f}from"zod";import{z as k}from"zod";import{z as y}from"zod";var au=["running","pausing","paused","stopping","completed","cancelled","failed"],ds=y.enum(au),us=["completed","cancelled","failed"],nE=y.enum(us),lu=["running","pausing","paused","stopping"],rE=y.enum(lu),cu=["running","pausing","stopping"],oE=y.enum(cu),du=["paused",...us],iE=y.enum(du),uu=["user","credits","user_credit_limit","provider_unavailable"],sE=y.enum(uu),pu=["exploring","curation","done"],aE=y.enum(pu),mu=["queued","running","done","failed","cancelled"],lE=y.enum(mu),fu=["done","failed","cancelled"],cE=y.enum(fu),hu=["lead_finished","user_cancelled","lead_failed"],dE=y.enum(hu);var gu=["none","attached","lost"],uE=y.enum(gu),yu=["idle","active","awaiting_user"],pE=y.enum(yu),wu=["atlas","make_auto","preset"],mE=y.enum(wu),Su=["extension_atlas_card","extension_make_auto_modal","web_atlas_dialog","web_make_auto_dialog","web_job_repeat","chat","web_workflow_repeat","web_runs_prompt","web_test_run_dialog","web_map_dialog","web_scenarios_dialog","web_launch_request"],fE=y.enum(Su),Eu=["web_runs_prompt","web_test_run_dialog","web_map_dialog","web_scenarios_dialog","extension_atlas_card","extension_make_auto_modal","web_workflow_repeat","web_launch_request"],vu=y.enum(Eu),bu=["web_runs_prompt","web_test_run_dialog","web_map_dialog","web_scenarios_dialog","extension_atlas_card","extension_make_auto_modal","web_workflow_repeat"],hE=y.enum(bu),gE=y.union([vu,y.literal("chat")]),_u=["browser","agent","none"],ku=y.enum(_u),Ru=["browser","agent"],yE=y.enum(Ru),Tu=["explore_app","find_bugs","create_tests","automate_scenarios","run_scenarios","custom"],wE=y.enum(Tu),xu=["file_bugs","write_tests","edit_project"],SE=y.enum(xu),Iu=["text","auto"],EE=y.enum(Iu),Ou=["project","scenarios","test_run","test_plan"],vE=y.enum(Ou),Au=["host_lost","awaiting_browser","awaiting_user","paused"],bE=y.enum(Au),Cu=["window","mcp_agent","agent"],_E=y.enum(Cu),Pu=["opening","idle","busy","closing","closed"],kE=y.enum(Pu),Nu=["lead","user","window_closed","workflow_ended","workflow_paused","unit_ended"],RE=y.enum(Nu),Lu=["lead","user","workflow_ended","no_connection","left"],TE=y.enum(Lu),Du=["lead","user","workflow_ended","workflow_paused","unit_ended"],xE=y.enum(Du),$u=["lead","user","window_closed","workflow_ended","workflow_paused","no_connection","left","unit_ended"],IE=y.enum($u),Uu=["make_auto","atlas","run","agent","mcp_task","check_launch"],OE=y.enum(Uu);var Mu=["starting","running","ended"],AE=y.enum(Mu),Gu=["completed","cancelled","failed","start_failed","lost"],CE=y.enum(Gu),Fu=["user","lead","left","no_connection","workflow_ended","not_taken"],Bu=y.enum(Fu);var ju=["lead","user","window_closed","host_lost","host_refused","workflow_ended","workflow_paused"],PE=y.enum(ju),Wu=["lead_choice","role_default"],NE=y.enum(Wu),Hu=["observe","main","dangerous"],LE=y.enum(Hu),Ju=["main","dangerous"],ps=y.enum(Ju);var Ku=["workflow.access_hint_lost","workflow.window_refused","workflow.tab_refused","workflow.scenario_needs_conversion","workflow.identity_busy","workflow.identity_not_set"],DE=y.enum(Ku),Vu=["workflows.not_found","workflows.not_initiator","workflows.not_initiator_or_admin","workflows.worker_not_found","workflows.not_running","workflows.host_held","workflows.host_mismatch","workflows.host_lost","workflows.host_attached","workflows.identity_delivering","workflows.host_pending","workflows.executor_kind_mismatch","workflows.executor_mismatch","workflows.agent_mismatch","workflows.request_mismatch","workflows.scope_not_found","workflows.scope_forbidden","workflows.conversation_busy","workflows.not_preset","workflows.not_pausable","workflows.not_continuable","workflows.text_not_stored","workflows.last_stage_not_retryable","workflows.not_amendable","workflows.place_mismatch","workflows.auto_requires_browser","workflows.segment_changed","workflows.mcp_join_unavailable","workflows.mcp_code_invalid","workflows.mcp_code_used","workflows.mcp_agent_not_found","workflows.mcp_agent_disconnected","workflows.mcp_inbox_invalid_cursor","workflows.question_not_to_lead","workflows.device_handoff_not_found","workflows.device_step_already_reported","workflows.device_run_ended","workflows.mcp_task_not_found","workflows.mcp_task_ended","workflows.mcp_task_address_required"],$E=y.enum(Vu),UE=y.object({status:ds}),qu=y.object({status:ds}),Yu=["conversation_deleted","text_not_stored"],Xu=y.enum(Yu),ME=qu.extend({reason:Xu.extract(["conversation_deleted"]).optional()}),GE=y.object({segment:y.number().int().min(1)}),FE=y.object({executorKind:ku}),BE=y.object({reason:y.enum(["ended","no_browser"])}),jE=y.object({reason:y.literal("task_paused")}),WE=y.discriminatedUnion("outcome",[y.object({outcome:y.enum(["finished","stopped"]),lostReason:y.null()}),y.object({outcome:y.literal("lost"),lostReason:Bu})]),HE=y.object({taskIds:y.array(y.uuid()).min(2)}),JE=y.object({stepNumber:y.number().int().min(1),currentStepNumber:y.number().int().min(1).nullable()}),KE=y.object({leaseExpiresAt:y.iso.datetime()}),VE=y.object({workflowId:y.uuid()}),qE=y.object({agentId:y.uuid()});var QE=k.object({queueId:k.uuid(),projectId:k.uuid(),projectDomain:k.string().min(1),applicationId:k.uuid().nullable(),entryUrl:k.url({protocol:/^https?$/}),headful:k.boolean()}).strict(),ms=k.object({launchId:k.uuid(),projectId:k.uuid(),projectDomain:k.string().min(1),entryUrl:k.url({protocol:/^https?$/}),headful:k.boolean()}).strict(),fs=k.object({projectId:k.uuid(),projectDomain:k.string().min(1),entryUrl:k.url({protocol:/^https?$/}),standMode:ps,accountLabel:k.string().min(1),role:k.string().min(1),locale:k.string().min(1),viewportWidth:k.number().int().min(1),viewportHeight:k.number().int().min(1)}).strict(),zu=k.object({...fs.shape,environmentId:k.uuid().nullable()}).strict(),ZE=k.union([fs,zu]),ev=k.object({workflowId:k.uuid(),entryUrl:k.url({protocol:/^https?$/}),headful:k.boolean()}).strict(),tv=k.object({conversationId:k.uuid(),headful:k.boolean()}).strict();import{z as bt}from"zod";import{z as De}from"zod";var hs=["passed","failed","infra","cancelled","abandoned"];var Qu=["queued","launching","in_progress"];var gs=["passed","failed"],Zu=["before_hook_failed","no_start_page","no_path_for_page"],ep=["no_route_to_start_page","navigation_service_unavailable","scenario_load_failed","run_policy_unavailable","variables_load_failed","start_failed"],Po=[...Zu,...ep],av=De.enum(Po).exclude(["before_hook_failed"]),lv=De.object({executorFailureReason:De.literal("launch_error").optional()}).strict().default({});var cv=[...hs,...Qu];var dv=De.object({by:De.literal("human"),outcome:De.enum(gs)}).strict(),uv=De.object({outcome:De.enum(gs)}).strict();var tp=["queued","launching","in_progress","completed","failed","cancelled"],gv=bt.enum(tp);var np=["queued","launching","in_progress"],ys=bt.enum(np);var rp=["claim_timeout","launch_timeout","launch_error","browser_gone","agent_lost","max_duration","killed","lease_lost","budget_exhausted",...Po,"result_not_saved","mcp_agent_disconnected","agent_revoked"],yv=bt.enum(rp),op=["launch_error","browser_gone","max_duration"],No=bt.enum(op),ip=["name_not_resolved","unreachable","certificate","timeout","other"],ws=bt.enum(ip);var sp=["claim_timeout","launch_timeout","launch_error","browser_gone","agent_lost","max_duration","killed","stalled","capability_mismatch","subject_rejected","model_timeout","runs_not_started","credits_exhausted","tab_closed","slot_taken","ai_disabled","workflow_host_lost","agent_revoked"],ap=bt.enum(sp),lp=["workflow_host_lost"],wv=ap.exclude(lp);var cp=f.enum(["darwin","linux","win32"]),dp=f.enum(["x64","arm64"]),Es=f.enum(["official","debug"]),Rv=f.object({enrollmentCode:f.string().min(32),hostname:f.string().min(1).max(255),platform:cp,arch:dp,agentVersion:f.string().min(1).max(30),protocolVersion:f.number().int().min(1)}).strict(),qn=f.object({agentId:f.uuid(),agentToken:f.string().regex(vt),pollWaitSec:f.number().int().min(1).max(25),protocolVersion:f.literal(1)}).strict(),Tv=f.object({waitSec:f.coerce.number().int().min(0).max(25).optional()}).strict(),vs=f.object({agent:f.object({revoked:f.boolean()}).strict(),run:f.union([f.null(),f.object({runId:f.uuid(),phase:ys,main:f.boolean().optional(),identities:f.array(f.object({identityId:f.uuid()}).strict()).optional(),launches:f.array(f.object({launchId:f.uuid()}).strict()).optional()}).strict()])}).strict(),Lo=f.object({v:f.literal(1),kind:f.literal("playback"),runId:f.uuid(),scenarioId:f.uuid(),projectId:f.uuid(),projectDomain:f.string().min(1),applicationId:f.uuid().nullable(),environmentId:f.uuid().nullable(),executionMode:f.literal("auto"),issuedAt:f.iso.datetime()}).strict(),Do=f.object({v:f.literal(1),kind:f.literal("scenario_launch"),runId:f.uuid(),issuedAt:f.iso.datetime(),...ms.shape}).strict(),$o=f.object({v:f.literal(1),kind:f.literal("swarm"),runId:f.uuid(),issuedAt:f.iso.datetime(),workflowId:f.uuid()}).strict(),up=f.object({v:f.literal(1),kind:f.literal("task_identity"),runId:f.uuid(),issuedAt:f.iso.datetime(),workflowId:f.uuid(),identityId:f.uuid()}).strict(),pp=f.object({v:f.literal(1),kind:f.literal("task_launch"),runId:f.uuid(),issuedAt:f.iso.datetime(),workflowId:f.uuid(),launchId:f.uuid()}).strict(),Uo=f.object({v:f.literal(1),kind:f.literal("conversation"),runId:f.uuid(),issuedAt:f.iso.datetime(),conversationId:f.uuid()}).strict(),xv=f.union([Lo,$o,Do,up,pp,Uo]),mp={playback:!0,swarm:!0,scenario_launch:!0,task_identity:!0,task_launch:!0,conversation:!0},Iv=Object.keys(mp),Ov=f.object({agentJobId:f.uuid(),updatedAt:f.iso.datetime()}).strict(),fp=f.enum(["invalid_envelope","dispatch_failed"]),bs=f.discriminatedUnion("outcome",[f.object({runId:f.uuid(),outcome:f.literal("dispatched")}).strict(),f.object({runId:f.uuid(),outcome:f.literal("rejected"),reason:fp}).strict()]),_s=f.object({cancelRequested:f.boolean(),killRequested:f.boolean()}).strict(),hp=2147483646,gp=f.object({stepId:f.uuid(),stepIndex:f.number().int().min(0).max(hp),status:f.enum(["passed","failed","skipped"]),failureCode:f.string().max(64).regex(/^[a-z0-9_]+$/).nullable(),notes:f.string().max(4e3).nullable(),startedAt:f.iso.datetime().nullable(),completedAt:f.iso.datetime().nullable()}).strict(),Av=f.object({events:f.array(gp).min(1).max(50)}).strict(),Cv=f.object({updated:f.number().int().min(0),control:_s}).strict(),Pv=f.object({phase:f.enum(["running","paused"])}).strict(),Nv=f.object({control:_s}).strict(),Ss=f.string().max(500).optional(),Lv=f.discriminatedUnion("reason",[f.object({reason:f.literal(No.enum.launch_error),message:Ss,entryFailure:ws.optional()}).strict(),f.object({reason:No.exclude(["launch_error"]),message:Ss}).strict()]),ks=f.object({status:f.enum(["failed","already_terminal"])}).strict();var Fv=v.union([v.object({}).strict(),v.object({capabilities:ts}).strict()]);function Yn(t){let{value:e}=t;e.command.runId!==e.runId&&t.issues.push({code:"custom",input:e.command.runId,path:["command","runId"],message:"command.runId must be the claimed runId \u2014 the agent and the extension must monitor the same unit of work"})}o(Yn,"checkClaimRunIdAgreement");function yp(t){let{value:e}=t;e.command.projectId!==e.projectId&&t.issues.push({code:"custom",input:e.command.projectId,path:["command","projectId"],message:"command.projectId must be the claimed projectId"})}o(yp,"checkPlaybackClaimProjectAgreement");var wp=v.object({runId:v.uuid(),scenarioId:v.uuid(),projectId:v.uuid(),applicationId:v.uuid().nullable(),projectDomain:v.string().min(1),entryUrl:v.url({protocol:/^https?$/}),environmentId:v.uuid().nullable(),runPurpose:Es,headful:v.boolean(),maxRunDurationSec:v.number().int().min(60).max(3600),extensionSession:v.object({accessToken:v.string().min(1),refreshToken:v.string().min(1)}).strict(),command:Lo}).strict().check(Yn).check(yp),Xn=v.object({accessToken:v.string().min(1),refreshToken:v.string().min(1)}).strict(),Go=v.object({extensionSession:Xn}).strict(),Sp=v.object({kind:v.literal("swarm"),runId:v.uuid(),entryUrl:v.url({protocol:/^https?$/}),headful:v.boolean(),maxRunDurationSec:v.number().int().min(60).max(604800),extensionSession:Xn,command:$o}).strict().check(Yn),Ep=v.object({kind:v.literal("scenario_launch"),runId:v.uuid(),entryUrl:v.url({protocol:/^https?$/}),headful:v.boolean(),maxRunDurationSec:v.number().int().min(60).max(604800),extensionSession:Xn,command:Do}).strict().check(Yn),vp=v.object({kind:v.literal("conversation"),runId:v.uuid(),headful:v.boolean(),maxRunDurationSec:v.number().int().min(60).max(604800),extensionSession:Xn,command:Uo}).strict().check(Yn),Rs=v.union([wp,Sp,Ep,vp]);import{z as Ts}from"zod";var bp=["finished","cancelled","ai_disabled"],_p=Ts.enum(bp),Hv=Ts.object({outcome:_p}).strict();import{spawn as Pp}from"node:child_process";import{existsSync as Np}from"node:fs";import{createRequire as Lp}from"node:module";import{dirname as Ls,join as Dp}from"node:path";var kp=new Set(["token","agenttoken","accesstoken","refreshtoken","pgrttoken","jobtoken","authorization","secret","password","resolvedvariables","cookie","set-cookie","x-api-key","proxy-authorization","api-key"]),Rp=/\b(?:pgat_|rr_|pgrt_|pgci_|pat_|mcp_at_)[A-Za-z0-9_-]+/g,ln="eyJ";function Is(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||t===95}o(Is,"isWordChar");function Os(t,e){let n=e;for(;n<t.length;){let r=t.charCodeAt(n);if(!Is(r)&&r!==45)break;n++}return n}o(Os,"base64UrlRunEnd");function xs(t,e){if(t[e]!==".")return-1;let n=Os(t,e+1);return n===e+1?-1:n}o(xs,"segmentEndAfterDot");function Tp(t){let e=[],n=0,r=-1,i=t.indexOf(ln);for(;i!==-1;){let s=i+ln.length;if(i>0&&Is(t.charCodeAt(i-1))){i=t.indexOf(ln,s);continue}r<s&&(r=Os(t,s));let l=r>s?xs(t,r):-1,c=l===-1?-1:xs(t,l);if(c===-1){i=t.indexOf(ln,r);continue}e.push(t.slice(n,i),cn),n=c,i=t.indexOf(ln,n)}return e.length===0?t:(e.push(t.slice(n)),e.join(""))}o(Tp,"redactJwsSpans");var xp=["token","secret","password","authorization","api_key","api-key","apikey"],Ip=new RegExp(`([?&](?:${xp.join("|")})=)([^&\\s]+)`,"gi"),Op=/(\bhttps?:\/\/)[^\s/?#]*@/gi,cn="[REDACTED]";function As(t){let e=Tp(t);return e=e.replace(Rp,cn),e=e.replace(Ip,`$1${cn}`),e=e.replace(Op,`$1${cn}@`),e}o(As,"redactValueString");function et(t){if(Array.isArray(t))return t.map(et);if(t!==null&&typeof t=="object"){let e=t,n={};for(let r of Object.keys(e))kp.has(r.toLowerCase())?n[r]=cn:n[r]=et(e[r]);return n}return typeof t=="string"?As(t):t}o(et,"redactSecrets");function C(t){return As(t)}o(C,"redactSensitiveText");import Fo from"pino";var Cs=new Set(["trace","debug","info","warn","error","fatal","silent"]);function Ap(){let t=process.env.PROGON_LOG_LEVEL;return t!==void 0&&Cs.has(t)?t:process.env.NODE_ENV==="production"?"info":"debug"}o(Ap,"resolveLogLevel");function Cp(){if(process.env.NODE_ENV!=="production")return{target:"pino-pretty",options:{translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname"}}}o(Cp,"buildTransport");var Ps={paths:["token","agentToken","accessToken","refreshToken","pgrtToken","jobToken","authorization","secret","password","resolvedVariables","cookie","set-cookie","x-api-key","proxy-authorization","api-key","*.token","*.agentToken","*.accessToken","*.refreshToken","*.secret","*.password","*.authorization","*.cookie","*.set-cookie","*.x-api-key","*.proxy-authorization","*.api-key"],censor:"[REDACTED]"},Ns=Fo({name:"qa-runner",level:Ap(),transport:Cp(),base:{pid:process.pid},redact:Ps}),Bo=null;function jo(t,e){let n=null,r=o(()=>Bo===null?t:(n??=Bo.child(e),n),"sink");return{debug(i,s){s!==void 0?r().debug(et(s),i):r().debug(i)},info(i,s){s!==void 0?r().info(et(s),i):r().info(i)},warn(i,s){s!==void 0?r().warn(et(s),i):r().warn(i)},error(i,s){s!==void 0?r().error(et(s),i):r().error(i)},child(i){return jo(t.child(i),{...e,...i})}}}o(jo,"adaptPino");function w(t){let e={module:t};return jo(Ns.child(e),e)}o(w,"createLogger");var ob=jo(Ns,{});function zn(){let t=process.env.PROGON_LOG_LEVEL;Bo=Fo({name:"qa-runner",level:t!==void 0&&Cs.has(t)?t:"silent",base:{pid:process.pid},redact:Ps},Fo.destination({dest:2,sync:!0}))}o(zn,"routeLogsAwayFromStdout");var Wo=w("browser-provision"),$p=60*6e4,Q=class extends Error{static{o(this,"BrowserProvisionError")}exitCode;timedOut;constructor(e,n={}){super(e,{cause:n.cause}),this.name="BrowserProvisionError",this.exitCode=n.exitCode===void 0?null:n.exitCode,this.timedOut=n.timedOut===void 0?!1:n.timedOut}},Ds=[" - Behind a proxy? Set HTTPS_PROXY (and NO_PROXY for internal hosts) before starting the",' agent, as http://host:port or https://host:port \u2014 a scheme-less "host:port" is read as'," HTTP, and a SOCKS proxy is not one this agent can use (gateway/proxy-config.ts)."," - TLS intercepted by a corporate gateway? Point NODE_EXTRA_CA_CERTS at the root certificate."," - CDN blocked? Set PLAYWRIGHT_DOWNLOAD_HOST to an internal Playwright download mirror."," - Out of disk? Chromium needs roughly 500MB unpacked in the Playwright browsers cache"," (PLAYWRIGHT_BROWSERS_PATH, or the per-user default cache)."].join(`
|
|
10
|
+
`);function Ho(){let t=Lp(import.meta.url),e;try{e=t.resolve("playwright-core/package.json")}catch(r){throw new Q(`[browser-provision] Cannot locate the 'playwright-core' package from ${import.meta.url}. It is a declared dependency of this agent \u2014 reinstall the package ('npm ci') rather than installing a browser by hand: the agent launches the revision THIS copy of playwright-core expects.`,{cause:r})}let n=Dp(Ls(e),"cli.js");if(!Np(n))throw new Q(`[browser-provision] 'playwright-core' resolved to ${Ls(e)} but its CLI is not at ${n}. That installation is incomplete or has been altered \u2014 reinstall it ('npm ci'). This agent installs Chromium through that CLI and through no other path (CONTRACT-la \xA715 A31.1).`);return{execPath:process.execPath,cliPath:n,args:["install","chromium","--no-shell"]}}o(Ho,"resolveInstallCommand");async function kt(t){let e=t.commandOverride===void 0?Ho():t.commandOverride,n=t.deadlineMs===void 0?$p:t.deadlineMs,r=t.stdio==="pipe"?[...e.args,"--no-progress"]:[...e.args],i=`${e.execPath} ${e.cliPath} ${r.join(" ")}`,s=Date.now();Wo.info("Provisioning Chromium",{cliPath:e.cliPath,args:r,deadlineMs:n});let l=Pp(e.execPath,[e.cliPath,...r],{env:process.env,stdio:["ignore","pipe","pipe"]}),{stdout:c,stderr:a}=l,d=t.stdio==="pipe"?Mp:Up;$s(c,"stdout",d),$s(a,"stderr",d);let u=!1,m=o(()=>{u=l.kill("SIGKILL")},"onAbort");t.signal?.aborted===!0?m():t.signal?.addEventListener("abort",m,{once:!0});let g=!1,E=setTimeout(()=>{g=!0,l.kill("SIGKILL")},n),S=new Map,b=o(()=>{for(let[N,z]of S)process.off(N,z);S.clear()},"removeSignalHandlers"),I=t.signal===void 0?["SIGTERM","SIGINT"]:[];for(let N of I){let z=o(()=>{l.kill("SIGKILL"),b(),process.stderr.write(JSON.stringify({level:"warn",module:"browser-provision",msg:"Chromium provisioning aborted by signal: the installer was killed, and the next start downloads again",signal:N,installerPid:l.pid})+`
|
|
11
11
|
`),process.kill(process.pid,N)},"handler");S.set(N,z),process.on(N,z)}try{await new Promise((N,z)=>{l.once("error",ue=>{z(new Q(`[browser-provision] Could not start the Playwright installer (${i}): ${ue.message}`,{cause:ue}))}),l.once("close",(ue,Et)=>{if(g){z(new Q(`[browser-provision] Chromium installation did not finish within ${n}ms and was killed (${i}). A stalled installer is a known Playwright failure mode (microsoft/playwright#40998) and usually means the download connection went silent rather than failing.
|
|
12
|
-
${Ds}`,{exitCode:ue,timedOut:!0}));return}if(ue===0){N();return}if(u&&t.signal!==void 0&&ue===null&&Et==="SIGKILL"){z(t.signal.reason);return}let
|
|
12
|
+
${Ds}`,{exitCode:ue,timedOut:!0}));return}if(ue===0){N();return}if(u&&t.signal!==void 0&&ue===null&&Et==="SIGKILL"){z(t.signal.reason);return}let ou=ue===null?`was terminated by signal ${String(Et)}`:`exited with code ${ue}`;z(new Q(`[browser-provision] Chromium could not be installed: the Playwright installer ${ou} (${i}). The agent cannot run scenarios without a browser and does not retry \u2014 a failed download is an environment condition, not a transient one.
|
|
13
13
|
${Ds}`,{exitCode:ue}))})})}finally{clearTimeout(E),t.signal?.removeEventListener("abort",m),b()}Wo.info("Chromium is provisioned",{durationMs:Date.now()-s})}o(kt,"provisionBrowser");function $s(t,e,n){let r="";t.setEncoding("utf8"),t.on("data",i=>{r+=i;let s=r.lastIndexOf(`
|
|
14
14
|
`);if(s===-1)return;let l=r.slice(0,s);r=r.slice(s+1);for(let c of l.split(`
|
|
15
|
-
`))n(c,e)}),t.on("end",()=>{let i=r;r="",n(i,e)})}o($s,"forwardLines");function
|
|
16
|
-
`)}o(Mp,"printLine");function Gp(t,e){let n=t.replace(/\r/g,"").trim();n!==""&&Wo.info("Chromium provisioning output",{stream:e,line:n})}o(Gp,"logLine");import{homedir as Dm}from"node:os";import{isAbsolute as ia,join as rr,resolve as $m}from"node:path";var p=class extends Error{static{o(this,"OperatorRefusalError")}};var Fp=new Set(["localhost","127.0.0.1","::1","[::1]"]);function Bp(t){return t.protocol==="https:"||t.protocol==="http:"&&Fp.has(t.hostname)}o(Bp,"usesTrustedHttpScheme");function ke(t){let e;try{e=new URL(t)}catch{throw new p("[config] PROGON_SERVER_URL is not a valid https:// URL.")}if(!Bp(e))throw new p(`[config] PROGON_SERVER_URL must use the https:// scheme (encrypted HTTP). http:// is only allowed for loopback hosts (localhost, 127.0.0.1, [::1]). Got scheme: ${JSON.stringify(e.protocol)} with host: ${JSON.stringify(e.hostname)}.`);if(e.host==="")throw new p(`[config] PROGON_SERVER_URL must include a non-empty host. Got: ${JSON.stringify(t)}.`);if(e.username!==""||e.password!=="")throw new p("[config] PROGON_SERVER_URL must not contain embedded credentials (userinfo). Use the PROGON_AGENT_TOKEN env var for authentication instead.");if(e.search!==""||e.hash!=="")throw new p(`[config] PROGON_SERVER_URL must be a base URL with no query string and no fragment \u2014 the agent-gateway routes are appended to it, and a query or a fragment would swallow them instead of preceding them. Got query ${JSON.stringify(e.search)} and fragment ${JSON.stringify(e.hash)}. Use scheme + host + optional path prefix only (https://host, https://host/prefix).`)}o(ke,"validateServerUrl");function cn(t){if(!vt.test(t))throw new p("[config] Agent token must match the pgat_ wire format (CONTRACT-la \xA75.1). Got a token that does not match this format. Ensure PROGON_AGENT_TOKEN was copied from the server correctly.")}o(cn,"validateRunnerToken");function Ko(t){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))throw new p(`[config] agentId must be a valid UUID (issued by the server at enroll). Got: ${JSON.stringify(t)}. The state file may be corrupted \u2014 remove it and re-enroll.`)}o(Ko,"validateRunnerMachineId");function Jo(t){if(t!==1)throw new p(`[config] Protocol version mismatch: state file records version ${t} but this daemon requires version ${1}. Remove the state file and re-enroll with the correct daemon version.`)}o(Jo,"validateProtocolVersion");import{Agent as jp,EnvHttpProxyAgent as Wp}from"undici";var Us=w("gateway-proxy"),Hp=["http_proxy","HTTP_PROXY"],Kp=["https_proxy","HTTPS_PROXY"],Jp=["no_proxy","NO_PROXY"];function Vp(t){return t.http!==void 0||t.https!==void 0}o(Vp,"gatewayIsProxied");var qp=/^[A-Za-z][A-Za-z0-9+.-]*:\/\//,Yp=/:\d+$/,Xp=/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)?[^/?#]*@/;function zp(t){let e=Xp.exec(t);if(e===null)return t;let n=e[1];return`${n===void 0?"":n}***@${t.slice(e[0].length)}`}o(zp,"withoutProxyCredentials");function Rt(t,e,n){return new p(`[config] ${t} does not name a proxy this agent can use: ${n}. Got: ${JSON.stringify(zp(e))}. Accepted: an absolute "http://host:port" (or "https://host:port"), or the scheme-less curl form "host:port", which is read as "http://host:port". The agent-gateway transport speaks HTTP proxying only \u2014 a SOCKS proxy cannot carry it. Unset ${t} to connect to the server directly.`)}o(Rt,"refuseProxyValue");function Ms(t,e){for(let n of e){let r=t[n];if(r!==void 0)return r===""?void 0:{variable:n,raw:r}}}o(Ms,"readProxyVariable");function Qp(t){for(let e of Jp){let n=t[e];if(n!==void 0)return n}}o(Qp,"readNoProxy");function Gs(t,e){if(qp.test(e)){let l;try{l=new URL(e)}catch{throw Rt(t,e,"it carries a scheme but is not a URL that parses")}if(l.protocol!=="http:"&&l.protocol!=="https:")throw Rt(t,e,`its scheme is ${JSON.stringify(l.protocol)}, not http: or https:`);if(l.hostname==="")throw Rt(t,e,"it names no host");return{variable:t,url:e,schemeCompleted:!1}}let n=e.search(/[/?#]/),r=n===-1?e:e.slice(0,n);if(!Yp.test(r))throw Rt(t,e,'it carries no scheme, so it is read as the curl "host:port" form, and it names no port');let i=`http://${e}`,s;try{s=new URL(i)}catch{throw Rt(t,e,'it is neither a URL nor a "host:port" pair')}if(s.hostname==="")throw Rt(t,e,"it names no host");return{variable:t,url:i,schemeCompleted:!0}}o(Gs,"parseProxyValue");function dn(t){let e=Ms(t,Hp),n=Ms(t,Kp);return{http:e===void 0?void 0:Gs(e.variable,e.raw),https:n===void 0?void 0:Gs(n.variable,n.raw),noProxy:Qp(t)}}o(dn,"resolveGatewayProxyConfig");function Fs(t,e,n){if(!Vp(t))return new jp(e);Us.info("Gateway traffic follows the proxy configured in this environment",{httpProxy:t.http!==void 0,httpsProxy:t.https!==void 0,noProxy:t.noProxy!==void 0});let r=[];for(let s of[t.http,t.https])s!==void 0&&s.schemeCompleted&&r.push(s.variable);r.length>0&&Us.info('A proxy variable carries no scheme and is read as an HTTP proxy (curl convention: "host:port" means "http://host:port")',{variables:r});let i={...e,...n===void 0?{}:{requestTls:{ca:n},proxyTls:{ca:n}},httpProxy:t.http?.url,httpsProxy:t.https?.url,noProxy:t.noProxy};return new Wp(i)}o(Fs,"createProxyAwareDispatcher");function zn(t){dn(t)}o(zn,"validateGatewayProxyEnv");import{X509Certificate as Zp}from"node:crypto";import{readFileSync as em,statSync as tm}from"node:fs";import{isAbsolute as nm}from"node:path";import{rootCertificates as Bs}from"node:tls";var rm=w("gateway-tls-trust"),Qn="PROGON_AGENT_EXTRA_CA_CERTS",js="NODE_EXTRA_CA_CERTS";function om(t,e,n){let r=`[config] ${Qn} does not name a certificate bundle this agent can use: ${e}. Got: ${JSON.stringify(t)}. Accepted: an ABSOLUTE path to a readable PEM file holding the corporate root certificate (one or more "-----BEGIN CERTIFICATE-----" blocks). It extends the trust of the agent's OWN connections to the Progon backend; it does not reach the browser, which trusts what the operating system trusts. Unset ${Qn} to trust only the public roots.`;return n===void 0?new p(r):new p(r,{cause:n})}o(om,"refuseExtraCaValue");function Zn(t){let e=t[Qn];if(e===void 0||e==="")return;let n=Ws(e);if("because"in n)throw om(e,n.because,n.cause);return{variable:Qn,path:e,pem:n.pem}}o(Zn,"resolveExtraCaTrust");function Ws(t){if(!nm(t))return{because:"it is not an absolute path, and a relative one would be resolved against the working directory the daemon happens to have been started in",cause:void 0};let e;try{e=tm(t)}catch(r){return{because:"it cannot be read",cause:r}}if(!e.isFile())return{because:"it is not a file",cause:void 0};let n;try{n=em(t,"utf8")}catch(r){return{because:"its contents could not be read",cause:r}}try{new Zp(n)}catch(r){return{because:"it does not hold a PEM certificate",cause:r}}return{pem:n}}o(Ws,"readCaBundle");function Hs(t){let e=t[js];if(e===void 0||e==="")return;let n=Ws(e);if(!("because"in n))return e;let r=n.cause instanceof Error?` (${n.cause.message})`:"";throw new p(`${js} does not name a certificate bundle every start of the agent can use: ${n.because}${r}. Got: ${JSON.stringify(e)}. Where Node cannot use the file it ignores it and trusts only the public roots, so behind a TLS-intercepting gateway the Chromium download and the agent's connections fail. Point it at an ABSOLUTE path to a readable PEM file with the corporate root certificate, or unset it.`,n.cause===void 0?void 0:{cause:n.cause})}o(Hs,"inspectNodeExtraCaCerts");function Ks(t){let e=Zn(t);if(e!==void 0)return rm.info("Trusting an extra certificate authority for the agent's own connections",{variable:e.variable,path:e.path,publicRootCount:Bs.length}),[...Bs,e.pem]}o(Ks,"readTrustedCaBundle");function er(t){Zn(t)}o(er,"validateExtraCaTrustEnv");import{readFileSync as cm}from"node:fs";import{dirname as dm,join as um}from"node:path";import{fileURLToPath as pm}from"node:url";function P(t){if(typeof t!="object"||t===null)return!1;let e=t.code;return e==="ENOENT"||e==="ENOTDIR"}o(P,"isAbsentPathError");import{statSync as im}from"node:fs";import{dirname as sm,join as am}from"node:path";var Js="package.json";function we(t){let e=t;for(;;){if(lm(e))return e;let n=sm(e);if(n===e)throw new Error(`[package-root] No ${Js} was found in ${t} or in any of its parent directories, so the root of the package this file belongs to cannot be determined. This is a packaging defect, not a configuration one: the module asking is supposed to be running from inside an installed or checked-out package.`);e=n}}o(we,"findPackageRoot");function lm(t){try{return im(am(t,Js)),!0}catch(e){if(P(e))return!1;throw e}}o(lm,"holdsPackageManifest");var mm="extension-bundle.json";function Tt(){return fm(um(we(dm(pm(import.meta.url))),mm))}o(Tt,"readBundledAppUrl");function fm(t){let e;try{e=cm(t,"utf-8")}catch(i){if(P(i))return null;throw new p(`[extension-bundle] ${t} exists but could not be read: ${String(i)}. It records the deployment this package was built for, so the agent cannot tell which Progon it belongs to until the file is readable. Check the permissions on the installed package, or reinstall it: npm i -g progon-agent@latest.`,{cause:i})}let n;try{n=JSON.parse(e)}catch(i){throw new p(`[extension-bundle] ${t} contains invalid JSON: ${String(i)}. This package's record of the deployment it was built for is damaged \u2014 reinstall it: npm i -g progon-agent@latest.`,{cause:i})}if(typeof n!="object"||n===null||Array.isArray(n)){let i=n===null?"null":Array.isArray(n)?"array":typeof n;throw new p(`[extension-bundle] ${t} must contain a JSON object, got: ${i}. Reinstall the package: npm i -g progon-agent@latest.`)}let r=n.appUrl;if(typeof r!="string"||r==="")throw new p(`[extension-bundle] ${t} has no usable 'appUrl' (expected a non-empty string). That field is the deployment this package was built for; without it the agent cannot tell which Progon it belongs to. Reinstall the package (npm i -g progon-agent@latest), or name the deployment explicitly with --server / PROGON_SERVER_URL.`);try{ke(r)}catch(i){throw new p(`[extension-bundle] ${t} has an invalid 'appUrl': ${String(i)}`,{cause:i})}return r}o(fm,"readBundledAppUrlFrom");import{unlinkSync as Nm}from"node:fs";import{readFileSync as _m,writeFileSync as km,renameSync as Rm,existsSync as Tm,fchmodSync as xm,openSync as qs,fsyncSync as Ys,closeSync as Xs,unlinkSync as Im}from"node:fs";import{join as zs}from"node:path";import{spawnSync as hm}from"node:child_process";import{chmodSync as gm,mkdirSync as ym}from"node:fs";import{resolve as wm}from"node:path";import{z as $e}from"zod";var tt="powershell.exe";function me(t){return`'${t.replace(/['‘’‚‛]/g,e=>e+e)}'`}o(me,"psQuote");function un(t){return Buffer.from(t,"utf16le").toString("base64")}o(un,"encodePowerShellCommand");var Sm=3e4,Vs=new Set;function xt(t){let e=wm(t);if(ym(e,{recursive:!0,mode:448}),process.platform!=="win32"){gm(e,448);return}Vs.has(e)||(bm(e),Vs.add(e))}o(xt,"makeStateDirPrivate");function Em(t){return`$ErrorActionPreference = 'Stop'
|
|
15
|
+
`))n(c,e)}),t.on("end",()=>{let i=r;r="",n(i,e)})}o($s,"forwardLines");function Up(t,e){t!==""&&process[e].write(`${C(t)}
|
|
16
|
+
`)}o(Up,"printLine");function Mp(t,e){let n=t.replace(/\r/g,"").trim();n!==""&&Wo.info("Chromium provisioning output",{stream:e,line:n})}o(Mp,"logLine");import{homedir as Lm}from"node:os";import{isAbsolute as ia,join as or,resolve as Dm}from"node:path";var p=class extends Error{static{o(this,"OperatorRefusalError")}};var Gp=new Set(["localhost","127.0.0.1","::1","[::1]"]);function Fp(t){return t.protocol==="https:"||t.protocol==="http:"&&Gp.has(t.hostname)}o(Fp,"usesTrustedHttpScheme");function Re(t){let e;try{e=new URL(t)}catch{throw new p("[config] PROGON_SERVER_URL is not a valid https:// URL.")}if(!Fp(e))throw new p(`[config] PROGON_SERVER_URL must use the https:// scheme (encrypted HTTP). http:// is only allowed for loopback hosts (localhost, 127.0.0.1, [::1]). Got scheme: ${JSON.stringify(e.protocol)} with host: ${JSON.stringify(e.hostname)}.`);if(e.host==="")throw new p(`[config] PROGON_SERVER_URL must include a non-empty host. Got: ${JSON.stringify(t)}.`);if(e.username!==""||e.password!=="")throw new p("[config] PROGON_SERVER_URL must not contain embedded credentials (userinfo). Use the PROGON_AGENT_TOKEN env var for authentication instead.");if(e.search!==""||e.hash!=="")throw new p(`[config] PROGON_SERVER_URL must be a base URL with no query string and no fragment \u2014 the agent-gateway routes are appended to it, and a query or a fragment would swallow them instead of preceding them. Got query ${JSON.stringify(e.search)} and fragment ${JSON.stringify(e.hash)}. Use scheme + host + optional path prefix only (https://host, https://host/prefix).`)}o(Re,"validateServerUrl");function dn(t){if(!vt.test(t))throw new p("[config] Agent token must match the pgat_ wire format (CONTRACT-la \xA75.1). Got a token that does not match this format. Ensure PROGON_AGENT_TOKEN was copied from the server correctly.")}o(dn,"validateRunnerToken");function Jo(t){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))throw new p(`[config] agentId must be a valid UUID (issued by the server at enroll). Got: ${JSON.stringify(t)}. The state file may be corrupted \u2014 remove it and re-enroll.`)}o(Jo,"validateRunnerMachineId");function Ko(t){if(t!==1)throw new p(`[config] Protocol version mismatch: state file records version ${t} but this daemon requires version ${1}. Remove the state file and re-enroll with the correct daemon version.`)}o(Ko,"validateProtocolVersion");import{Agent as Bp,EnvHttpProxyAgent as jp}from"undici";var Us=w("gateway-proxy"),Wp=["http_proxy","HTTP_PROXY"],Hp=["https_proxy","HTTPS_PROXY"],Jp=["no_proxy","NO_PROXY"];function Kp(t){return t.http!==void 0||t.https!==void 0}o(Kp,"gatewayIsProxied");var Vp=/^[A-Za-z][A-Za-z0-9+.-]*:\/\//,qp=/:\d+$/,Yp=/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)?[^/?#]*@/;function Xp(t){let e=Yp.exec(t);if(e===null)return t;let n=e[1];return`${n===void 0?"":n}***@${t.slice(e[0].length)}`}o(Xp,"withoutProxyCredentials");function Rt(t,e,n){return new p(`[config] ${t} does not name a proxy this agent can use: ${n}. Got: ${JSON.stringify(Xp(e))}. Accepted: an absolute "http://host:port" (or "https://host:port"), or the scheme-less curl form "host:port", which is read as "http://host:port". The agent-gateway transport speaks HTTP proxying only \u2014 a SOCKS proxy cannot carry it. Unset ${t} to connect to the server directly.`)}o(Rt,"refuseProxyValue");function Ms(t,e){for(let n of e){let r=t[n];if(r!==void 0)return r===""?void 0:{variable:n,raw:r}}}o(Ms,"readProxyVariable");function zp(t){for(let e of Jp){let n=t[e];if(n!==void 0)return n}}o(zp,"readNoProxy");function Gs(t,e){if(Vp.test(e)){let l;try{l=new URL(e)}catch{throw Rt(t,e,"it carries a scheme but is not a URL that parses")}if(l.protocol!=="http:"&&l.protocol!=="https:")throw Rt(t,e,`its scheme is ${JSON.stringify(l.protocol)}, not http: or https:`);if(l.hostname==="")throw Rt(t,e,"it names no host");return{variable:t,url:e,schemeCompleted:!1}}let n=e.search(/[/?#]/),r=n===-1?e:e.slice(0,n);if(!qp.test(r))throw Rt(t,e,'it carries no scheme, so it is read as the curl "host:port" form, and it names no port');let i=`http://${e}`,s;try{s=new URL(i)}catch{throw Rt(t,e,'it is neither a URL nor a "host:port" pair')}if(s.hostname==="")throw Rt(t,e,"it names no host");return{variable:t,url:i,schemeCompleted:!0}}o(Gs,"parseProxyValue");function un(t){let e=Ms(t,Wp),n=Ms(t,Hp);return{http:e===void 0?void 0:Gs(e.variable,e.raw),https:n===void 0?void 0:Gs(n.variable,n.raw),noProxy:zp(t)}}o(un,"resolveGatewayProxyConfig");function Fs(t,e,n){if(!Kp(t))return new Bp(e);Us.info("Gateway traffic follows the proxy configured in this environment",{httpProxy:t.http!==void 0,httpsProxy:t.https!==void 0,noProxy:t.noProxy!==void 0});let r=[];for(let s of[t.http,t.https])s!==void 0&&s.schemeCompleted&&r.push(s.variable);r.length>0&&Us.info('A proxy variable carries no scheme and is read as an HTTP proxy (curl convention: "host:port" means "http://host:port")',{variables:r});let i={...e,...n===void 0?{}:{requestTls:{ca:n},proxyTls:{ca:n}},httpProxy:t.http?.url,httpsProxy:t.https?.url,noProxy:t.noProxy};return new jp(i)}o(Fs,"createProxyAwareDispatcher");function Qn(t){un(t)}o(Qn,"validateGatewayProxyEnv");import{X509Certificate as Qp}from"node:crypto";import{readFileSync as Zp,statSync as em}from"node:fs";import{isAbsolute as tm}from"node:path";import{rootCertificates as Bs}from"node:tls";var nm=w("gateway-tls-trust"),Zn="PROGON_AGENT_EXTRA_CA_CERTS",js="NODE_EXTRA_CA_CERTS";function rm(t,e,n){let r=`[config] ${Zn} does not name a certificate bundle this agent can use: ${e}. Got: ${JSON.stringify(t)}. Accepted: an ABSOLUTE path to a readable PEM file holding the corporate root certificate (one or more "-----BEGIN CERTIFICATE-----" blocks). It extends the trust of the agent's OWN connections to the Progon backend; it does not reach the browser, which trusts what the operating system trusts. Unset ${Zn} to trust only the public roots.`;return n===void 0?new p(r):new p(r,{cause:n})}o(rm,"refuseExtraCaValue");function er(t){let e=t[Zn];if(e===void 0||e==="")return;let n=Ws(e);if("because"in n)throw rm(e,n.because,n.cause);return{variable:Zn,path:e,pem:n.pem}}o(er,"resolveExtraCaTrust");function Ws(t){if(!tm(t))return{because:"it is not an absolute path, and a relative one would be resolved against the working directory the daemon happens to have been started in",cause:void 0};let e;try{e=em(t)}catch(r){return{because:"it cannot be read",cause:r}}if(!e.isFile())return{because:"it is not a file",cause:void 0};let n;try{n=Zp(t,"utf8")}catch(r){return{because:"its contents could not be read",cause:r}}try{new Qp(n)}catch(r){return{because:"it does not hold a PEM certificate",cause:r}}return{pem:n}}o(Ws,"readCaBundle");function Hs(t){let e=t[js];if(e===void 0||e==="")return;let n=Ws(e);if(!("because"in n))return e;let r=n.cause instanceof Error?` (${n.cause.message})`:"";throw new p(`${js} does not name a certificate bundle every start of the agent can use: ${n.because}${r}. Got: ${JSON.stringify(e)}. Where Node cannot use the file it ignores it and trusts only the public roots, so behind a TLS-intercepting gateway the Chromium download and the agent's connections fail. Point it at an ABSOLUTE path to a readable PEM file with the corporate root certificate, or unset it.`,n.cause===void 0?void 0:{cause:n.cause})}o(Hs,"inspectNodeExtraCaCerts");function Js(t){let e=er(t);if(e!==void 0)return nm.info("Trusting an extra certificate authority for the agent's own connections",{variable:e.variable,path:e.path,publicRootCount:Bs.length}),[...Bs,e.pem]}o(Js,"readTrustedCaBundle");function tr(t){er(t)}o(tr,"validateExtraCaTrustEnv");import{readFileSync as lm}from"node:fs";import{dirname as cm,join as dm}from"node:path";import{fileURLToPath as um}from"node:url";function P(t){if(typeof t!="object"||t===null)return!1;let e=t.code;return e==="ENOENT"||e==="ENOTDIR"}o(P,"isAbsentPathError");import{statSync as om}from"node:fs";import{dirname as im,join as sm}from"node:path";var Ks="package.json";function Se(t){let e=t;for(;;){if(am(e))return e;let n=im(e);if(n===e)throw new Error(`[package-root] No ${Ks} was found in ${t} or in any of its parent directories, so the root of the package this file belongs to cannot be determined. This is a packaging defect, not a configuration one: the module asking is supposed to be running from inside an installed or checked-out package.`);e=n}}o(Se,"findPackageRoot");function am(t){try{return om(sm(t,Ks)),!0}catch(e){if(P(e))return!1;throw e}}o(am,"holdsPackageManifest");var pm="extension-bundle.json";function Tt(){return mm(dm(Se(cm(um(import.meta.url))),pm))}o(Tt,"readBundledAppUrl");function mm(t){let e;try{e=lm(t,"utf-8")}catch(i){if(P(i))return null;throw new p(`[extension-bundle] ${t} exists but could not be read: ${String(i)}. It records the deployment this package was built for, so the agent cannot tell which Progon it belongs to until the file is readable. Check the permissions on the installed package, or reinstall it: npm i -g progon-agent@latest.`,{cause:i})}let n;try{n=JSON.parse(e)}catch(i){throw new p(`[extension-bundle] ${t} contains invalid JSON: ${String(i)}. This package's record of the deployment it was built for is damaged \u2014 reinstall it: npm i -g progon-agent@latest.`,{cause:i})}if(typeof n!="object"||n===null||Array.isArray(n)){let i=n===null?"null":Array.isArray(n)?"array":typeof n;throw new p(`[extension-bundle] ${t} must contain a JSON object, got: ${i}. Reinstall the package: npm i -g progon-agent@latest.`)}let r=n.appUrl;if(typeof r!="string"||r==="")throw new p(`[extension-bundle] ${t} has no usable 'appUrl' (expected a non-empty string). That field is the deployment this package was built for; without it the agent cannot tell which Progon it belongs to. Reinstall the package (npm i -g progon-agent@latest), or name the deployment explicitly with --server / PROGON_SERVER_URL.`);try{Re(r)}catch(i){throw new p(`[extension-bundle] ${t} has an invalid 'appUrl': ${String(i)}`,{cause:i})}return r}o(mm,"readBundledAppUrlFrom");import{unlinkSync as Pm}from"node:fs";import{readFileSync as bm,writeFileSync as _m,renameSync as km,existsSync as Rm,fchmodSync as Tm,openSync as qs,fsyncSync as Ys,closeSync as Xs,unlinkSync as xm}from"node:fs";import{join as zs}from"node:path";import{spawnSync as fm}from"node:child_process";import{chmodSync as hm,mkdirSync as gm}from"node:fs";import{resolve as ym}from"node:path";import{z as $e}from"zod";var tt="powershell.exe";function me(t){return`'${t.replace(/['‘’‚‛]/g,e=>e+e)}'`}o(me,"psQuote");function pn(t){return Buffer.from(t,"utf16le").toString("base64")}o(pn,"encodePowerShellCommand");var wm=3e4,Vs=new Set;function xt(t){let e=ym(t);if(gm(e,{recursive:!0,mode:448}),process.platform!=="win32"){hm(e,448);return}Vs.has(e)||(vm(e),Vs.add(e))}o(xt,"makeStateDirPrivate");function Sm(t){return`$ErrorActionPreference = 'Stop'
|
|
17
17
|
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
|
18
18
|
$path = ${me(t)}
|
|
19
19
|
$sidType = [System.Security.Principal.SecurityIdentifier]
|
|
@@ -34,8 +34,8 @@ foreach ($sid in $trusted) {
|
|
|
34
34
|
}
|
|
35
35
|
$dir.SetAccessControl($acl)
|
|
36
36
|
$foreign = @(Get-ChildItem -LiteralPath $path -Force | ForEach-Object { $o = ForeignOwner $_; if ($null -ne $o) { $_.Name + ' (' + $o + ')' } })
|
|
37
|
-
[pscustomobject]@{ kind = 'private'; foreign = $foreign } | ConvertTo-Json -Compress`}o(
|
|
38
|
-
`).slice(0,3).join(" / ")}). The agent does not write its token into a directory other users may read. Fix the cause above, or pick another --state-dir.`)}let n=
|
|
37
|
+
[pscustomobject]@{ kind = 'private'; foreign = $foreign } | ConvertTo-Json -Compress`}o(Sm,"renderAccessListScript");var Em=$e.discriminatedUnion("kind",[$e.object({kind:$e.literal("foreign-owner"),owner:$e.string()}),$e.object({kind:$e.literal("private"),foreign:$e.array($e.string())})]);function vm(t){let e=fm(tt,["-NoProfile","-NonInteractive","-EncodedCommand",pn(Sm(t))],{encoding:"utf8",timeout:wm,windowsHide:!0});if(e.error!==void 0||e.status!==0){let i=e.error?.message??(e.stderr.trim()||e.stdout.trim()||`exit ${e.status}`);throw new p(`Could not make the state directory ${t} private to this user (${tt}: ${i.split(`
|
|
38
|
+
`).slice(0,3).join(" / ")}). The agent does not write its token into a directory other users may read. Fix the cause above, or pick another --state-dir.`)}let n=Em.safeParse(JSON.parse(e.stdout.replace(/^\uFEFF/,"")));if(!n.success)throw new Error(`[private-state-dir] PowerShell answered in a form this version does not read: ${n.error.message}`);let r=n.data;if(r.kind==="foreign-owner")throw new p(`The state directory ${t} belongs to ${r.owner}, who can give themselves access to its token at any time. Use a directory of your own: pick another --state-dir.`);if(r.foreign.length>0)throw new p(`The state directory ${t} is now private to this user, but these entries in it belong to another user, who can still read or change them: ${r.foreign.join(", ")}. Delete them (or the whole directory) and start again.`)}o(vm,"setOwnerOnlyAccessList");var nr=w("state-file");function nt(t){return zs(t,"runner-state.json")}o(nt,"stateFilePath");function mn(t){return zs(t,"runner-state.json.tmp")}o(mn,"stateTmpPath");function Qs(t){let e=nt(t);if(!Rm(e))return nr.debug("No state file found \u2014 first start",{filePath:e}),null;let n;try{n=bm(e,"utf-8")}catch(s){throw new p(`[state-file] Failed to read state file at ${e}: ${String(s)}. Check that this user owns the file and its directory. If it is beyond repair, remove it and enroll the machine again with 'progon-agent enroll' (a source checkout, which carries no bundled deployment, also needs --server <url>).`)}let r;try{r=JSON.parse(n)}catch(s){throw new p(`[state-file] State file at ${e} contains invalid JSON: ${String(s)}. Remove the file and enroll the machine again with 'progon-agent enroll' (a source checkout, which carries no bundled deployment, also needs --server <url>).`)}let i=Am(r,e);return nr.info("State file loaded",{agentId:i.agentId,protocolVersion:i.protocolVersion}),i}o(Qs,"readState");function Zs(t,e){xt(t);let n=nt(t),r=mn(t),i=JSON.stringify(e,null,2);try{let s=qs(r,"w",384);try{Tm(s,384),_m(s,i,{encoding:"utf-8"}),Ys(s)}finally{Xs(s)}km(r,n),Om(t)}catch(s){throw Im(r),new p(`[state-file] Failed to write state file at ${n}: ${String(s)}. Check permissions on stateDir ${t}.`)}nr.info("State file written",{agentId:e.agentId,filePath:n})}o(Zs,"writeState");function Im(t){try{xm(t)}catch(e){if(e.code==="ENOENT")return;nr.error("Failed to remove the temporary state file \u2014 it may still hold the agent credential",{tmpPath:t,err:e instanceof Error?e.message:String(e)})}}o(Im,"removeStateTmp");function Om(t){let e=qs(t,"r");try{Ys(e)}finally{Xs(e)}}o(Om,"fsyncDirectory");function Am(t,e){if(typeof t!="object"||t===null||Array.isArray(t)){let c=t===null?"null":Array.isArray(t)?"array":typeof t;throw new p(`[state-file] State file ${e} must contain a JSON object, got: ${c}`)}let n=t,r=n.agentId;if(typeof r!="string"||r==="")throw new p(`[state-file] State file ${e} is missing or has invalid 'agentId' (expected non-empty string).`);Jo(r);let i=n.agentToken;if(typeof i!="string"||i==="")throw new p(`[state-file] State file ${e} is missing or has invalid 'agentToken' (expected non-empty string).`);dn(i);let s=n.protocolVersion;if(typeof s!="number"||!Number.isInteger(s))throw new p(`[state-file] State file ${e} is missing or has invalid 'protocolVersion' (expected integer).`);Ko(s);let l=n.serverUrl;if(typeof l!="string"||l==="")throw new p(`[state-file] State file ${e} is missing or has invalid 'serverUrl' (expected non-empty string).`);try{Re(l)}catch(c){throw new p(`[state-file] State file ${e} has an invalid 'serverUrl': ${String(c)}`)}return{agentId:r,agentToken:i,protocolVersion:s,serverUrl:l,tokenRotatedAt:Cm(n,e)}}o(Am,"validateState");function Cm(t,e){let n=t.tokenRotatedAt;if(n==null)return null;if(typeof n!="string"||n==="")throw new p(`[state-file] State file ${e} has an invalid 'tokenRotatedAt' (expected a non-empty ISO string, null, or the key to be absent on a file written before agent token rotation shipped).`);return n}o(Cm,"readTokenRotatedAt");var ea=w("token-store");function L(t){return Qs(t)}o(L,"loadAgentIdentity");function It(t,e){Zs(t,e)}o(It,"saveAgentIdentity");function rr(t){let e=nt(t),n=mn(t),r=ta(n,"temporary state file"),i=ta(e,"identity");if(!i&&!r){ea.info("Agent identity wipe: no state file to remove",{filePath:e,tmpPath:n});return}ea.warn("Agent identity wiped \u2014 this agent was revoked and must be re-enrolled",{filePath:e,tmpPath:n,removedState:i,removedTmp:r})}o(rr,"wipeAgentIdentity");function ta(t,e){try{return Pm(t),!0}catch(n){if(Nm(n))return!1;throw new Error(`[token-store] Failed to wipe the agent ${e} at ${t}: ${String(n)}. The agent has been revoked (CONTRACT-la \xA715 A15.1) and its credential must not remain on disk \u2014 remove the file manually.`)}}o(ta,"removeCredentialFile");function Nm(t){return t.code==="ENOENT"}o(Nm,"isFileNotFound");var na="extension-bundle.json";function Ue(t,e){return ra(t)===ra(e)}o(Ue,"isSameDeployment");function ra(t){let e=new URL(t);return`${e.origin}${e.pathname.replace(/\/+$/,"")}`}o(ra,"normalizeDeployment");function oa(t){let{envUrl:e,envTokenPresent:n,stateDir:r}=t;if(e!==void 0)return Re(e),{url:e,source:"env"};if(n){let l=Tt();if(l!==null)return{url:l,source:"bundle"};throw new p(`[config] PROGON_SERVER_URL is not set, and PROGON_AGENT_TOKEN names no deployment \u2014 a pgat_ token is only meaningful at the backend that minted it, and this daemon will not guess which one that is.
|
|
39
39
|
This build carries no ${na} either, so it was not built for a particular deployment \u2014 that is what a source checkout is, and an installed progon-agent from npm always has one.
|
|
40
40
|
The state file in ${r} is deliberately NOT consulted on this path: PROGON_AGENT_TOKEN is the rotation and recovery mechanism, and it must not start depending on the very file an operator sets it to recover from.
|
|
41
41
|
Set PROGON_SERVER_URL to the deployment this token belongs to; or unset PROGON_AGENT_TOKEN, after which an enrolled machine takes both its credential and its server from that state file.
|
|
@@ -44,8 +44,8 @@ $foreign = @(Get-ChildItem -LiteralPath $path -Force | ForEach-Object { $o = For
|
|
|
44
44
|
Enroll this machine \u2014 'progon-agent enroll --server <url>' (approved in a browser), or 'progon-agent enroll <code> --server <url>' with a code from Progon (Settings \u2192 Agents). Enrollment persists the server together with the credential, so every later command finds it with no environment at all.
|
|
45
45
|
If this machine WAS enrolled with PROGON_RUNNER_STATE_DIR set, set the same variable again \u2014 that directory is where its credential and its server are.
|
|
46
46
|
Setting PROGON_SERVER_URL on its own names a server but no agent: it is what an 'enroll' needs, and it is enough for 'start' only alongside PROGON_AGENT_TOKEN.
|
|
47
|
-
See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`)}o(oa,"resolveServerUrl");function
|
|
48
|
-
`)}o(gn,"writeLine");function la(t){let e=t instanceof Error?t.message:String(t),n=t instanceof Error?t.stack:void 0;return{err:C(e),stack:n!==void 0?C(n):void 0}}o(la,"describeError");function aa(t,e,n){gn("fatal",`Unhandled ${t} \u2014 terminating the daemon`,{event:t,...la(e),...n})}o(aa,"writeFatalLine");function ca(){process.on("uncaughtException",(t,e)=>{aa("uncaughtException",t,{origin:e}),process.exit(1)}),process.on("unhandledRejection",t=>{aa("unhandledRejection",t,{}),process.exit(1)})}o(ca,"installProcessGuards");var ir=["SIGTERM","SIGINT","SIGHUP"];function da(t){let e=!1,n=o(r=>{if(e){gn("info","Shutdown already in progress \u2014 signal ignored",{signal:r});return}e=!0,gn("info","Signal received \u2014 shutting down",{signal:r}),(async()=>{try{await t(r)}catch(i){gn("fatal","Shutdown hook failed \u2014 the daemon may leave resources behind",{signal:r,...la(i)}),process.exit(1)}gn("info","Shutdown complete",{signal:r}),process.exit(0)})()},"handle");for(let r of ir)process.on(r,n);return n}o(da,"installShutdownHandlers");var Um=w("debug-env-guard"),Mm=["pw:protocol","pw:api"];function Gm(t){return t.replace(/[\\^$.|?+()[\]{}]/g,"\\$&")}o(Gm,"escapeRegExp");function ua(t){if(t.startsWith("-"))return!1;let e=`^${t.split("*").map(Gm).join(".*?")}$`,n=new RegExp(e);return Mm.some(r=>n.test(r))}o(ua,"enablesPlaywright");function Fm(){let t=process.env.DEBUG;if(t===void 0||t==="")return[];let e=t.split(/[\s,]+/).map(i=>i.trim()).filter(i=>i!==""),n=e.filter(i=>ua(i));if(n.length===0)return[];let r=e.filter(i=>!ua(i));return r.length===0?delete process.env.DEBUG:process.env.DEBUG=r.join(","),Um.warn("Playwright debug namespaces removed from DEBUG before playwright-core loaded",{removed:n,kept:r,debugFile:process.env.DEBUG_FILE??null,reason:"pw: namespaces write raw CDP messages \u2014 including the per-run session tokens written into the token database \u2014 to a sink that bypasses log redaction (CONTRACT-la \xA79, \xA711.10)"}),n}o(Fm,"sanitizePlaywrightDebugEnv");Fm();import{statSync as fa}from"node:fs";import{isAbsolute as Jm,join as Vm}from"node:path";import{createRequire as Bm}from"node:module";var Re=Bm(import.meta.url)("playwright-core"),rt=Re.chromium,H_=Re.firefox,K_=Re.webkit,J_=Re.selectors,V_=Re.devices,pa=Re.errors,q_=Re.request,Y_=Re._electron,X_=Re._android;import{writeFileSync as jm}from"node:fs";import{join as Wm}from"node:path";var Hm="Local State",Km={async_dns:{enabled:!1},dns_over_https:{mode:"off"}};function ma(t){jm(Wm(t,Hm),JSON.stringify(Km),{flag:"wx"})}o(ma,"writeOsResolverLocalState");var yn="chromium";var sr="instances",ar="instance.json";var qm=["--disable-backgrounding-occluded-windows","--disable-renderer-backgrounding"],ha={handleSIGINT:!1,handleSIGTERM:!1,handleSIGHUP:!1};async function ga(t){return ma(t.userDataDir),rt.launchPersistentContext(t.userDataDir,{headless:!t.headful,channel:yn,...ha,viewport:null,ignoreHTTPSErrors:t.allowInsecureHttps,chromiumSandbox:!t.disableBrowserSandbox,args:[`--disable-extensions-except=${t.extensionDist}`,`--load-extension=${t.extensionDist}`,"--no-first-run","--no-default-browser-check","--silent-debugger-extension-api",...t.headful?[]:["--screen-info={1280x1024}"],...t.keepBackgroundWindowsRendering?qm:[]]})}o(ga,"launchExtensionContext");async function ya(t){return rt.launchPersistentContext(t,{headless:!0,channel:yn,...ha,chromiumSandbox:!0})}o(ya,"launchSandboxedProbeContext");async function wa(t,e){let n=await t.newCDPSession(e);try{let{windowId:r}=await n.send("Browser.getWindowForTarget");await n.send("Browser.setContentsSize",{windowId:r,width:1280,height:720})}finally{await n.detach()}}o(wa,"setRunnerContentViewport");function Ym(t){let e=t.browser();if(e===null)throw new Error("context.browser() returned null for a persistent context \u2014 the browser handle is unusable, so neither its PID nor its version can be read");return e}o(Ym,"requireBrowser");function Sa(t){return Ym(t).version()}o(Sa,"readChromeVersion");async function lr(t,e){let n,r=new Promise(i=>{n=setTimeout(()=>i({settled:"timeout"}),e)});try{return await Promise.race([t.close().then(()=>({settled:"closed"}),i=>({settled:"rejected",error:i})),r])}finally{n!==void 0&&clearTimeout(n)}}o(lr,"raceClose");function cr(t){if(!Jm(t))throw new p(`[runtime] The extension dist path must be absolute, got ${JSON.stringify(t)}. A relative path would be resolved against the daemon's working directory.`);let e;try{e=fa(t)}catch(r){throw new p(`[runtime] The extension dist directory ${t} cannot be read. Chromium does NOT fail on a bad --load-extension: it would start without the extension and every run would time out in the readiness probe. Check PROGON_AGENT_EXTENSION_DIST.`,{cause:r})}if(!e.isDirectory())throw new p(`[runtime] The extension dist path ${t} is not a directory.`);let n=Vm(t,"manifest.json");try{fa(n)}catch(r){throw new p(`[runtime] ${n} is missing, so ${t} is not a built extension. Build qa-extension, or point PROGON_AGENT_EXTENSION_DIST at a real dist.`,{cause:r})}}o(cr,"assertUsableExtensionDist");import{fetch as rf}from"undici";import{z as Ga}from"zod";var A=class extends Error{static{o(this,"GatewayError")}operation;constructor(e,n,r){super(n,{cause:r}),this.name=new.target.name,this.operation=e}},Z=class extends A{static{o(this,"GatewayTransportError")}constructor(e,n,r){super(e,`[gateway] ${e} failed before a response was received: ${n}`,r)}},x=class extends A{static{o(this,"GatewayHttpError")}status;errorCode;params;retryAfterMs;constructor(e,n,r,i,s,l=null){super(e,`[gateway] ${e} refused with HTTP ${n}: ${s}`),this.status=n,this.errorCode=r,this.params=i,this.retryAfterMs=l}},Ot=class extends x{static{o(this,"GatewayUnauthorizedError")}},O=class extends x{static{o(this,"TokenSupersededError")}},T=class extends A{static{o(this,"TerminalSignalError")}signal;constructor(e,n,r){super(e,`[gateway] agent revoked (${n}) during ${e}: ${r}`),this.signal=n}},At=class extends x{static{o(this,"EnrollmentCodeRejectedError")}},ot=class extends x{static{o(this,"ProtocolVersionMismatchError")}},ee=class extends x{static{o(this,"AgentUpgradeRequiredError")}constructor(e,n,r,i,s){super(e,n,r,i,`${s}. Update the agent with 'progon-agent update' and start it again.`)}},Ct=class extends x{static{o(this,"RunNotClaimableError")}},it=class extends x{static{o(this,"RunNotFoundError")}},fe=class extends A{static{o(this,"GatewayResponseSchemaError")}constructor(e,n,r){super(e,`[gateway] ${e} returned a body that violates the contract: ${n}`,r)}};import{readFileSync as Xm}from"node:fs";import{dirname as zm,join as Qm}from"node:path";import{fileURLToPath as Zm}from"node:url";var ef=/^\d+\.\d+\.\d+$/,Ea=30,qo=null;function te(){if(qo!==null)return qo;let t=we(zm(Zm(import.meta.url))),e=JSON.parse(Xm(Qm(t,"package.json"),"utf8")),n=typeof e=="object"&&e!==null?e.version:void 0;if(typeof n!="string"||!ef.test(n))throw new Error(`[agent-version] The agent package.json in ${t} has no usable "version" field (got ${JSON.stringify(n)}, expected x.y.z), so the agent cannot state its version to the server. This is a packaging defect: the daemon must not run under an invented version.`);if(n.length>Ea)throw new Error(`[agent-version] The agent package version ${JSON.stringify(n)} is longer than the ${Ea} characters CONTRACT-la \xA75.1 allows for agentVersion.`);return qo=n,n}o(te,"readAgentVersion");function va(){return`agent/${te()}`}o(va,"agentClientHeaderValue");var Pt=class extends x{static{o(this,"EnrollmentSlowDownError")}retryAfterSec;constructor(e,n,r,i,s,l){super(e,n,r,i,s),this.retryAfterSec=l}},Nt=class extends x{static{o(this,"EnrollmentAccessDeniedError")}},Lt=class extends x{static{o(this,"EnrollmentRequestExpiredError")}},Dt=class extends x{static{o(this,"EnrollmentAlreadyCompletedError")}},$t=class extends x{static{o(this,"EnrollmentRequestInvalidError")}};function ba(t,e){return e.status===426&&e.errorCode==="client.upgrade_required"?J(ee,t,e):null}o(ba,"mapClientVersionRefusal");function _a(t){return t.status===401&&t.errorCode==="agent_enroll.invalid_code"?J(At,"enroll",t):t.status===409&&t.errorCode==="agent_enroll.protocol_version"?J(ot,"enroll",t):ne("enroll",t)}o(_a,"mapEnrollError");function ka(t){return t.status===409&&t.errorCode==="agent_enroll.protocol_version"?J(ot,"enrollment_request_create",t):ne("enrollment_request_create",t)}o(ka,"mapEnrollmentRequestCreateError");function Ra(t){if(t.status===429&&t.errorCode==="agent_enroll.slow_down"){let e=t.params===null?void 0:t.params.retryAfterSeconds,n=typeof e=="number"&&Number.isFinite(e)&&e>0?e:null;return new Pt("enrollment_request_poll",t.status,t.errorCode,t.params,t.message,n)}return t.status===403&&t.errorCode==="agent_enroll.access_denied"?J(Nt,"enrollment_request_poll",t):t.status===410&&t.errorCode==="agent_enroll.expired"?J(Lt,"enrollment_request_poll",t):t.status===410&&t.errorCode==="agent_enroll.already_completed"?J(Dt,"enrollment_request_poll",t):t.status===401&&t.errorCode==="agent_enroll.invalid_request"?J($t,"enrollment_request_poll",t):ne("enrollment_request_poll",t)}o(Ra,"mapEnrollmentRequestPollError");function Ta(t){return ne("enrollment_request_cancel",t)}o(Ta,"mapEnrollmentRequestCancelError");function xa(t){return Te("poll_desired_state",t,()=>ne("poll_desired_state",t))}o(xa,"mapPollDesiredStateError");function Ia(t){return Te("claim",t,()=>t.status===409&&t.errorCode==="run.not_claimable"?J(Ct,"claim",t):t.status===404?J(it,"claim",t):ne("claim",t))}o(Ia,"mapClaimError");function Oa(t){return Te("fail",t,()=>t.status===404?J(it,"fail",t):ne("fail",t))}o(Oa,"mapFailError");function Aa(t){return Te("token_status",t,()=>ne("token_status",t))}o(Aa,"mapTokenStatusError");function Ca(t){return Te("token_rotate",t,()=>ne("token_rotate",t))}o(Ca,"mapTokenRotateError");function Pa(t){return Te("declare_capabilities",t,()=>ne("declare_capabilities",t))}o(Pa,"mapDeclareCapabilitiesError");function Na(t){return Te("identity_session",t,()=>ne("identity_session",t))}o(Na,"mapIdentitySessionError");function La(t){return Te("revoke",t,()=>ne("revoke",t))}o(La,"mapRevokeError");function Da(t){return Te("launch_session",t,()=>ne("launch_session",t))}o(Da,"mapLaunchSessionError");function Te(t,e,n){return e.status===403&&e.errorCode==="agents.revoked"?new T(t,"http_403_agents_revoked",e.message):e.status===401&&e.errorCode==="agents.token_superseded"?J(O,t,e):e.status===401?J(Ot,t,e):n()}o(Te,"bearerRoute");function J(t,e,n){return new t(e,n.status,n.errorCode,n.params,n.message,n.retryAfterMs)}o(J,"named");function ne(t,e){return J(x,t,e)}o(ne,"generic");var $a=w("gateway-http");async function st(t){let e={accept:"application/json","x-progon-client":va()};t.agentToken!==null&&(e.authorization=`Bearer ${t.agentToken}`),t.body!==null&&(e["content-type"]="application/json"),$a.debug("Gateway request",{operation:t.operation,method:t.method,url:t.url.toString()});let n;try{n=await t.fetchImpl(t.url,{method:t.method,headers:e,body:t.body===null?void 0:JSON.stringify(t.body),signal:t.signal})}catch(i){throw new Z(t.operation,dr(i),i)}let r;try{r=await n.text()}catch(i){throw new Z(t.operation,dr(i),i)}if(!n.ok){let i=Xo(n,r);throw $a.debug("Gateway request refused",{operation:t.operation,status:i.status,errorCode:i.errorCode}),ba(t.operation,i)??t.mapHttpError(i)}try{return JSON.parse(r)}catch(i){throw new fe(t.operation,`the ${n.status} response body is not valid JSON`,i)}}o(st,"executeGatewayRequest");function V(t,e){if(e.success)return e.data;throw new fe(t,zo(e.error),e.error)}o(V,"parseGatewayBody");function ur(t,e){return new URL(`${t.replace(/\/+$/,"")}${e}`)}o(ur,"buildServerRouteUrl");function Xo(t,e){let{status:n}=t,r=tf(t.headers.get("retry-after")),i;try{i=JSON.parse(e)}catch{return{status:n,errorCode:null,params:null,message:Yo,retryAfterMs:r}}if(typeof i!="object"||i===null||Array.isArray(i))return{status:n,errorCode:null,params:null,message:Yo,retryAfterMs:r};let s=i,l=s.error_code,c=s.params,a=s.message;return{status:n,errorCode:typeof l=="string"?l:null,params:typeof c=="object"&&c!==null&&!Array.isArray(c)?c:null,message:typeof a=="string"?C(a):Yo,retryAfterMs:r}}o(Xo,"readErrorEnvelope");function tf(t){return t===null||!/^\d+$/.test(t)?null:Number(t)*1e3}o(tf,"parseRetryAfterMs");var Yo="the response body carried no Progon error envelope";function dr(t){if(!(t instanceof Error))return C(String(t));let e=nf(t.cause);return C(e===""?t.message:`${t.message}: ${e}`)}o(dr,"describeTransportCause");function nf(t){return t instanceof Error?t.message!==""||!(t instanceof AggregateError)?t.message:t.errors.map(e=>e instanceof Error?e.message:"").filter(e=>e!=="").join("; "):""}o(nf,"causeText");function zo(t){let e=t.issues;if(!Array.isArray(e)||e.length===0)return"the response body failed schema validation (the validator reported no issue list)";let n=e.map(r=>{let i=r.path;return!Array.isArray(i)||i.length===0?"<root>":i.map(s=>String(s)).join(".")});return`${e.length} schema violation(s) at: ${n.join(", ")}`}o(zo,"summarizeSchemaViolation");var pr=[...ns,rs,os,ss,is,as,ls];import{z as at}from"zod";var Ua=at.object({rotationDue:at.boolean(),tokenRotatedAt:at.string().nullable(),anchorAt:at.string(),intervalDays:at.number().int()}),Ma=at.object({agentToken:at.string().regex(vt)});var wn=w("gateway-client"),of=Ga.object({success:Ga.literal(!0)}),sf="/api/agent-gateway";function q(t,e){return ur(t,`${sf}${e}`)}o(q,"buildGatewayUrl");var Fa=3e5,ja=1e4,Ba={headersTimeout:Fa,bodyTimeout:Fa,connect:{timeout:ja}};function af(){let t=Ks(process.env);return Fs(dn(process.env),t===void 0?Ba:{...Ba,connect:{timeout:ja,ca:t}},t)}o(af,"buildGatewayDispatcher");var Qo,Mt=o((t,e)=>{if(Qo===void 0){let n=af();Qo=o((r,i)=>rf(r,{...i,dispatcher:n}),"defaultGatewayFetch")}return Qo(t,e)},"pinnedGatewayFetch"),Ut=class{static{o(this,"GatewayEnrollmentClient")}serverUrl;machine;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.machine=e.machine,this.fetchImpl=e.fetchImpl??Mt}async enroll(e,n){let r={...this.machine,enrollmentCode:e,protocolVersion:1},i=await st({operation:"enroll",method:"POST",url:q(this.serverUrl,"/enroll"),agentToken:null,body:r,signal:n?.signal,fetchImpl:this.fetchImpl,mapHttpError:_a}),s=V("enroll",Vn.safeParse(i));return wn.info("Agent enrolled",{agentId:s.agentId,pollWaitSec:s.pollWaitSec,protocolVersion:s.protocolVersion}),s}},Ge=class{static{o(this,"GatewayClient")}serverUrl;agentToken;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.agentToken=e.agentToken,this.fetchImpl=e.fetchImpl??Mt}async authenticatedRequest(e){return st({operation:e.operation,method:e.method,url:e.url,agentToken:this.agentToken,body:e.body,signal:e.signal,fetchImpl:this.fetchImpl,mapHttpError:e.mapHttpError})}async pollDesiredState(e){let n=q(this.serverUrl,"/state");e?.waitSec!==void 0&&n.searchParams.set("waitSec",String(e.waitSec));let r=await this.authenticatedRequest({operation:"poll_desired_state",method:"GET",url:n,body:null,signal:e?.signal,mapHttpError:xa}),i=V("poll_desired_state",vs.safeParse(r));if(i.agent.revoked)throw new T("poll_desired_state","desired_state_snapshot","the desired-state snapshot reports this agent as revoked");return i}async claimRun(e){let n=await this.authenticatedRequest({operation:"claim",method:"POST",url:q(this.serverUrl,`/runs/${encodeURIComponent(e)}/claim`),body:{capabilities:pr},signal:void 0,mapHttpError:Ia});return V("claim",Rs.safeParse(n))}async issueIdentitySession(e,n){let r=await this.authenticatedRequest({operation:"identity_session",method:"POST",url:q(this.serverUrl,`/runs/${encodeURIComponent(e)}/identities/${encodeURIComponent(n)}/session`),body:null,signal:void 0,mapHttpError:Na});return V("identity_session",Go.safeParse(r)).extensionSession}async issueLaunchSession(e,n){let r=await this.authenticatedRequest({operation:"launch_session",method:"POST",url:q(this.serverUrl,`/runs/${encodeURIComponent(e)}/launches/${encodeURIComponent(n)}/session`),body:null,signal:void 0,mapHttpError:Da});return V("launch_session",Go.safeParse(r)).extensionSession}async failRun(e,n){let r=await this.authenticatedRequest({operation:"fail",method:"POST",url:q(this.serverUrl,`/runs/${encodeURIComponent(e)}/fail`),body:n,signal:void 0,mapHttpError:Oa}),i=V("fail",ks.safeParse(r));return wn.info("Reported run failure to the gateway",{runId:e,reason:n.reason,status:i.status}),i}async getTokenRotationStatus(e){let n=await this.authenticatedRequest({operation:"token_status",method:"GET",url:q(this.serverUrl,"/token"),body:null,signal:e?.signal,mapHttpError:Aa});return V("token_status",Ua.safeParse(n))}async rotateToken(e){let n=await this.authenticatedRequest({operation:"token_rotate",method:"POST",url:q(this.serverUrl,"/token/rotate"),body:null,signal:e?.signal,mapHttpError:Ca});return V("token_rotate",Ma.safeParse(n))}async declareCapabilities(e){await this.authenticatedRequest({operation:"declare_capabilities",method:"POST",url:q(this.serverUrl,"/capabilities"),body:{capabilities:pr},signal:e?.signal,mapHttpError:Pa}),wn.info("Capabilities declared",{capabilities:pr})}async revokeSelf(){let e=await this.authenticatedRequest({operation:"revoke",method:"POST",url:q(this.serverUrl,"/revoke"),body:null,signal:void 0,mapHttpError:La});V("revoke",of.safeParse(e)),wn.info("Agent registration revoked on the server by this agent")}useAgentToken(e){this.agentToken=e,wn.info("Adopted a rotated agent token for all subsequent gateway requests")}};import{z as R}from"zod";var mr=R.object({id:R.string().min(1),status:R.string(),revision:R.number(),counts:R.object({total:R.number().int(),queued:R.number().int(),running:R.number().int(),finished:R.number().int(),notStarted:R.number().int()}),current:R.string().nullable(),waitingForRunner:R.object({ahead:R.number().int()}).nullable(),verdict:R.string().nullable(),webUrl:R.string().min(1)}),Wa=R.object({runnerId:R.string().min(1),enrollmentCode:R.string().min(1)}),lf=R.object({scenarioId:R.string(),scenarioName:R.string(),status:R.string(),outcome:R.string().nullable(),failureReason:R.string().nullable(),notStartedReason:R.string().nullable(),failedStep:R.object({number:R.string(),name:R.string()}).nullable()}),Ha=R.object({items:R.array(lf),total:R.number().int()}),fr="finished",hr="passed",gr="failed",Ka="no_result",Zo="passed",ei="failed",Ja="finished",yr="not_started";var cf="/api/ci/v1",Fe=class extends Error{static{o(this,"CiApiError")}},he=class extends Fe{constructor(n,r,i,s,l){super(s);this.status=n;this.errorCode=r;this.params=i;this.retryAfterMs=l}static{o(this,"CiRefusalError")}},Gt=class extends Fe{static{o(this,"CiNoAnswerError")}},lt=class extends Fe{static{o(this,"CiBadAnswerError")}},df=100,wr=class{static{o(this,"CiApiClient")}serverUrl;key;requestTimeoutMs;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.key=e.key,this.requestTimeoutMs=e.requestTimeoutMs,this.fetchImpl=e.fetchImpl??Mt}async createRunner(e){let n=await this.call("POST","/runners",null,this.requestTimeoutMs,e);return this.parse(Wa,n)}async createLaunch(e,n){let r=await this.call("POST","/launches",e,this.requestTimeoutMs,n);return this.parse(mr,r)}async getLaunch(e,n){let r=`/launches/${encodeURIComponent(e)}`,i=await this.call("GET",r,null,this.requestTimeoutMs,n);return this.parse(mr,i)}async listItems(e,n,r){let i=`/launches/${encodeURIComponent(e)}/items?offset=${n}&limit=${df}`,s=await this.call("GET",i,null,this.requestTimeoutMs,r);return this.parse(Ha,s)}async stopLaunch(e,n){let r=`/launches/${encodeURIComponent(e)}/stop`,i=await this.call("POST",r,null,n,void 0);return this.parse(mr,i)}async call(e,n,r,i,s){let l=ur(this.serverUrl,`${cf}${n}`),c={accept:"application/json",authorization:`Bearer ${this.key}`};r!==null&&(c["content-type"]="application/json");let a=new AbortController,d=!1,u=setTimeout(()=>{d=!0,a.abort()},i),m=o(()=>a.abort(),"onCallerAbort");s!==void 0&&(s.aborted?a.abort():s.addEventListener("abort",m,{once:!0}));let g,E;try{g=await this.fetchImpl(l,{method:e,headers:c,body:r===null?void 0:JSON.stringify(r),signal:a.signal}),E=await g.text()}catch(S){throw new Gt(d?`no answer within ${Math.round(i/1e3)}s`:dr(S))}finally{clearTimeout(u),s?.removeEventListener("abort",m)}if(!g.ok){let S=Xo(g,E);throw new he(S.status,S.errorCode,S.params,S.message,S.retryAfterMs)}try{return JSON.parse(E)}catch{throw new lt(`the ${g.status} answer of Progon is not valid JSON`)}}parse(e,n){let r=e.safeParse(n);if(r.success)return r.data;throw new lt(`the answer of Progon does not match this CLI: ${zo(r.error)}`)}};var Va=`progon-agent ci run \u2014 run Progon scenarios as a step of a CI pipeline
|
|
47
|
+
See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`)}o(oa,"resolveServerUrl");function fn(t){let e=process.env[t];return e!==void 0&&e!==""?e:void 0}o(fn,"getOptional");function Vo(t,e){let n=process.env[t];if(n===void 0||n==="")return e;let r=n.trim().toLowerCase();if(r==="true"||r==="1")return!0;if(r==="false"||r==="0")return!1;throw new p(`[config] Environment variable ${t} must be one of true/false/1/0, got: ${JSON.stringify(n)}.`)}o(Vo,"getOptionalBool");var ir="progon-agent";function hn(t,e,n){if(n==="")throw new p("[config] Cannot resolve the default state directory: the current user has no home directory (os.homedir() returned an empty string \u2014 happens in service/container contexts without HOME). Set PROGON_RUNNER_STATE_DIR explicitly.");switch(t){case"darwin":return or(n,"Library","Application Support",ir);case"linux":{let r=e.XDG_STATE_HOME;if(r===void 0||r==="")return or(n,".local","state",ir);if(!ia(r))throw new p(`[config] XDG_STATE_HOME must be an absolute path (XDG Base Directory specification), got: ${JSON.stringify(r)}. Fix the variable or set PROGON_RUNNER_STATE_DIR explicitly.`);return or(r,ir)}case"win32":{let r=e.APPDATA;if(r===void 0||r==="")throw new p("[config] %APPDATA% is not set, so the default Windows state directory cannot be resolved. Set PROGON_RUNNER_STATE_DIR explicitly.");return or(r,ir)}default:throw new p(`[config] No default state directory is defined for platform ${JSON.stringify(t)} (supported: darwin, linux, win32 \u2014 CONTRACT-la \xA75.1, \xA710.3). Set PROGON_RUNNER_STATE_DIR explicitly.`)}}o(hn,"resolveDefaultStateDir");function G(){let t=fn("PROGON_RUNNER_STATE_DIR");return t!==void 0?{path:Dm(t),source:"env"}:{path:hn(process.platform,process.env,Lm()),source:"default"}}o(G,"resolveStateDir");var sa=["PROGON_SERVER_URL","PROGON_LOG_LEVEL","PROGON_AGENT_EXTENSION_DIST","PROGON_AGENT_HEADFUL","PROGON_AGENT_ALLOW_INSECURE_HTTPS","PROGON_AGENT_DISABLE_BROWSER_SANDBOX","PROGON_AGENT_EXTRA_CA_CERTS","NODE_EXTRA_CA_CERTS","PLAYWRIGHT_BROWSERS_PATH","PLAYWRIGHT_DOWNLOAD_HOST","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy"];function gn(){let t=fn("PROGON_AGENT_EXTENSION_DIST");if(t!==void 0&&!ia(t))throw new p(`[config] PROGON_AGENT_EXTENSION_DIST must be an absolute path, got: ${JSON.stringify(t)}.`);return{extensionDistOverride:t,headfulOverride:Vo("PROGON_AGENT_HEADFUL",!1),allowInsecureHttps:Vo("PROGON_AGENT_ALLOW_INSECURE_HTTPS",!1),disableBrowserSandbox:Vo("PROGON_AGENT_DISABLE_BROWSER_SANDBOX",!1)}}o(gn,"loadBrowserRuntimeEnv");function Me(){Qn(process.env),tr(process.env);let t=process.env.PROGON_AGENT_TOKEN;if(t==="")throw new p("[config] PROGON_AGENT_TOKEN is set but empty. To use the persisted state-file token, unset this variable entirely. To rotate the token, set it to the new pgat_ token. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.");let e=t;e!==void 0&&dn(e);let n=G().path,r=oa({envUrl:fn("PROGON_SERVER_URL"),envTokenPresent:e!==void 0,stateDir:n}),i=fn("PROGON_AGENT_ENROLL_CODE");if(i!==void 0&&i.length<32)throw new p(`[config] PROGON_AGENT_ENROLL_CODE is shorter than the ${32} characters an enrollment code has (got ${i.length}). Copy the whole code from the agent's enrollment dialog. See docs/working/local-agent-v1/CONTRACT-la.md \xA75.1.`);return{serverUrl:r.url,serverUrlSource:r.source,initialToken:e,stateDir:n,...gn(),enrollmentCode:i,nodeEnv:fn("NODE_ENV")??"production"}}o(Me,"loadConfig");import{randomUUID as Ug}from"node:crypto";function yn(t,e,n){process.stderr.write(JSON.stringify({level:t,module:"process-guards",msg:e,...n})+`
|
|
48
|
+
`)}o(yn,"writeLine");function la(t){let e=t instanceof Error?t.message:String(t),n=t instanceof Error?t.stack:void 0;return{err:C(e),stack:n!==void 0?C(n):void 0}}o(la,"describeError");function aa(t,e,n){yn("fatal",`Unhandled ${t} \u2014 terminating the daemon`,{event:t,...la(e),...n})}o(aa,"writeFatalLine");function ca(){process.on("uncaughtException",(t,e)=>{aa("uncaughtException",t,{origin:e}),process.exit(1)}),process.on("unhandledRejection",t=>{aa("unhandledRejection",t,{}),process.exit(1)})}o(ca,"installProcessGuards");var sr=["SIGTERM","SIGINT","SIGHUP"];function da(t){let e=!1,n=o(r=>{if(e){yn("info","Shutdown already in progress \u2014 signal ignored",{signal:r});return}e=!0,yn("info","Signal received \u2014 shutting down",{signal:r}),(async()=>{try{await t(r)}catch(i){yn("fatal","Shutdown hook failed \u2014 the daemon may leave resources behind",{signal:r,...la(i)}),process.exit(1)}yn("info","Shutdown complete",{signal:r}),process.exit(0)})()},"handle");for(let r of sr)process.on(r,n);return n}o(da,"installShutdownHandlers");var $m=w("debug-env-guard"),Um=["pw:protocol","pw:api"];function Mm(t){return t.replace(/[\\^$.|?+()[\]{}]/g,"\\$&")}o(Mm,"escapeRegExp");function ua(t){if(t.startsWith("-"))return!1;let e=`^${t.split("*").map(Mm).join(".*?")}$`,n=new RegExp(e);return Um.some(r=>n.test(r))}o(ua,"enablesPlaywright");function Gm(){let t=process.env.DEBUG;if(t===void 0||t==="")return[];let e=t.split(/[\s,]+/).map(i=>i.trim()).filter(i=>i!==""),n=e.filter(i=>ua(i));if(n.length===0)return[];let r=e.filter(i=>!ua(i));return r.length===0?delete process.env.DEBUG:process.env.DEBUG=r.join(","),$m.warn("Playwright debug namespaces removed from DEBUG before playwright-core loaded",{removed:n,kept:r,debugFile:process.env.DEBUG_FILE??null,reason:"pw: namespaces write raw CDP messages \u2014 including the per-run session tokens written into the token database \u2014 to a sink that bypasses log redaction (CONTRACT-la \xA79, \xA711.10)"}),n}o(Gm,"sanitizePlaywrightDebugEnv");Gm();import{statSync as fa}from"node:fs";import{isAbsolute as Jm,join as Km}from"node:path";import{createRequire as Fm}from"node:module";var Te=Fm(import.meta.url)("playwright-core"),rt=Te.chromium,W_=Te.firefox,H_=Te.webkit,J_=Te.selectors,K_=Te.devices,pa=Te.errors,V_=Te.request,q_=Te._electron,Y_=Te._android;import{writeFileSync as Bm}from"node:fs";import{join as jm}from"node:path";var Wm="Local State",Hm={async_dns:{enabled:!1},dns_over_https:{mode:"off"}};function ma(t){Bm(jm(t,Wm),JSON.stringify(Hm),{flag:"wx"})}o(ma,"writeOsResolverLocalState");var wn="chromium";var ar="instances",lr="instance.json";var Vm=["--disable-backgrounding-occluded-windows","--disable-renderer-backgrounding"],ha={handleSIGINT:!1,handleSIGTERM:!1,handleSIGHUP:!1};async function ga(t){return ma(t.userDataDir),rt.launchPersistentContext(t.userDataDir,{headless:!t.headful,channel:wn,...ha,viewport:null,ignoreHTTPSErrors:t.allowInsecureHttps,chromiumSandbox:!t.disableBrowserSandbox,args:[`--disable-extensions-except=${t.extensionDist}`,`--load-extension=${t.extensionDist}`,"--no-first-run","--no-default-browser-check","--silent-debugger-extension-api",...t.headful?[]:["--screen-info={1280x1024}"],...t.keepBackgroundWindowsRendering?Vm:[]]})}o(ga,"launchExtensionContext");async function ya(t){return rt.launchPersistentContext(t,{headless:!0,channel:wn,...ha,chromiumSandbox:!0})}o(ya,"launchSandboxedProbeContext");async function wa(t,e){let n=await t.newCDPSession(e);try{let{windowId:r}=await n.send("Browser.getWindowForTarget");await n.send("Browser.setContentsSize",{windowId:r,width:1280,height:720})}finally{await n.detach()}}o(wa,"setRunnerContentViewport");function qm(t){let e=t.browser();if(e===null)throw new Error("context.browser() returned null for a persistent context \u2014 the browser handle is unusable, so neither its PID nor its version can be read");return e}o(qm,"requireBrowser");function Sa(t){return qm(t).version()}o(Sa,"readChromeVersion");async function cr(t,e){let n,r=new Promise(i=>{n=setTimeout(()=>i({settled:"timeout"}),e)});try{return await Promise.race([t.close().then(()=>({settled:"closed"}),i=>({settled:"rejected",error:i})),r])}finally{n!==void 0&&clearTimeout(n)}}o(cr,"raceClose");function dr(t){if(!Jm(t))throw new p(`[runtime] The extension dist path must be absolute, got ${JSON.stringify(t)}. A relative path would be resolved against the daemon's working directory.`);let e;try{e=fa(t)}catch(r){throw new p(`[runtime] The extension dist directory ${t} cannot be read. Chromium does NOT fail on a bad --load-extension: it would start without the extension and every run would time out in the readiness probe. Check PROGON_AGENT_EXTENSION_DIST.`,{cause:r})}if(!e.isDirectory())throw new p(`[runtime] The extension dist path ${t} is not a directory.`);let n=Km(t,"manifest.json");try{fa(n)}catch(r){throw new p(`[runtime] ${n} is missing, so ${t} is not a built extension. Build qa-extension, or point PROGON_AGENT_EXTENSION_DIST at a real dist.`,{cause:r})}}o(dr,"assertUsableExtensionDist");import{fetch as nf}from"undici";import{z as Ga}from"zod";var A=class extends Error{static{o(this,"GatewayError")}operation;constructor(e,n,r){super(n,{cause:r}),this.name=new.target.name,this.operation=e}},Z=class extends A{static{o(this,"GatewayTransportError")}constructor(e,n,r){super(e,`[gateway] ${e} failed before a response was received: ${n}`,r)}},x=class extends A{static{o(this,"GatewayHttpError")}status;errorCode;params;retryAfterMs;constructor(e,n,r,i,s,l=null){super(e,`[gateway] ${e} refused with HTTP ${n}: ${s}`),this.status=n,this.errorCode=r,this.params=i,this.retryAfterMs=l}},Ot=class extends x{static{o(this,"GatewayUnauthorizedError")}},O=class extends x{static{o(this,"TokenSupersededError")}},T=class extends A{static{o(this,"TerminalSignalError")}signal;constructor(e,n,r){super(e,`[gateway] agent revoked (${n}) during ${e}: ${r}`),this.signal=n}},At=class extends x{static{o(this,"EnrollmentCodeRejectedError")}},ot=class extends x{static{o(this,"ProtocolVersionMismatchError")}},ee=class extends x{static{o(this,"AgentUpgradeRequiredError")}constructor(e,n,r,i,s){super(e,n,r,i,`${s}. Update the agent with 'progon-agent update' and start it again.`)}},Ct=class extends x{static{o(this,"RunNotClaimableError")}},it=class extends x{static{o(this,"RunNotFoundError")}},fe=class extends A{static{o(this,"GatewayResponseSchemaError")}constructor(e,n,r){super(e,`[gateway] ${e} returned a body that violates the contract: ${n}`,r)}};import{readFileSync as Ym}from"node:fs";import{dirname as Xm,join as zm}from"node:path";import{fileURLToPath as Qm}from"node:url";var Zm=/^\d+\.\d+\.\d+$/,Ea=30,qo=null;function te(){if(qo!==null)return qo;let t=Se(Xm(Qm(import.meta.url))),e=JSON.parse(Ym(zm(t,"package.json"),"utf8")),n=typeof e=="object"&&e!==null?e.version:void 0;if(typeof n!="string"||!Zm.test(n))throw new Error(`[agent-version] The agent package.json in ${t} has no usable "version" field (got ${JSON.stringify(n)}, expected x.y.z), so the agent cannot state its version to the server. This is a packaging defect: the daemon must not run under an invented version.`);if(n.length>Ea)throw new Error(`[agent-version] The agent package version ${JSON.stringify(n)} is longer than the ${Ea} characters CONTRACT-la \xA75.1 allows for agentVersion.`);return qo=n,n}o(te,"readAgentVersion");function va(){return`agent/${te()}`}o(va,"agentClientHeaderValue");var Pt=class extends x{static{o(this,"EnrollmentSlowDownError")}retryAfterSec;constructor(e,n,r,i,s,l){super(e,n,r,i,s),this.retryAfterSec=l}},Nt=class extends x{static{o(this,"EnrollmentAccessDeniedError")}},Lt=class extends x{static{o(this,"EnrollmentRequestExpiredError")}},Dt=class extends x{static{o(this,"EnrollmentAlreadyCompletedError")}},$t=class extends x{static{o(this,"EnrollmentRequestInvalidError")}};function ba(t,e){return e.status===426&&e.errorCode==="client.upgrade_required"?K(ee,t,e):null}o(ba,"mapClientVersionRefusal");function _a(t){return t.status===401&&t.errorCode==="agent_enroll.invalid_code"?K(At,"enroll",t):t.status===409&&t.errorCode==="agent_enroll.protocol_version"?K(ot,"enroll",t):ne("enroll",t)}o(_a,"mapEnrollError");function ka(t){return t.status===409&&t.errorCode==="agent_enroll.protocol_version"?K(ot,"enrollment_request_create",t):ne("enrollment_request_create",t)}o(ka,"mapEnrollmentRequestCreateError");function Ra(t){if(t.status===429&&t.errorCode==="agent_enroll.slow_down"){let e=t.params===null?void 0:t.params.retryAfterSeconds,n=typeof e=="number"&&Number.isFinite(e)&&e>0?e:null;return new Pt("enrollment_request_poll",t.status,t.errorCode,t.params,t.message,n)}return t.status===403&&t.errorCode==="agent_enroll.access_denied"?K(Nt,"enrollment_request_poll",t):t.status===410&&t.errorCode==="agent_enroll.expired"?K(Lt,"enrollment_request_poll",t):t.status===410&&t.errorCode==="agent_enroll.already_completed"?K(Dt,"enrollment_request_poll",t):t.status===401&&t.errorCode==="agent_enroll.invalid_request"?K($t,"enrollment_request_poll",t):ne("enrollment_request_poll",t)}o(Ra,"mapEnrollmentRequestPollError");function Ta(t){return ne("enrollment_request_cancel",t)}o(Ta,"mapEnrollmentRequestCancelError");function xa(t){return xe("poll_desired_state",t,()=>ne("poll_desired_state",t))}o(xa,"mapPollDesiredStateError");function Ia(t){return xe("claim",t,()=>t.status===409&&t.errorCode==="run.not_claimable"?K(Ct,"claim",t):t.status===404?K(it,"claim",t):ne("claim",t))}o(Ia,"mapClaimError");function Oa(t){return xe("fail",t,()=>t.status===404?K(it,"fail",t):ne("fail",t))}o(Oa,"mapFailError");function Aa(t){return xe("token_status",t,()=>ne("token_status",t))}o(Aa,"mapTokenStatusError");function Ca(t){return xe("token_rotate",t,()=>ne("token_rotate",t))}o(Ca,"mapTokenRotateError");function Pa(t){return xe("declare_capabilities",t,()=>ne("declare_capabilities",t))}o(Pa,"mapDeclareCapabilitiesError");function Na(t){return xe("identity_session",t,()=>ne("identity_session",t))}o(Na,"mapIdentitySessionError");function La(t){return xe("revoke",t,()=>ne("revoke",t))}o(La,"mapRevokeError");function Da(t){return xe("launch_session",t,()=>ne("launch_session",t))}o(Da,"mapLaunchSessionError");function xe(t,e,n){return e.status===403&&e.errorCode==="agents.revoked"?new T(t,"http_403_agents_revoked",e.message):e.status===401&&e.errorCode==="agents.token_superseded"?K(O,t,e):e.status===401?K(Ot,t,e):n()}o(xe,"bearerRoute");function K(t,e,n){return new t(e,n.status,n.errorCode,n.params,n.message,n.retryAfterMs)}o(K,"named");function ne(t,e){return K(x,t,e)}o(ne,"generic");var $a=w("gateway-http");async function st(t){let e={accept:"application/json","x-progon-client":va()};t.agentToken!==null&&(e.authorization=`Bearer ${t.agentToken}`),t.body!==null&&(e["content-type"]="application/json"),$a.debug("Gateway request",{operation:t.operation,method:t.method,url:t.url.toString()});let n;try{n=await t.fetchImpl(t.url,{method:t.method,headers:e,body:t.body===null?void 0:JSON.stringify(t.body),signal:t.signal})}catch(i){throw new Z(t.operation,ur(i),i)}let r;try{r=await n.text()}catch(i){throw new Z(t.operation,ur(i),i)}if(!n.ok){let i=Xo(n,r);throw $a.debug("Gateway request refused",{operation:t.operation,status:i.status,errorCode:i.errorCode}),ba(t.operation,i)??t.mapHttpError(i)}try{return JSON.parse(r)}catch(i){throw new fe(t.operation,`the ${n.status} response body is not valid JSON`,i)}}o(st,"executeGatewayRequest");function V(t,e){if(e.success)return e.data;throw new fe(t,zo(e.error),e.error)}o(V,"parseGatewayBody");function pr(t,e){return new URL(`${t.replace(/\/+$/,"")}${e}`)}o(pr,"buildServerRouteUrl");function Xo(t,e){let{status:n}=t,r=ef(t.headers.get("retry-after")),i;try{i=JSON.parse(e)}catch{return{status:n,errorCode:null,params:null,message:Yo,retryAfterMs:r}}if(typeof i!="object"||i===null||Array.isArray(i))return{status:n,errorCode:null,params:null,message:Yo,retryAfterMs:r};let s=i,l=s.error_code,c=s.params,a=s.message;return{status:n,errorCode:typeof l=="string"?l:null,params:typeof c=="object"&&c!==null&&!Array.isArray(c)?c:null,message:typeof a=="string"?C(a):Yo,retryAfterMs:r}}o(Xo,"readErrorEnvelope");function ef(t){return t===null||!/^\d+$/.test(t)?null:Number(t)*1e3}o(ef,"parseRetryAfterMs");var Yo="the response body carried no Progon error envelope";function ur(t){if(!(t instanceof Error))return C(String(t));let e=tf(t.cause);return C(e===""?t.message:`${t.message}: ${e}`)}o(ur,"describeTransportCause");function tf(t){return t instanceof Error?t.message!==""||!(t instanceof AggregateError)?t.message:t.errors.map(e=>e instanceof Error?e.message:"").filter(e=>e!=="").join("; "):""}o(tf,"causeText");function zo(t){let e=t.issues;if(!Array.isArray(e)||e.length===0)return"the response body failed schema validation (the validator reported no issue list)";let n=e.map(r=>{let i=r.path;return!Array.isArray(i)||i.length===0?"<root>":i.map(s=>String(s)).join(".")});return`${e.length} schema violation(s) at: ${n.join(", ")}`}o(zo,"summarizeSchemaViolation");var mr=[...ns,rs,os,ss,is,as,ls];import{z as at}from"zod";var Ua=at.object({rotationDue:at.boolean(),tokenRotatedAt:at.string().nullable(),anchorAt:at.string(),intervalDays:at.number().int()}),Ma=at.object({agentToken:at.string().regex(vt)});var Sn=w("gateway-client"),rf=Ga.object({success:Ga.literal(!0)}),of="/api/agent-gateway";function q(t,e){return pr(t,`${of}${e}`)}o(q,"buildGatewayUrl");var Fa=3e5,ja=1e4,Ba={headersTimeout:Fa,bodyTimeout:Fa,connect:{timeout:ja}};function sf(){let t=Js(process.env);return Fs(un(process.env),t===void 0?Ba:{...Ba,connect:{timeout:ja,ca:t}},t)}o(sf,"buildGatewayDispatcher");var Qo,Mt=o((t,e)=>{if(Qo===void 0){let n=sf();Qo=o((r,i)=>nf(r,{...i,dispatcher:n}),"defaultGatewayFetch")}return Qo(t,e)},"pinnedGatewayFetch"),Ut=class{static{o(this,"GatewayEnrollmentClient")}serverUrl;machine;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.machine=e.machine,this.fetchImpl=e.fetchImpl??Mt}async enroll(e,n){let r={...this.machine,enrollmentCode:e,protocolVersion:1},i=await st({operation:"enroll",method:"POST",url:q(this.serverUrl,"/enroll"),agentToken:null,body:r,signal:n?.signal,fetchImpl:this.fetchImpl,mapHttpError:_a}),s=V("enroll",qn.safeParse(i));return Sn.info("Agent enrolled",{agentId:s.agentId,pollWaitSec:s.pollWaitSec,protocolVersion:s.protocolVersion}),s}},Ge=class{static{o(this,"GatewayClient")}serverUrl;agentToken;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.agentToken=e.agentToken,this.fetchImpl=e.fetchImpl??Mt}async authenticatedRequest(e){return st({operation:e.operation,method:e.method,url:e.url,agentToken:this.agentToken,body:e.body,signal:e.signal,fetchImpl:this.fetchImpl,mapHttpError:e.mapHttpError})}async pollDesiredState(e){let n=q(this.serverUrl,"/state");e?.waitSec!==void 0&&n.searchParams.set("waitSec",String(e.waitSec));let r=await this.authenticatedRequest({operation:"poll_desired_state",method:"GET",url:n,body:null,signal:e?.signal,mapHttpError:xa}),i=V("poll_desired_state",vs.safeParse(r));if(i.agent.revoked)throw new T("poll_desired_state","desired_state_snapshot","the desired-state snapshot reports this agent as revoked");return i}async claimRun(e){let n=await this.authenticatedRequest({operation:"claim",method:"POST",url:q(this.serverUrl,`/runs/${encodeURIComponent(e)}/claim`),body:{capabilities:mr},signal:void 0,mapHttpError:Ia});return V("claim",Rs.safeParse(n))}async issueIdentitySession(e,n){let r=await this.authenticatedRequest({operation:"identity_session",method:"POST",url:q(this.serverUrl,`/runs/${encodeURIComponent(e)}/identities/${encodeURIComponent(n)}/session`),body:null,signal:void 0,mapHttpError:Na});return V("identity_session",Go.safeParse(r)).extensionSession}async issueLaunchSession(e,n){let r=await this.authenticatedRequest({operation:"launch_session",method:"POST",url:q(this.serverUrl,`/runs/${encodeURIComponent(e)}/launches/${encodeURIComponent(n)}/session`),body:null,signal:void 0,mapHttpError:Da});return V("launch_session",Go.safeParse(r)).extensionSession}async failRun(e,n){let r=await this.authenticatedRequest({operation:"fail",method:"POST",url:q(this.serverUrl,`/runs/${encodeURIComponent(e)}/fail`),body:n,signal:void 0,mapHttpError:Oa}),i=V("fail",ks.safeParse(r));return Sn.info("Reported run failure to the gateway",{runId:e,reason:n.reason,status:i.status}),i}async getTokenRotationStatus(e){let n=await this.authenticatedRequest({operation:"token_status",method:"GET",url:q(this.serverUrl,"/token"),body:null,signal:e?.signal,mapHttpError:Aa});return V("token_status",Ua.safeParse(n))}async rotateToken(e){let n=await this.authenticatedRequest({operation:"token_rotate",method:"POST",url:q(this.serverUrl,"/token/rotate"),body:null,signal:e?.signal,mapHttpError:Ca});return V("token_rotate",Ma.safeParse(n))}async declareCapabilities(e){await this.authenticatedRequest({operation:"declare_capabilities",method:"POST",url:q(this.serverUrl,"/capabilities"),body:{capabilities:mr},signal:e?.signal,mapHttpError:Pa}),Sn.info("Capabilities declared",{capabilities:mr})}async revokeSelf(){let e=await this.authenticatedRequest({operation:"revoke",method:"POST",url:q(this.serverUrl,"/revoke"),body:null,signal:void 0,mapHttpError:La});V("revoke",rf.safeParse(e)),Sn.info("Agent registration revoked on the server by this agent")}useAgentToken(e){this.agentToken=e,Sn.info("Adopted a rotated agent token for all subsequent gateway requests")}};import{z as R}from"zod";var fr=R.object({id:R.string().min(1),status:R.string(),revision:R.number(),counts:R.object({total:R.number().int(),queued:R.number().int(),running:R.number().int(),finished:R.number().int(),notStarted:R.number().int()}),current:R.string().nullable(),waitingForRunner:R.object({ahead:R.number().int()}).nullable(),verdict:R.string().nullable(),webUrl:R.string().min(1)}),Wa=R.object({runnerId:R.string().min(1),enrollmentCode:R.string().min(1)}),af=R.object({scenarioId:R.string(),scenarioName:R.string(),status:R.string(),outcome:R.string().nullable(),failureReason:R.string().nullable(),notStartedReason:R.string().nullable(),failedStep:R.object({number:R.string(),name:R.string()}).nullable()}),Ha=R.object({items:R.array(af),total:R.number().int()}),hr="finished",gr="passed",yr="failed",Ja="no_result",Zo="passed",ei="failed",Ka="finished",wr="not_started";var lf="/api/ci/v1",Fe=class extends Error{static{o(this,"CiApiError")}},he=class extends Fe{constructor(n,r,i,s,l){super(s);this.status=n;this.errorCode=r;this.params=i;this.retryAfterMs=l}static{o(this,"CiRefusalError")}},Gt=class extends Fe{static{o(this,"CiNoAnswerError")}},lt=class extends Fe{static{o(this,"CiBadAnswerError")}},cf=100,Sr=class{static{o(this,"CiApiClient")}serverUrl;key;requestTimeoutMs;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.key=e.key,this.requestTimeoutMs=e.requestTimeoutMs,this.fetchImpl=e.fetchImpl??Mt}async createRunner(e){let n=await this.call("POST","/runners",null,this.requestTimeoutMs,e);return this.parse(Wa,n)}async createLaunch(e,n){let r=await this.call("POST","/launches",e,this.requestTimeoutMs,n);return this.parse(fr,r)}async getLaunch(e,n){let r=`/launches/${encodeURIComponent(e)}`,i=await this.call("GET",r,null,this.requestTimeoutMs,n);return this.parse(fr,i)}async listItems(e,n,r){let i=`/launches/${encodeURIComponent(e)}/items?offset=${n}&limit=${cf}`,s=await this.call("GET",i,null,this.requestTimeoutMs,r);return this.parse(Ha,s)}async stopLaunch(e,n){let r=`/launches/${encodeURIComponent(e)}/stop`,i=await this.call("POST",r,null,n,void 0);return this.parse(fr,i)}async call(e,n,r,i,s){let l=pr(this.serverUrl,`${lf}${n}`),c={accept:"application/json",authorization:`Bearer ${this.key}`};r!==null&&(c["content-type"]="application/json");let a=new AbortController,d=!1,u=setTimeout(()=>{d=!0,a.abort()},i),m=o(()=>a.abort(),"onCallerAbort");s!==void 0&&(s.aborted?a.abort():s.addEventListener("abort",m,{once:!0}));let g,E;try{g=await this.fetchImpl(l,{method:e,headers:c,body:r===null?void 0:JSON.stringify(r),signal:a.signal}),E=await g.text()}catch(S){throw new Gt(d?`no answer within ${Math.round(i/1e3)}s`:ur(S))}finally{clearTimeout(u),s?.removeEventListener("abort",m)}if(!g.ok){let S=Xo(g,E);throw new he(S.status,S.errorCode,S.params,S.message,S.retryAfterMs)}try{return JSON.parse(E)}catch{throw new lt(`the ${g.status} answer of Progon is not valid JSON`)}}parse(e,n){let r=e.safeParse(n);if(r.success)return r.data;throw new lt(`the answer of Progon does not match this CLI: ${zo(r.error)}`)}};var Va=`progon-agent ci run \u2014 run Progon scenarios as a step of a CI pipeline
|
|
49
49
|
|
|
50
50
|
Usage:
|
|
51
51
|
progon-agent ci run (--spec <id> | --scenario <id> [--scenario <id> ...]) [options]
|
|
@@ -77,38 +77,38 @@ Exit codes:
|
|
|
77
77
|
2 the launch was not created: fix the pipeline setup (command, key, scenarios, runner)
|
|
78
78
|
3 no result: runner offline or queue full, Progon or network failure, --timeout expired
|
|
79
79
|
before the launch was created, or a launch that ended without a failed scenario but not
|
|
80
|
-
fully passed`;function qa(t){let[e,...n]=t;return e===void 0?{kind:"refused",reason:"'ci' needs a command: run"}:
|
|
80
|
+
fully passed`;function qa(t){let[e,...n]=t;return e===void 0?{kind:"refused",reason:"'ci' needs a command: run"}:df(e)?{kind:"help"}:e!=="run"?{kind:"refused",reason:`unknown command 'ci ${e}'`}:uf(n)}o(qa,"parseCiArgs");function df(t){return t==="--help"||t==="-h"||t==="help"}o(df,"isHelpFlag");function uf(t){let e=null,n=[],r=null,i=null,s=null,l=!1,c=null;for(let d=0;d<t.length;d+=1){let u=t[d];if(u==="--help"||u==="-h")return{kind:"help"};if(u==="--in-job"){if(l)return En(u);l=!0;continue}if(!pf.has(u))return{kind:"refused",reason:`unknown option '${u}' for 'ci run'`};let m=t[d+1];if(m===void 0||m===""||m.startsWith("--"))return{kind:"refused",reason:`'${u}' needs a value`};switch(d+=1,u){case"--spec":if(e!==null)return{kind:"refused",reason:"'--spec' is given twice"};e=m;break;case"--scenario":n.push(m);break;case"--environment":if(r!==null)return En(u);r=m;break;case"--entry-url":if(i!==null)return En(u);i=m;break;case"--runner":if(s!==null)return En(u);s=m;break;case"--timeout":{if(c!==null)return En(u);let g=mf(m);if(g===null)return{kind:"refused",reason:`'--timeout' takes a duration like 90s, 30m or 1h30m, got '${m}'`};c=g;break}}}if(l&&s!==null)return{kind:"refused",reason:"'--runner' cannot be used with '--in-job'"};if(e!==null&&n.length>0)return{kind:"refused",reason:"give either '--spec' or '--scenario', not both"};let a=e!==null?{kind:"spec",specNodeId:e}:n.length>0?{kind:"scenarios",scenarioIds:n}:null;return a===null?{kind:"refused",reason:"give '--spec <id>' or '--scenario <id>'"}:{kind:"run",options:{selection:a,environmentId:r,entryUrl:i,runnerId:s,inJob:l,timeoutMs:c}}}o(uf,"parseRunFlags");var pf=new Set(["--spec","--scenario","--environment","--entry-url","--runner","--timeout"]);function En(t){return{kind:"refused",reason:`'${t}' is given twice`}}o(En,"repeatedFlag");function mf(t){let e=/^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/.exec(t);if(e===null||t==="")return null;let[,n,r,i]=e,s=o(c=>c===void 0?0:Number(c),"unitValue"),l=(s(n)*3600+s(r)*60+s(i))*1e3;return l>0&&l<=2147483647?l:null}o(mf,"parseDurationMs");var ti=0,ff=1,ct=2,U=3,hf=new Map([[409,new Set(["agents.runner_ambiguous","agents.capability_missing","agent_enroll.protocol_version","agents.one_shot_used"])],[426,new Set(["client.upgrade_required"])]]);function vn(t,e){return t===400||t===401||t===403||t===404||t===422||e!==null&&hf.get(t)?.has(e)===!0?ct:U}o(vn,"exitCodeOfRefusalBeforeLaunch");function Ya(t){return t===gr?ti:t===yr?ff:U}o(Ya,"exitCodeOfVerdict");function D(t,e){let n=t[e];return n===void 0||n===""?null:n}o(D,"readJobVariable");function Xa(t){return t.GITHUB_ACTIONS==="true"?gf(t):t.GITLAB_CI==="true"?yf(t):D(t,"BITBUCKET_BUILD_NUMBER")!==null?wf(t):null}o(Xa,"readCiJobFacts");function gf(t){let e=t.GITHUB_EVENT_NAME==="pull_request"?D(t,"GITHUB_HEAD_REF"):D(t,"GITHUB_REF_NAME"),n=D(t,"GITHUB_SERVER_URL"),r=D(t,"GITHUB_REPOSITORY"),i=D(t,"GITHUB_RUN_ID"),s=n===null||r===null||i===null?null:`${n}/${r}/actions/runs/${i}`;return ni(D(t,"GITHUB_SHA"),e,s)}o(gf,"fromGitHub");function yf(t){return ni(D(t,"CI_COMMIT_SHA"),D(t,"CI_COMMIT_REF_NAME"),D(t,"CI_JOB_URL"))}o(yf,"fromGitLab");function wf(t){let e=D(t,"BITBUCKET_REPO_FULL_NAME"),n=D(t,"BITBUCKET_BUILD_NUMBER"),r=e===null||n===null?null:`https://bitbucket.org/${e}/pipelines/results/${n}`,i=D(t,"BITBUCKET_BRANCH"),s=i===null?D(t,"BITBUCKET_TAG"):i;return ni(D(t,"BITBUCKET_COMMIT"),s,r)}o(wf,"fromBitbucket");function ni(t,e,n){return t===null&&e===null&&n===null?null:{...t===null?{}:{commit:t},...e===null?{}:{ref:e},...n===null?{}:{runUrl:n}}}o(ni,"factsOf");import{mkdtempSync as bg,rmSync as _g}from"node:fs";import{tmpdir as kg}from"node:os";import{join as hc}from"node:path";import{chmodSync as Rf,cpSync as Tf,mkdirSync as xf,readdirSync as If,renameSync as Of,rmSync as ii,statSync as ol,writeFileSync as Af}from"node:fs";import{dirname as Cf,join as Ft}from"node:path";import{fileURLToPath as Pf}from"node:url";import{randomBytes as Sf}from"node:crypto";import{lstatSync as za,readFileSync as Ef,renameSync as vf,rmSync as bf,writeFileSync as _f}from"node:fs";import{join as Qa}from"node:path";var kf=w("cleanup-ownership"),Er="progon-agent-cleanup.json";function Za(t){return/^progon-agent-cleanup\.json\.tmp-\d+-[0-9a-f]{16}$/.test(t)}o(Za,"isCleanupTemporaryEntry");var vr={version:1,serviceFiles:!1,extensionCopy:!1,profiles:[]};function br(t){let e=Qa(t,Er),n;try{if(!za(e).isFile())throw new Error("Cleanup ownership marker is not a regular file");n=JSON.parse(Ef(e,"utf8"))}catch(s){if(P(s))return null;throw s}if(typeof n!="object"||n===null)throw new Error("Invalid cleanup ownership marker");let r=n,i=r.profiles;if(r.version!==1||typeof r.serviceFiles!="boolean"||typeof r.extensionCopy!="boolean"||!Array.isArray(i)||!i.every(s=>typeof s=="string"&&s!==""&&s!=="."&&s!==".."&&!/[\\/\0]/.test(s)))throw new Error("Invalid cleanup ownership marker");return{version:1,serviceFiles:r.serviceFiles,extensionCopy:r.extensionCopy,profiles:i}}o(br,"readCleanupOwnership");function _r(t,e){let n=Qa(t,Er),r=`${n}.tmp-${process.pid}-${Sf(8).toString("hex")}`;try{_f(r,JSON.stringify(e),{flag:"wx",mode:384,flush:!0}),vf(r,n)}finally{bf(r,{force:!0})}}o(_r,"writeCleanupOwnership");function el(t){try{za(t)}catch(e){if(P(e))return;throw e}nl(t,"serviceFiles")}o(el,"rememberServiceCleanup");function tl(t){nl(t,"extensionCopy")}o(tl,"rememberExtensionCopy");function nl(t,e){let n=br(t)??vr;n[e]||_r(t,{...n,[e]:!0})}o(nl,"remember");function kr(t,e){return rl(t,e,"remember")}o(kr,"rememberProfileCleanup");function ri(t,e){return rl(t,e,"forget")}o(ri,"forgetProfileCleanup");function rl(t,e,n){try{let r=br(t)??vr,{profiles:i}=r;return i.includes(e)===(n==="remember")||_r(t,{...r,profiles:n==="remember"?[...i,e]:i.filter(s=>s!==e)}),!0}catch(r){return kf.warn("Could not update profile cleanup ownership",{stateDir:t,runId:e,operation:n,err:r instanceof Error?r.message:String(r)}),!1}}o(rl,"updateProfileCleanup");var Rr=w("extension-dist"),Nf="extension-dist",ai="extension-dist",si=`${ai}.tmp-`,li="agent-manifest.json";function sl(t){return t.startsWith(si)&&/^\d+$/.test(t.slice(si.length))}o(sl,"isStagingDirName");function al(t){return t===ai||sl(t)}o(al,"isExtensionWorkingCopyName");var il="manifest.json";function Lf(){return Se(Cf(Pf(import.meta.url)))}o(Lf,"packageRoot");function Df(){return $f(Ft(Lf(),Nf))}o(Df,"resolveBundledExtensionSource");function $f(t){let e;try{e=ol(t)}catch(r){throw P(r)?new Error(oi(t,"the directory does not exist"),{cause:r}):r}if(!e.isDirectory())throw new Error(oi(t,"that path is not a directory"));let n=Ft(t,il);try{ol(n)}catch(r){throw P(r)?new Error(oi(t,`it holds no ${il}`),{cause:r}):r}return t}o($f,"assertBundledExtensionSource");function oi(t,e){return`[extension-dist] No extension dist is bundled in this package (${t}): ${e}.
|
|
81
81
|
This package was built WITHOUT the bundling step. Run 'npm run bundle:extension' in the agent package (it copies a built qa-extension dist in; set PROGON_EXTENSION_DIST_SRC to point at that dist if it is not the sibling checkout), then reinstall or restart the daemon.
|
|
82
|
-
For a dev or E2E stand you can instead set PROGON_AGENT_EXTENSION_DIST to an already agent-mode dist, which bypasses the bundled copy entirely (CONTRACT-la \xA78).`}o(oi,"bundledMissingMessage");function
|
|
83
|
-
`,"utf8")}o(
|
|
84
|
-
Either enroll the agent ('progon-agent enroll <code>'), which persists the identity the server issued, or set PROGON_AGENT_EXTENSION_DIST to a dist that is already in agent mode (dev/E2E path, \xA78).`);return t}o(ci,"requireManifestAgentId");function ge(t,e=Math.random){if(t<0)throw new Error(`[backoff] attempt must be >= 0, got ${t}. Pass 0 for the first reconnect after a disconnect.`);let n=Math.min(6e4,1e3*Math.pow(2,Math.min(t,26)));return Math.floor(e()*n)}o(ge,"computeBackoffDelayMs");function Be(t){let e=
|
|
85
|
-
`)){let r=n.trim();if(r==="")continue;let i=Number(r);!Number.isInteger(i)||i===process.pid||e.push(i)}return e}o(
|
|
86
|
-
`)){let l=s.indexOf(" ");if(l===-1)continue;let c=Number(s.slice(0,l).trim()),a=s.slice(l+1);!Number.isInteger(c)||c===process.pid||
|
|
87
|
-
`)){let r=n.trim().split(/\s+/);if(r.length<3)continue;let[i,s,l]=r,c=Number(i),a=Number(s),d=Number(l);!Number.isInteger(c)||!Number.isInteger(a)||!Number.isInteger(d)||e.push({pid:c,ppid:a,pgid:d})}return e}o(cl,"readProcessTable");function
|
|
88
|
-
`);async function
|
|
89
|
-
${
|
|
90
|
-
Chromium's output: ${r instanceof Error?r.message:String(r)}`,{cause:r})}finally{await
|
|
91
|
-
`)){let r=ph.exec(n)?.[1];r!==void 0&&r!==""&&e.push(r)}return e.length===0?null:e.join(" | ")}o(Rl,"browserStderrOf");var mh=new Set(["ERR_CONNECTION_REFUSED","ERR_CONNECTION_RESET","ERR_CONNECTION_CLOSED","ERR_CONNECTION_FAILED","ERR_CONNECTION_TIMED_OUT","ERR_ADDRESS_UNREACHABLE","ERR_TIMED_OUT"]),fh=/\bnet::(ERR_[A-Z0-9_]+)\b/;function Tl(t){if(hh(t))return"timeout";let e=fh.exec(mi(t))?.[1];return e===void 0?"other":e==="ERR_NAME_NOT_RESOLVED"?"name_not_resolved":mh.has(e)?"unreachable":e.startsWith("ERR_CERT_")?"certificate":"other"}o(Tl,"entryFailureOf");function hh(t){let e=new Set,n=t;for(;n instanceof Error&&!e.has(n);){if(n instanceof pa.TimeoutError)return!0;e.add(n),n=n.cause}return!1}o(hh,"causeChainHasTimeout");var We=class extends Error{static{o(this,"InstanceAlreadyRegisteredError")}runId;userDataDir;constructor(e,n,r){super(`[runtime] refusing to launch run ${e}: instance directory already exists at ${n}. Either this run is already live, or a previous daemon left it behind (the startup sweep clears leftovers \u2014 CONTRACT-la \xA715 A3, gate G-3).`,{cause:r}),this.name="InstanceAlreadyRegisteredError",this.runId=e,this.userDataDir=n}},Cr=class extends Error{static{o(this,"RuntimeBusyError")}requestedRunId;activeRunId;constructor(e,n){super(`[runtime] refusing to launch run ${e}: this runtime already owns the browser instance for run ${n}. An agent runs at most one run at a time (CONTRACT-la \xA73.1, \xA715 A3).`),this.name="RuntimeBusyError",this.requestedRunId=e,this.activeRunId=n}};var re=w("browser-instance");async function Pr(t){let e=await ae(t.runId,"browser_launch",()=>ga({userDataDir:t.userDataDir,extensionDist:t.extensionDist,headful:t.headful,allowInsecureHttps:t.allowInsecureHttps,disableBrowserSandbox:t.disableBrowserSandbox,keepBackgroundWindowsRendering:t.keepBackgroundWindowsRendering}));t.onContext(e),t.assertNotAborted();let n=await ae(t.runId,"browser_version",()=>Sa(e)),r=await ae(t.runId,"readiness_probe",()=>kl(e));await yh(t,r.worker);let{entryUrl:i}=t;return i===null?await ae(t.runId,"empty_tab",()=>vh(e)):await ae(t.runId,"entry_navigation",()=>Eh(e,i)),await wh(t,e),{context:e,chromeVersion:n,extensionId:r.extensionId,readinessAttempts:r.attempts,readyAfterMs:r.readyAfterMs}}o(Pr,"bringUpBrowser");async function yh(t,e){let n=await ae(t.runId,"token_seed",()=>wl(e,t.extensionSession));re.info("Run session seeded into the browser profile",{runId:t.runId,userDataDir:t.userDataDir,accessTokenLength:n.accessTokenLength,refreshTokenLength:n.refreshTokenLength}),await ae(t.runId,"command_seed",()=>Sl(e,t.command)),re.info("Command envelope seeded",{runId:t.runId,userDataDir:t.userDataDir,command:t.command})}o(yh,"seed");async function wh(t,e){let n=await ae(t.runId,"command_ack",()=>El(e,t.runId,15e3));if(n.outcome==="rejected")throw new je(t.runId,"command_ack",`the extension refused the command envelope: ${n.reason}`);re.info("Command envelope dispatched by the extension",{runId:t.runId,userDataDir:t.userDataDir,kind:t.command.kind})}o(wh,"awaitDispatchAck");async function bn(t,e){let n=Date.now(),r="closed",i=null,s=null;if(e.context!==null){let g=await lr(e.context,e.timeoutMs);g.settled==="closed"?r="closed":g.settled==="timeout"?(r="timeout-force-killed",re.error("context.close() did not settle before the deadline \u2014 force-killing",{runId:e.instanceKey,timeoutMs:e.timeoutMs,userDataDir:e.userDataDir})):(r="close-failed-force-killed",re.error("context.close() rejected \u2014 force-killing",{runId:e.instanceKey,userDataDir:e.userDataDir,err:g.error instanceof Error?g.error.message:String(g.error)}))}if(r!=="closed"||e.trigger==="instance_lost"||e.trigger==="dispose_during_launch")try{i=await Bt(e.userDataDir)}catch(g){s=g,re.error("Force-kill of the run process tree failed",{runId:e.instanceKey,userDataDir:e.userDataDir,trigger:e.trigger,disposeOutcome:r,err:g instanceof Error?g.message:String(g)})}let c=s===null&&(i===null||i.survivorPids.length===0),a=null,d=!1;if(c)try{t.release(e.instanceKey),d=!0}catch(g){a=g,re.error("Failed to remove the instance directory after teardown",{runId:e.instanceKey,userDataDir:e.userDataDir,err:g instanceof Error?g.message:String(g)})}else re.error("Instance directory KEPT \u2014 the force-kill is unconfirmed and the startup sweep must still be able to find this tree",{runId:e.instanceKey,userDataDir:e.userDataDir,disposeOutcome:r,killFailed:s!==null,survivorPids:i===null?null:i.survivorPids});let u={runId:e.instanceKey,outcome:r,kill:i,instanceReleased:d,durationMs:Date.now()-n},m={runId:u.runId,disposeOutcome:u.outcome,trigger:e.trigger,contextPresent:e.context!==null,kill:u.kill,killFailed:s!==null,instanceReleased:u.instanceReleased,durationMs:u.durationMs};return s!==null||a!==null?re.error("Instance disposed with a failed cleanup step",m):re.info("Instance disposed",m),{result:u,killConfirmed:c,failure:Sh(e,i,s,a)}}o(bn,"tearDownBrowser");function Nr(t,e){let{instanceKey:n}=e;if(!e.killConfirmed)throw re.error("Dispose repeated for an instance whose force-kill was never confirmed \u2014 the instance directory stays for the startup sweep",{runId:n,disposeOutcome:e.result.outcome,kill:e.result.kill,instanceReleased:!1}),new Error(`[runtime] the instance directory for ${n} is deliberately retained: the force-kill of its process tree was never confirmed, and this runtime does not retry it. The startup sweep (CONTRACT-la \xA715 A3 rule 2) is the next eraser.`);let r=Date.now();re.warn("Dispose repeated for an instance whose directory survived \u2014 retrying",{runId:n,disposeOutcome:e.result.outcome}),t.release(n);let i={...e.result,instanceReleased:!0,durationMs:Date.now()-r};return re.info("Instance released on a repeated dispose",{runId:n,disposeOutcome:i.outcome,instanceReleased:!0,durationMs:i.durationMs}),i}o(Nr,"retryRetainedRelease");function Sh(t,e,n,r){return r!==null?xl(r):n!==null?xl(n):e!==null&&e.survivorPids.length>0?new Error(`[runtime] force-kill for run ${t.instanceKey} left ${e.survivorPids.length} process(es) alive after the settle delay (${e.survivorPids.join(", ")}). The instance directory ${t.userDataDir} is kept so the startup sweep can re-discover them (CONTRACT-la \xA715 A3 rule 2).`):null}o(Sh,"teardownFailure");function xl(t){return t instanceof Error?t:new Error(String(t))}o(xl,"asError");async function ae(t,e,n){try{return await n()}catch(r){throw r instanceof je||r instanceof We?r:new je(t,e,r instanceof Error?r.message:String(r),r)}}o(ae,"stage");async function Eh(t,e){await(await Il(t)).goto(e,{waitUntil:"domcontentloaded"})}o(Eh,"navigateToEntry");async function vh(t){await Il(t)}o(vh,"prepareEmptyTab");async function Il(t){let e=t.pages()[0],n=e===void 0?await t.newPage():e;return await wa(t,n),n}o(Il,"sizedFirstPage");import Lr from"node:os";import{createRequire as bh}from"node:module";var Ol=bh(import.meta.url);function _h(){let t=Ol.resolve("playwright-core/package.json"),e=Ol(t);if(typeof e!="object"||e===null)throw new Error(`[runtime] ${t} did not parse into an object.`);let n=e.version;if(typeof n!="string"||n==="")throw new Error(`[runtime] ${t} declares no version string.`);return n}o(_h,"readPlaywrightCoreVersion");function Al(t){return{node:process.version,platform:`${Lr.platform()} ${Lr.release()} ${Lr.arch()}`,cpus:Lr.cpus().length,playwrightCore:_h(),chromiumExecutable:rt.executablePath(),channel:yn,extensionDist:t}}o(Al,"buildEnvFingerprint");async function Dr(t){let e=new Date().toISOString(),r=t.serviceWorkers()[0];if(r===void 0)return{ok:!1,observedAt:e,reason:"service_worker_absent",detail:"the browser context exposes no service worker \u2014 the extension is not running"};try{let i=await xe({operation:"read playback, job pulse and identity detach from chrome.storage.session",timeoutMs:1e4,evaluate:o(()=>r.evaluate(async s=>{let l=await new Promise(g=>chrome.storage.session.get(["tabStates",s,"agent:detached-identity"],g)),c=l.tabStates,a=typeof c!="object"||c===null?[]:Object.entries(c).map(([g,E])=>{let S=typeof E=="object"&&E!==null?E.playback:null;if(typeof S!="object"||S===null)return{tabId:g,playback:null};let b=S;return{tabId:g,playback:{runId:typeof b.runId=="string"?b.runId:null,status:typeof b.status=="string"?b.status:null,currentStepIndex:typeof b.currentStepIndex=="number"?b.currentStepIndex:null}}}),d=l[s],u=typeof d!="object"||d===null?null:(()=>{let g=d;return{agentJobId:typeof g.agentJobId=="string"?g.agentJobId:null,updatedAt:typeof g.updatedAt=="string"?g.updatedAt:null}})(),m=l["agent:detached-identity"];if(m===void 0)return{tabs:a,agentJob:u};if(typeof m!="object"||m===null||!("agentJobId"in m)||typeof m.agentJobId!="string"||!("identityId"in m)||typeof m.identityId!="string")throw new Error("Unreadable identity detach acknowledgement in chrome.storage.session");return{tabs:a,agentJob:u,detachedIdentity:{agentJobId:m.agentJobId,identityId:m.identityId}}},cs),"evaluate")});return{ok:!0,observedAt:e,...i}}catch(i){return{ok:!1,observedAt:e,reason:"evaluate_failed",detail:i instanceof Error?i.message:String(i)}}}o(Dr,"probePlaybackSession");var jt=w("task-browser-instances"),fi=class extends Error{static{o(this,"TaskBrowserLaunchAbortedError")}subjectId;constructor(e){super(`[runtime] launch of the instance of task browser subject ${e} was aborted: the instance was disposed while the browser was still coming up, so it was torn down instead of being kept.`),this.name="TaskBrowserLaunchAbortedError",this.subjectId=e}},Wt=class{static{o(this,"TaskBrowserInstances")}#e;#t;#n;#r;#i;#a;#l=new Map;#o=new Map;constructor(e){this.#e=e.registry,this.#t=e.extensionDist,this.#n=e.allowInsecureHttps,this.#r=e.disableBrowserSandbox,this.#i=e.onLost,this.#a=e.kind}subjectIdsWithInstance(){return[...this.#l.keys()]}async start(e,n,r,i){let s=this.#l.get(n);if(s!==void 0)throw new Error(`[runtime] task browser subject ${n} already has an instance in state ${s.state}`);let l=this.#m(e.jobId,n),c=await ae(e.jobId,"instance_reserve",()=>{let u=this.#o.get(l);return u!==void 0&&this.#d(u),this.#e.reserve(l,e.deadlineAt)}),a={subjectId:n,jobId:e.jobId,instanceKey:l,userDataDir:c.userDataDir,state:"launching",context:null,contextAtTeardown:null,teardown:null};this.#l.set(n,a),jt.info("Launching the browser task browser instance",{runId:e.jobId,workflowId:e.workflowId,subjectId:n,headful:e.headful,userDataDir:c.userDataDir,deadlineAt:e.deadlineAt});let d=Date.now();try{let u=await Pr({runId:e.jobId,userDataDir:c.userDataDir,extensionDist:this.#t,headful:e.headful,allowInsecureHttps:this.#n,disableBrowserSandbox:this.#r,keepBackgroundWindowsRendering:!0,extensionSession:r,command:i,entryUrl:e.entryUrl,onContext:o(m=>{a.context=m},"onContext"),assertNotAborted:o(()=>this.#s(a),"assertNotAborted")});this.#s(a),a.state="active",this.#c(a,u.context),jt.info("Task browser instance launched",{runId:e.jobId,subjectId:n,chromeVersion:u.chromeVersion,extensionId:u.extensionId,readinessAttempts:u.readinessAttempts,readyAfterMs:u.readyAfterMs,launchDurationMs:Date.now()-d})}catch(u){let m=o(g=>{jt.error("Teardown after a failed task browser launch did not finish",{runId:e.jobId,subjectId:n,err:g instanceof Error?g.message:String(g)})},"logTeardownFailure");if(a.teardown===null)await this.#u(a,"launch_failure").catch(m);else if(await a.teardown.catch(m),a.context!==null&&a.context!==a.contextAtTeardown){let g=await bn(this.#e,{instanceKey:a.instanceKey,context:a.context,userDataDir:a.userDataDir,timeoutMs:2e4,trigger:"dispose_during_launch"});this.#p(a,g),g.failure!==null&&m(g.failure)}throw u}}async dispose(e,n){let r=this.#l.get(n);if(r!==void 0&&r.jobId===e){if(r.teardown!==null)return r.teardown;let s=r.state==="launching"?"dispose_during_launch":"dispose";return this.#u(r,s)}let i=this.#o.get(this.#m(e,n));return i!==void 0?this.#d(i):null}async disposeAll(e){let n=new Set;for(let s of this.#l.values())s.jobId===e&&n.add(s.subjectId);for(let s of this.#o.values())s.jobId===e&&n.add(s.subjectId);if(n.size===0)return;let i=(await Promise.allSettled([...n].map(s=>this.dispose(e,s)))).find(s=>s.status==="rejected");if(i!==void 0)throw i.reason}async probe(e){let n=this.#l.get(e);return n===void 0||n.state!=="active"||n.context===null?{ok:!1,observedAt:new Date().toISOString(),reason:"service_worker_absent",detail:`the runtime owns no running instance of task browser subject ${e}`}:Dr(n.context)}#s(e){if(e.teardown!==null)throw new fi(e.subjectId)}#c(e,n){let r=o(s=>{if(e.state!=="active"||e.teardown!==null)return;let l=this.#u(e,"instance_lost"),c={jobId:e.jobId,subjectId:e.subjectId,at:new Date().toISOString(),source:s};jt.warn("Task browser instance disappeared without a dispose",{...c}),l.catch(a=>{jt.error("Teardown after a lost task browser instance failed",{runId:e.jobId,subjectId:e.subjectId,err:a instanceof Error?a.message:String(a)})}).finally(()=>this.#i(c))},"report");n.on("close",()=>r("context_closed"));let i=n.browser();i!==null&&i.on("disconnected",()=>r("browser_disconnected"))}#u(e,n){e.state="tearing_down",e.contextAtTeardown=e.context;let r=(async()=>{try{let i=await bn(this.#e,{instanceKey:e.instanceKey,context:e.context,userDataDir:e.userDataDir,timeoutMs:2e4,trigger:n});if(jt.info("Task browser instance closed",{runId:e.jobId,subjectId:e.subjectId,trigger:n,disposeOutcome:i.result.outcome,instanceReleased:i.result.instanceReleased}),this.#p(e,i),i.failure!==null)throw i.failure;return i.result}finally{this.#l.get(e.subjectId)===e&&this.#l.delete(e.subjectId)}})();return e.teardown=r,r}#p(e,n){if(n.result.instanceReleased){this.#o.delete(e.instanceKey);return}this.#o.set(e.instanceKey,{instanceKey:e.instanceKey,jobId:e.jobId,subjectId:e.subjectId,result:n.result,killConfirmed:n.killConfirmed})}#m(e,n){return this.#a==="identity"?`${e}~${n}`:`${e}~launch~${n}`}#d(e){let n=Nr(this.#e,e);return this.#o.delete(e.instanceKey),n}};var $r=class{static{o(this,"IdentityInstances")}#e;constructor(e){this.#e=new Wt({...e,kind:"identity",onLost:o(({subjectId:n,...r})=>e.onLost({...r,identityId:n}),"onLost")})}identityIdsWithInstance(){return this.#e.subjectIdsWithInstance()}async start(e,n,r){await this.#e.start(e,n,r,{v:1,kind:"task_identity",runId:e.jobId,issuedAt:new Date().toISOString(),workflowId:e.workflowId,identityId:n})}dispose(e,n){return this.#e.dispose(e,n)}disposeAll(e){return this.#e.disposeAll(e)}probe(e){return this.#e.probe(e)}};var Ur=class{static{o(this,"TaskJobInstances")}identities;launches;constructor(e){this.identities=new $r(e),this.launches=new Wt({...e,kind:"launch",onLost:o(({subjectId:n,...r})=>e.onLaunchLost({...r,launchId:n}),"onLost")})}async startLaunch(e,n,r,i){let s=hi(e,n);await this.launches.start(s,r,i,{v:1,kind:"task_launch",runId:n,issuedAt:new Date().toISOString(),workflowId:s.workflowId,launchId:r})}async disposeAll(e){let n=await Promise.allSettled([this.identities.disposeAll(e),this.launches.disposeAll(e)]);for(let r of n)if(r.status==="rejected")throw r.reason}};function hi(t,e){if(t===null||t.runId!==e)throw new Error(`[runtime] job ${e} is not the running instance (running: ${t===null?"none":t.runId})`);if(t.identityInputs===null)throw new Error(`[runtime] job ${e} is not a task job; only a swarm job hosts task browser instances`);return t.identityInputs}o(hi,"taskInputs");import{mkdirSync as Cl,lstatSync as Rh,readdirSync as Th,readFileSync as xh,renameSync as Ih,rmSync as Oh,writeFileSync as Ah}from"node:fs";import{join as _n}from"node:path";var dt=w("instance-registry");function Mr(t){return typeof t=="string"&&t!==""}o(Mr,"isNonEmptyString");function Ch(t,e){if(typeof t!="object"||t===null)throw new Error(`[instance-registry] ${e} does not contain a JSON object.`);let n=t;if(n.v!==1)throw new Error(`[instance-registry] ${e} has version ${JSON.stringify(n.v)}, expected 1.`);if(!Mr(n.runId))throw new Error(`[instance-registry] ${e} has a missing or empty runId.`);if(!Mr(n.userDataDir))throw new Error(`[instance-registry] ${e} has a missing or empty userDataDir.`);if(!Mr(n.startedAt)||!Mr(n.deadlineAt))throw new Error(`[instance-registry] ${e} has a missing or empty timestamp field.`);if(typeof n.agentPid!="number"||!Number.isInteger(n.agentPid))throw new Error(`[instance-registry] ${e} has a non-integer agentPid.`);return{v:1,runId:n.runId,agentPid:n.agentPid,userDataDir:n.userDataDir,startedAt:n.startedAt,deadlineAt:n.deadlineAt}}o(Ch,"parseInstanceRecord");function Ph(t,e){let n=`${t}.tmp`;Ah(n,JSON.stringify(e,null,2),{encoding:"utf8",mode:384}),Ih(n,t)}o(Ph,"writeMarkerAtomically");var ut=class{static{o(this,"InstanceRegistry")}#e;#t;constructor(e){this.#t=e,this.#e=_n(e,sr)}get instancesRoot(){return this.#e}userDataDirFor(e){return _n(this.#e,e)}reserve(e,n){Cl(this.#e,{recursive:!0,mode:448});let r=this.userDataDirFor(e);try{Cl(r,{recursive:!1,mode:448})}catch(s){throw typeof s=="object"&&s!==null&&s.code==="EEXIST"?new We(e,r,s):s}let i=new Date().toISOString();try{_r(this.#t,e),Ph(_n(r,ar),{v:1,runId:e,agentPid:process.pid,userDataDir:r,startedAt:i,deadlineAt:n})}catch(s){try{this.release(e)}catch(l){dt.error("Failed to roll back the instance directory after a failed reservation",{runId:e,userDataDir:r,err:l instanceof Error?l.message:String(l)})}throw s}return dt.info("Instance reserved",{runId:e,userDataDir:r,deadlineAt:n}),{runId:e,userDataDir:r,startedAt:i,deadlineAt:n}}read(e){return this.#r(_n(this.userDataDirFor(e),ar))}release(e){let n=this.userDataDirFor(e);try{Rh(n)}catch(i){if(!P(i))throw i;ri(this.#t,e);return}let r=_r(this.#t,e);try{Oh(n,{recursive:!0,force:!0})}catch(i){throw r||_r(this.#t,e),i}ri(this.#t,e),dt.info("Instance released",{runId:e,userDataDir:n})}listRunIds(){let e;try{e=Th(this.#e,{withFileTypes:!0})}catch(n){if(typeof n=="object"&&n!==null&&n.code==="ENOENT")return[];throw n}return e.filter(n=>n.isDirectory()).map(n=>n.name)}async sweepOrphans(){let e=new Date().toISOString(),n=[];for(let r of this.listRunIds())n.push(await this.#n(r));return n.length>0?dt.warn("Startup sweep found leftover browser instances",{instancesRoot:this.#e,count:n.length,outcomes:n}):dt.info("Startup sweep found no leftover browser instances",{instancesRoot:this.#e}),{scannedAt:e,instancesRoot:this.#e,outcomes:n}}async#n(e){let n=this.userDataDirFor(e),r=_n(n,ar),i=null,s;try{i=this.#r(r),s="valid"}catch(c){s=(typeof c=="object"&&c!==null?c.code:null)==="ENOENT"?"missing":"unreadable",dt.warn("Leftover instance marker is unusable \u2014 killing by directory path anyway",{runId:e,userDataDir:n,marker:s,err:c instanceof Error?c.message:String(c)})}let l=await Bt(n);return dt.warn("Leftover browser instance swept",{runId:e,userDataDir:n,marker:s,kill:l}),this.release(e),{runId:e,userDataDir:n,marker:s,record:i,kill:l,removed:!0}}#r(e){let n=xh(e,"utf8");return Ch(JSON.parse(n),e)}};var Ie=w("playwright-execution-runtime"),gi=class extends Error{static{o(this,"LaunchAbortedError")}runId;constructor(e){super(`[runtime] launch of run ${e} was aborted: the instance was disposed while the browser was still coming up, so it was torn down instead of being published (CONTRACT-la \xA715 A3, A19.1).`),this.name="LaunchAbortedError",this.runId=e}},Gr=class{static{o(this,"PlaywrightExecutionRuntime")}#e;#t;#n;#r;#i;#a;#l;#o;#s=null;#c=null;#u=!1;#p=null;#m=null;constructor(e){cr(e.extensionDist),this.#e=e.extensionDist,this.#t=e.headfulOverride,this.#n=e.allowInsecureHttps,this.#r=e.disableBrowserSandbox,this.#i=e.onInstanceLost,this.#a=new ut(e.stateDir),this.#l=Al(e.extensionDist),this.#o=new Ur({registry:this.#a,extensionDist:e.extensionDist,allowInsecureHttps:e.allowInsecureHttps,disableBrowserSandbox:e.disableBrowserSandbox,onLost:e.onIdentityInstanceLost,onLaunchLost:e.onLaunchInstanceLost}),Ie.info("Execution runtime constructed",{stateDir:e.stateDir,instancesRoot:this.#a.instancesRoot,headfulOverride:e.headfulOverride,allowInsecureHttps:e.allowInsecureHttps,envFingerprint:this.#l})}getActiveInstance(){let e=this.#s;return e===null?null:{runId:e.runId,userDataDir:e.userDataDir,headful:e.headful,extensionId:e.extensionId,chromeVersion:e.chromeVersion,startedAt:e.startedAt,deadlineAt:e.deadlineAt}}async startIdentityInstance(e,n,r){await this.#o.identities.start(hi(this.#s,e),n,r)}async startLaunchInstance(e,n,r){await this.#o.startLaunch(this.#s,e,n,r)}disposeLaunchInstance(e,n){return this.#o.launches.dispose(e,n)}launchIdsWithInstance(){return this.#o.launches.subjectIdsWithInstance()}async disposeIdentityInstance(e,n){return this.#o.identities.dispose(e,n)}async probeIdentityInstance(e){return this.#o.identities.probe(e)}identityIdsWithInstance(){return this.#o.identities.identityIdsWithInstance()}async sweepOrphanInstances(){return this.#a.sweepOrphans()}async probePlaybackSession(){let e=this.#s;return e===null?{ok:!1,observedAt:new Date().toISOString(),reason:"service_worker_absent",detail:"the runtime owns no browser instance"}:Dr(e.context)}async startRun(e){let n=this.#s;if(n!==null)throw new Cr(e.runId,n.runId);let r=Date.now(),i=new Date(r+e.maxRunDurationSec*1e3).toISOString(),s=this.#g(e),l=Nh(e,s,i),c=await ae(e.runId,"instance_reserve",()=>this.#a.reserve(e.runId,i));this.#m?.runId===e.runId&&(this.#m=null);let a={runId:e.runId,userDataDir:c.userDataDir,context:null,disposeRequested:!1};this.#c=a;let d=e.command.kind==="swarm"||e.command.kind==="conversation";Ie.info("Launching browser for run",{runId:e.runId,headful:s,requestHeadful:e.headful,headfulOverride:this.#t,keepBackgroundWindowsRendering:d,userDataDir:c.userDataDir,maxRunDurationSec:e.maxRunDurationSec,deadlineAt:i,envFingerprint:this.#l});let u=null;try{let m=await Pr({runId:e.runId,userDataDir:c.userDataDir,extensionDist:this.#e,headful:s,allowInsecureHttps:this.#n,disableBrowserSandbox:this.#r,keepBackgroundWindowsRendering:d,extensionSession:e.extensionSession,command:e.command,entryUrl:e.entryUrl,onContext:o(E=>{u=E,a.context=E},"onContext"),assertNotAborted:o(()=>this.#f(a),"assertNotAborted")}),g={runId:e.runId,context:m.context,userDataDir:c.userDataDir,headful:s,extensionId:m.extensionId,chromeVersion:m.chromeVersion,startedAt:c.startedAt,deadlineAt:i,identityInputs:l};this.#f(a),this.#y(g),this.#s=g,this.#c===a&&(this.#c=null),Ie.info("Run launched",{runId:e.runId,chromeVersion:m.chromeVersion,extensionId:m.extensionId,readinessAttempts:m.readinessAttempts,readyAfterMs:m.readyAfterMs,launchDurationMs:Date.now()-r})}catch(m){throw this.#c===a&&(this.#c=null),await this.#h({runId:e.runId,context:u,userDataDir:c.userDataDir,timeoutMs:2e4,trigger:a.disposeRequested?"dispose_during_launch":"launch_failure"}),m}finally{this.#c===a&&(this.#c=null)}}async cancelRun(e){await this.disposeRun(e)}async disposeRun(e,n=2e4){let[r,i]=await Promise.allSettled([this.#o.disposeAll(e),this.#d(e,n)]);if(i.status==="rejected")throw i.reason;if(r.status==="rejected")throw r.reason;return i.value}async#d(e,n){let r=this.#p;if(r!==null&&r.runId===e)return Ie.info("Dispose requested for a lost instance \u2014 joining the teardown already running",{runId:e}),r.promise;let i=this.#c;if(i!==null&&i.runId===e)return i.disposeRequested=!0,Ie.warn("Dispose requested for a run that is still launching \u2014 aborting the launch",{runId:e,userDataDir:i.userDataDir,contextPresent:i.context!==null}),this.#h({runId:e,context:i.context,userDataDir:i.userDataDir,timeoutMs:n,trigger:"dispose_during_launch"});let s=this.#s;return s===null||s.runId!==e?this.#w(e):(this.#s=null,this.#h({runId:e,context:s.context,userDataDir:s.userDataDir,timeoutMs:n,trigger:"dispose"}))}#g(e){return e.headful||this.#t}#f(e){if(e.disposeRequested)throw new gi(e.runId)}#y(e){let n=o(i=>{if(this.#u||this.#s?.runId!==e.runId)return;this.#s=null;let s=this.#h({runId:e.runId,context:e.context,userDataDir:e.userDataDir,timeoutMs:2e4,trigger:"instance_lost"});this.#p={runId:e.runId,promise:s},s.catch(c=>{Ie.error("Teardown after a lost browser instance failed",{runId:e.runId,userDataDir:e.userDataDir,err:c instanceof Error?c.message:String(c)})}).finally(()=>{this.#p?.promise===s&&(this.#p=null)});let l={runId:e.runId,at:new Date().toISOString(),source:i};Ie.error("Browser instance disappeared without a dispose",{...l}),this.#i(l)},"report");e.context.on("close",()=>n("context_closed"));let r=e.context.browser();r!==null&&r.on("disconnected",()=>n("browser_disconnected"))}#w(e){let n=this.#m;if(n===null||n.runId!==e)return Ie.info("Dispose requested for a run this runtime does not own \u2014 no-op",{requestedRunId:e,activeRunId:this.#s===null?null:this.#s.runId,disposeOutcome:"closed"}),{runId:e,outcome:"closed",kill:null,instanceReleased:!1,durationMs:0};if(n.result.instanceReleased)return Ie.info("Dispose repeated for a run already torn down \u2014 replaying its outcome",{runId:e,disposeOutcome:n.result.outcome,instanceReleased:!0}),n.result;let r=Nr(this.#a,{instanceKey:e,result:n.result,killConfirmed:n.killConfirmed});return this.#m={runId:e,result:r,killConfirmed:!0},r}async#h(e){this.#u=!0;try{let n=await bn(this.#a,{instanceKey:e.runId,context:e.context,userDataDir:e.userDataDir,timeoutMs:e.timeoutMs,trigger:e.trigger});if(this.#m={runId:e.runId,result:n.result,killConfirmed:n.killConfirmed},n.failure!==null)throw n.failure;return n.result}finally{this.#u=!1}}};function Nh(t,e,n){if(t.command.kind!=="swarm")return null;if(t.entryUrl===null)throw new Error(`[runtime] swarm job ${t.runId} was handed to the runtime without its entry address, which its claim member requires`);return{jobId:t.runId,workflowId:t.command.workflowId,entryUrl:t.entryUrl,headful:e,deadlineAt:n}}o(Nh,"identityInputsOf");import{setTimeout as Lh}from"node:timers/promises";var He=w("supervisor-identity");function yi(t){if(t.initialToken!==void 0)return{source:"env_token",agentToken:t.initialToken};let e=L(t.stateDir);return e===null?null:(Bh(e.serverUrl,t.serverUrl),{source:"state_file",agentToken:e.agentToken,agentId:e.agentId})}o(yi,"selectExistingCredential");async function Fr(t){let{config:e}=t,n=yi(e);if(n?.source==="env_token")return Dh(e,n.agentToken);if(n?.source==="state_file")return He.info("Agent identity loaded from the state file",{agentId:n.agentId}),{agentToken:n.agentToken,agentId:n.agentId,pollWaitSec:void 0,source:"state_file"};if(e.enrollmentCode!==void 0)return Uh(t,e.enrollmentCode);throw new p(`[progon-agent] This machine has no agent identity, so the daemon cannot start.
|
|
82
|
+
For a dev or E2E stand you can instead set PROGON_AGENT_EXTENSION_DIST to an already agent-mode dist, which bypasses the bundled copy entirely (CONTRACT-la \xA78).`}o(oi,"bundledMissingMessage");function Uf(t){let{stateDir:e,agentId:n}=t;if(n==="")throw new Error(`[extension-dist] agentId is required: ${li} carries it (CONTRACT-la \xA71 D-C) and this module does not invent identity.`);let r=t.sourceDir??Df(),i=Ft(e,ai),s=Ft(e,`${si}${process.pid}`);return xf(e,{recursive:!0,mode:448}),tl(e),Gf(e),ii(s,{recursive:!0,force:!0}),Tf(r,s,{recursive:!0}),Rf(s,448),Mf(s,n),ii(i,{recursive:!0,force:!0}),Of(s,i),Rr.info("Agent-mode extension dist prepared",{extensionDist:i,sourceDir:r,agentId:n,protocolVersion:1}),i}o(Uf,"prepareAgentExtensionDist");function Mf(t,e){let n={agentMode:!0,agentId:e,protocolVersion:1};Af(Ft(t,li),JSON.stringify(n,null,2)+`
|
|
83
|
+
`,"utf8")}o(Mf,"writeAgentManifest");function Gf(t){let e;try{e=If(t,{withFileTypes:!0})}catch(n){if(typeof n=="object"&&n!==null&&n.code==="ENOENT")return;throw n}for(let n of e){if(!sl(n.name))continue;let r=Ft(t,n.name);try{ii(r,{recursive:!0,force:!0}),Rr.warn("Removed a leftover extension-dist staging directory",{leftover:r})}catch(i){Rr.error("Failed to remove a leftover extension-dist staging directory",{leftover:r,err:i instanceof Error?i.message:String(i)})}}}o(Gf,"removeLeftoverStagingDirs");function Tr(t){return t.overridePath!==void 0?(Rr.info("Using the PROGON_AGENT_EXTENSION_DIST override as built",{extensionDist:t.overridePath}),t.overridePath):Uf({stateDir:t.stateDir,agentId:ci(t.agentId)})}o(Tr,"resolveExtensionDist");function ci(t){if(t===null)throw new p(`[extension-dist] Cannot prepare the agent-mode extension dist: this daemon authenticated with PROGON_AGENT_TOKEN, which carries no agentId, and ${li} must name the agent the browser reports as (CONTRACT-la \xA71 D-C).
|
|
84
|
+
Either enroll the agent ('progon-agent enroll <code>'), which persists the identity the server issued, or set PROGON_AGENT_EXTENSION_DIST to a dist that is already in agent mode (dev/E2E path, \xA78).`);return t}o(ci,"requireManifestAgentId");function ge(t,e=Math.random){if(t<0)throw new Error(`[backoff] attempt must be >= 0, got ${t}. Pass 0 for the first reconnect after a disconnect.`);let n=Math.min(6e4,1e3*Math.pow(2,Math.min(t,26)));return Math.floor(e()*n)}o(ge,"computeBackoffDelayMs");function Be(t){let e=Ff(t.error);return e!==null?{retry:!1,reason:e}:{retry:!0,delayMs:ge(t.attempt,t.rng)}}o(Be,"decideGatewayRetry");function Ff(t){if(t instanceof T)return"terminal_signal";if(t instanceof fe)return"contract_breach";if(t instanceof ee)return"upgrade_required";if(t instanceof O)return"semantic_refusal";if(t.operation==="claim"||t.operation==="token_rotate")return"one_shot_operation";if(t instanceof Z||t instanceof Ot)return null;if(t instanceof x)return t.status===429?"rate_limited":t.status>=500?null:"semantic_refusal";throw new Error(`[backoff-policy] No retry row for ${t.name} on operation '${t.operation}'. A new GatewayError subclass was added without extending the decision table in src/gateway/backoff-policy.ts.`)}o(Ff,"classifyFailure");import{mkdtempSync as th,rmSync as nh}from"node:fs";import{tmpdir as rh}from"node:os";import{join as oh}from"node:path";import{execFile as jf}from"node:child_process";import{promisify as Wf}from"node:util";import{setTimeout as ul}from"node:timers/promises";var xr=Wf(jf),Ir={timeout:5e3};function pl(t){if(typeof t!="object"||t===null)return null;let e=t;return typeof e.code!="number"?null:{code:e.code,stdout:typeof e.stdout=="string"?e.stdout:"",stderr:typeof e.stderr=="string"?e.stderr:""}}o(pl,"asExecFailure");function Hf(t){let e=[];for(let n of t.split(`
|
|
85
|
+
`)){let r=n.trim();if(r==="")continue;let i=Number(r);!Number.isInteger(i)||i===process.pid||e.push(i)}return e}o(Hf,"parsePidLines");var di="--user-data-dir=",Jf=new Set([" "," ",'"',"'"]),Kf=new Set([" "," ",'"',"'"]);function Vf(t){return t.replace(/[\\^$.|?*+()[\]{}]/g,"\\$&")}o(Vf,"escapeEre");function qf(t){return`(^|[[:space:]'"])${Vf(`${di}${t}`)}([[:space:]'"]|$)`}o(qf,"buildAnchorPattern");function Yf(t,e){let n=t.toLowerCase(),r=`${di}${e}`.toLowerCase();for(let i=n.indexOf(r);i!==-1;i=n.indexOf(r,i+1)){let s=i===0?void 0:n[i-1],l=n[i+r.length],c=s===void 0||Jf.has(s),a=l===void 0||Kf.has(l);if(c&&a)return!0}return!1}o(Yf,"matchesAnchor");async function Xf(t){try{let{stdout:e}=await xr("pgrep",["-f",qf(t)],Ir);return Hf(e)}catch(e){let n=pl(e);if(n!==null&&n.code===1&&n.stdout.trim()==="")return[];throw e}}o(Xf,"discoverPosix");async function ll(t){let n=`Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Where-Object { $_.ProcessId -ne $PID -and $_.CommandLine -and $_.CommandLine.Contains('${`${di}${t}`.replace(/'/g,"''")}') } | ForEach-Object { "$($_.ProcessId)\`t$($_.CommandLine)" }`,{stdout:r}=await xr("powershell.exe",["-NoProfile","-NonInteractive","-Command",n],Ir),i=[];for(let s of r.split(`
|
|
86
|
+
`)){let l=s.indexOf(" ");if(l===-1)continue;let c=Number(s.slice(0,l).trim()),a=s.slice(l+1);!Number.isInteger(c)||c===process.pid||Yf(a,t)&&i.push(c)}return i}o(ll,"discoverWin32");async function cl(){let{stdout:t}=await xr("ps",["-A","-o","pid=,ppid=,pgid="],Ir),e=[];for(let n of t.split(`
|
|
87
|
+
`)){let r=n.trim().split(/\s+/);if(r.length<3)continue;let[i,s,l]=r,c=Number(i),a=Number(s),d=Number(l);!Number.isInteger(c)||!Number.isInteger(a)||!Number.isInteger(d)||e.push({pid:c,ppid:a,pgid:d})}return e}o(cl,"readProcessTable");function zf(t,e){let n=new Map;for(let a of t){let d=n.get(a.ppid);d===void 0?n.set(a.ppid,[a.pid]):d.push(a.pid)}let r=new Set(e),i=[...e];for(let a=i.pop();a!==void 0;a=i.pop()){let d=n.get(a);if(d!==void 0)for(let u of d)r.has(u)||(r.add(u),i.push(u))}let s=t.find(a=>a.pid===process.pid),l=s===void 0?null:s.pgid,c=new Set;for(let a of t)r.has(a.pid)&&(a.pgid<=0||l!==null&&a.pgid===l||c.add(a.pgid));return r.delete(process.pid),{members:[...r],groups:[...c]}}o(zf,"expandTree");function Qf(t){try{return process.kill(t,"SIGKILL"),"signalled"}catch(e){if(typeof e=="object"&&e!==null&&e.code==="ESRCH")return"already_gone";throw e}}o(Qf,"sigkill");async function Bt(t){return process.platform==="win32"?eh(t):Zf(t)}o(Bt,"killProcessTree");async function Zf(t){let e=await Xf(t);if(e.length===0)return{platform:process.platform,userDataDir:t,discoveredPids:[],signalledPids:[],survivorPids:[]};let n=await cl(),{members:r,groups:i}=zf(n,e),s=[];for(let a of r)Qf(a)==="signalled"&&s.push(a);for(let a of i)try{process.kill(-a,"SIGKILL")}catch(d){if(typeof d!="object"||d===null||d.code!=="ESRCH")throw d}await ul(500);let l=await cl(),c=new Set(l.map(a=>a.pid));return{platform:process.platform,userDataDir:t,discoveredPids:e,signalledPids:s,survivorPids:r.filter(a=>c.has(a))}}o(Zf,"killProcessTreePosix");async function eh(t){let e=await ll(t),n=[];for(let i of e)try{await xr("taskkill.exe",["/T","/F","/PID",String(i)],Ir),n.push(i)}catch(s){let l=pl(s);if(l===null||l.code!==128)throw s}await ul(500);let r=await ll(t);return{platform:"win32",userDataDir:t,discoveredPids:e,signalledPids:n,survivorPids:r}}o(eh,"killProcessTreeWin32");var ml=w("browser-sandbox-probe"),ih=[" - Ubuntu 23.10 or newer restricts user namespaces with AppArmor. Give Chromium an AppArmor"," profile: https://chromium.googlesource.com/chromium/src/+/main/docs/security/apparmor-userns-restrictions.md"," - In a container, Docker's default seccomp profile blocks the namespaces Chromium needs. Use"," a seccomp profile that allows them, and run as a user other than root."," - Chromium refuses to use its sandbox as root. Run the agent as an ordinary user."," - If you accept the risk on this machine, set PROGON_AGENT_DISABLE_BROWSER_SANDBOX=true. A"," renderer exploit on any page a run opens then gets this user's rights."].join(`
|
|
88
|
+
`);async function Or(){let t=Date.now(),e=th(oh(rh(),"progon-agent-sandbox-probe-")),n=null;try{n=await ya(e),await(await n.newPage()).evaluate("1")}catch(r){throw new p(`[browser-sandbox] Chromium could not start with its sandbox on this machine, so the agent is not starting.
|
|
89
|
+
${ih}
|
|
90
|
+
Chromium's output: ${r instanceof Error?r.message:String(r)}`,{cause:r})}finally{await sh(n,e)}ml.info("Chromium runs with its sandbox on this machine",{durationMs:Date.now()-t})}o(Or,"probeBrowserSandbox");async function sh(t,e){try{t!==null&&(await cr(t,2e4)).settled==="closed"||await Bt(e),nh(e,{recursive:!0,force:!0})}catch(n){ml.error("Could not clean up the sandbox probe: a browser or its profile may be left",{userDataDir:e,err:n instanceof Error?n.message:String(n)})}}o(sh,"closeProbeBrowser");var ah=w("run-browser-preparation");async function Ar(t){if(await kt({stdio:"pipe",signal:t.signal}),t.signal?.throwIfAborted(),t.disableBrowserSandbox){ah.warn("PROGON_AGENT_DISABLE_BROWSER_SANDBOX is set: Chromium runs without its sandbox, so a renderer exploit on any page a run opens gets this user's rights");return}await Or()}o(Ar,"prepareRunBrowser");var lh=w("worker-evaluate"),ui=class extends Error{static{o(this,"EvaluateDeadlineError")}operation;timeoutMs;constructor(e,n){super(`[runtime] ${e}: the extension service worker did not answer worker.evaluate within ${n}ms \u2014 the worker is wedged or gone`),this.name="EvaluateDeadlineError",this.operation=e,this.timeoutMs=n}};async function Ie(t){let e=t.evaluate(),n=!1;e.catch(s=>{n&&lh.warn("An abandoned worker.evaluate rejected after its deadline had passed",{operation:t.operation,timeoutMs:t.timeoutMs,err:s instanceof Error?s.message:String(s)})});let r,i=new Promise((s,l)=>{r=setTimeout(()=>{n=!0,l(new ui(t.operation,t.timeoutMs))},t.timeoutMs)});try{return await Promise.race([e,i])}finally{r!==void 0&&clearTimeout(r)}}o(Ie,"evaluateWithDeadline");var fl={name:"progon-session",version:1,store:"tokens"},hl="accessToken",gl="refreshToken";async function wl(t,e){await Ie({operation:"write the run session into the token database",timeoutMs:1e4,evaluate:o(()=>t.evaluate(([r,i,s,l,c])=>new Promise((a,d)=>{let u=indexedDB.open(r.name,r.version);u.onupgradeneeded=()=>{u.result.createObjectStore(r.store)},u.onerror=()=>d(new Error("the token database did not open")),u.onsuccess=()=>{let m=u.result,g=m.transaction(r.store,"readwrite"),E=g.objectStore(r.store);E.put(l,i),E.put(c,s),g.oncomplete=()=>{m.close(),a()},g.onabort=()=>{m.close(),d(new Error("the token write was aborted"))}}}),[fl,hl,gl,e.accessToken,e.refreshToken]),"evaluate")});let n=await Ie({operation:"read the run session back out of the token database",timeoutMs:1e4,evaluate:o(()=>t.evaluate(([r,i,s])=>new Promise((l,c)=>{let a=indexedDB.open(r.name,r.version);a.onerror=()=>c(new Error("the token database did not open")),a.onsuccess=()=>{let d=a.result,u=d.transaction(r.store,"readonly"),m=u.objectStore(r.store),g=m.get(i),E=m.get(s);u.oncomplete=()=>{d.close(),l({accessTokenLength:typeof g.result=="string"?g.result.length:null,refreshTokenLength:typeof E.result=="string"?E.result.length:null})},u.onabort=()=>{d.close(),c(new Error("the token read was aborted"))}}}),[fl,hl,gl]),"evaluate")});if(n.accessTokenLength!==e.accessToken.length||n.refreshTokenLength!==e.refreshToken.length)throw new Error(`run-session read-back mismatch: the token database holds accessToken(len=${String(n.accessTokenLength)}), refreshToken(len=${String(n.refreshTokenLength)}) but ${e.accessToken.length}/${e.refreshToken.length} were written`);return n}o(wl,"seedRunSession");function yl(t){return JSON.stringify(Object.keys(t).sort().map(e=>[e,t[e]]))}o(yl,"canonicalise");async function Sl(t,e){await Ie({operation:`write the command envelope to chrome.storage.session['${Ze}']`,timeoutMs:1e4,evaluate:o(()=>t.evaluate(([l,c])=>new Promise(a=>chrome.storage.session.set({[l]:c},()=>chrome.storage.local.set({[l]:!0},()=>a()))),[Ze,e]),"evaluate")});let n=await Ie({operation:"read the command envelope back out of chrome.storage.session",timeoutMs:1e4,evaluate:o(()=>t.evaluate(l=>new Promise(c=>chrome.storage.session.get([l],a=>{let d=a[l];c(d===void 0?null:d)})),Ze),"evaluate")});if(typeof n!="object"||n===null)throw new Error(`command envelope read-back returned ${JSON.stringify(n)} \u2014 chrome.storage.session['${Ze}'] does not hold the envelope`);let r=yl({...e}),i=yl(n);if(r!==i)throw new Error(`command envelope read-back mismatch: wrote ${r}, read ${i}`);let s=await Ie({operation:"read the command marker back out of chrome.storage.local",timeoutMs:1e4,evaluate:o(()=>t.evaluate(l=>new Promise(c=>chrome.storage.local.get([l],a=>{let d=a[l];c(d===void 0?null:d)})),Ze),"evaluate")});if(s!==!0)throw new Error(`command marker read-back returned ${JSON.stringify(s)} \u2014 chrome.storage.local['${Ze}'] does not hold it`)}o(Sl,"seedCommandEnvelope");async function dh(t,e,n){let r=await Ie({operation:`read chrome.storage.session['${Vn}']`,timeoutMs:n,evaluate:o(()=>t.evaluate(s=>new Promise(l=>chrome.storage.session.get([s],c=>{let a=c[s];l(a===void 0?null:a)})),Vn),"evaluate")});if(r===null)return{kind:"absent"};let i=bs.safeParse(r);return i.success?i.data.runId!==e?{kind:"other_run",detail:`the ack under that key belongs to run ${i.data.runId}`}:{kind:"ack",ack:i.data}:{kind:"invalid",detail:`the value under that key failed agentCommandAckSchema: ${String(i.error)}`}}o(dh,"pollCommandAck");async function El(t,e,n){let r=Date.now()+n,i="no ack was written";for(;;){let s=r-Date.now();if(s<=0)throw new Error(`no command ack for run ${e} within ${n}ms \u2014 ${i}. chrome.storage.session['${Vn}'] is the only success signal (CONTRACT-la \xA75.4).`);let l=t.serviceWorkers()[0];if(l===void 0)i="the context exposed no service worker while polling (evicted, restarting)";else{let c;try{c=await dh(l,e,s)}catch(a){i=`the last poll failed: ${a instanceof Error?a.message:String(a)}`,c={kind:"invalid",detail:i}}if(c.kind==="ack")return c.ack;c.kind!=="absent"&&(i=c.detail)}await new Promise(c=>setTimeout(c,250))}}o(El,"waitForCommandAck");async function vl(t,e){let r=t.serviceWorkers()[0];return r!==void 0?r:t.waitForEvent("serviceworker",{timeout:e})}o(vl,"waitForServiceWorker");async function bl(t,e){let n,r=new Promise((i,s)=>{n=setTimeout(()=>s(new Error(`chrome.runtime.id did not resolve within ${e}ms \u2014 the extension's service worker is not executing`)),e)});try{let i=await Promise.race([t.evaluate(()=>chrome.runtime.id),r]);if(typeof i!="string"||i==="")throw new Error(`chrome.runtime.id returned ${JSON.stringify(i)} \u2014 expected a non-empty extension id`);return i}finally{n!==void 0&&clearTimeout(n)}}o(bl,"readRuntimeId");function Cr(t,e){let n=t-Date.now();if(n<=0)throw new Error(`the ${45e3}ms extension readiness budget was already spent before ${e} could run`);return n}o(Cr,"remainingBudgetMs");async function kl(t){let e=Date.now(),n=e+45e3,r=n-5e3,i=await vl(t,Math.min(5e3,Cr(r,"the service-worker target wait")));try{let s=await bl(i,Cr(r,"the first readiness evaluate"));return{worker:i,extensionId:s,serviceWorkerUrl:i.url(),attempts:1,readyAfterMs:Date.now()-e}}catch(s){let l=await t.newPage();try{let c=await vl(t,Math.min(5e3,Cr(n,"the retry service-worker target wait"))),a=await bl(c,Cr(n,"the retry readiness evaluate"));return{worker:c,extensionId:a,serviceWorkerUrl:c.url(),attempts:2,readyAfterMs:Date.now()-e}}catch(c){let a=s instanceof Error?s.message:String(s),d=c instanceof Error?c.message:String(c);throw new Error(`extension readiness probe failed on both exp5 lanes. Direct attempt: ${a}. Page-open retry: ${d}.`,{cause:c})}finally{await l.close()}}}o(kl,"probeExtensionReadiness");var je=class extends Error{static{o(this,"RuntimeLaunchError")}runId;stage;failReason="launch_error";constructor(e,n,r,i){super(`[runtime] launch failed at stage ${n} for run ${e}: ${r}`,{cause:i}),this.name="RuntimeLaunchError",this.runId=e,this.stage=n}};function mi(t){let e=new Set,n=t;for(;n instanceof Error&&!e.has(n)&&(e.add(n),n.cause!==void 0);)n=n.cause;return n instanceof Error?n.message:String(n)}o(mi,"deepestCauseMessage");var uh=/^\s*(?:- )?\[pid=\d+\]\[err\] ?(.*)$/;function Rl(t){let e=[];for(let n of t.split(`
|
|
91
|
+
`)){let r=uh.exec(n)?.[1];r!==void 0&&r!==""&&e.push(r)}return e.length===0?null:e.join(" | ")}o(Rl,"browserStderrOf");var ph=new Set(["ERR_CONNECTION_REFUSED","ERR_CONNECTION_RESET","ERR_CONNECTION_CLOSED","ERR_CONNECTION_FAILED","ERR_CONNECTION_TIMED_OUT","ERR_ADDRESS_UNREACHABLE","ERR_TIMED_OUT"]),mh=/\bnet::(ERR_[A-Z0-9_]+)\b/;function Tl(t){if(fh(t))return"timeout";let e=mh.exec(mi(t))?.[1];return e===void 0?"other":e==="ERR_NAME_NOT_RESOLVED"?"name_not_resolved":ph.has(e)?"unreachable":e.startsWith("ERR_CERT_")?"certificate":"other"}o(Tl,"entryFailureOf");function fh(t){let e=new Set,n=t;for(;n instanceof Error&&!e.has(n);){if(n instanceof pa.TimeoutError)return!0;e.add(n),n=n.cause}return!1}o(fh,"causeChainHasTimeout");var We=class extends Error{static{o(this,"InstanceAlreadyRegisteredError")}runId;userDataDir;constructor(e,n,r){super(`[runtime] refusing to launch run ${e}: instance directory already exists at ${n}. Either this run is already live, or a previous daemon left it behind (the startup sweep clears leftovers \u2014 CONTRACT-la \xA715 A3, gate G-3).`,{cause:r}),this.name="InstanceAlreadyRegisteredError",this.runId=e,this.userDataDir=n}},jt=class extends Error{static{o(this,"RuntimeBusyError")}requestedRunId;activeRunId;constructor(e,n){super(`[runtime] refusing to launch run ${e}: this runtime already owns the browser instance for run ${n}. An agent runs at most one run at a time (CONTRACT-la \xA73.1, \xA715 A3).`),this.name="RuntimeBusyError",this.requestedRunId=e,this.activeRunId=n}};var re=w("browser-instance");async function Pr(t){let e=await ae(t.runId,"browser_launch",()=>ga({userDataDir:t.userDataDir,extensionDist:t.extensionDist,headful:t.headful,allowInsecureHttps:t.allowInsecureHttps,disableBrowserSandbox:t.disableBrowserSandbox,keepBackgroundWindowsRendering:t.keepBackgroundWindowsRendering}));t.onContext(e),t.assertNotAborted();let n=await ae(t.runId,"browser_version",()=>Sa(e)),r=await ae(t.runId,"readiness_probe",()=>kl(e));await gh(t,r.worker);let{entryUrl:i}=t;return i===null?await ae(t.runId,"empty_tab",()=>Eh(e)):await ae(t.runId,"entry_navigation",()=>Sh(e,i)),await yh(t,e),{context:e,chromeVersion:n,extensionId:r.extensionId,readinessAttempts:r.attempts,readyAfterMs:r.readyAfterMs}}o(Pr,"bringUpBrowser");async function gh(t,e){let n=await ae(t.runId,"token_seed",()=>wl(e,t.extensionSession));re.info("Run session seeded into the browser profile",{runId:t.runId,userDataDir:t.userDataDir,accessTokenLength:n.accessTokenLength,refreshTokenLength:n.refreshTokenLength}),await ae(t.runId,"command_seed",()=>Sl(e,t.command)),re.info("Command envelope seeded",{runId:t.runId,userDataDir:t.userDataDir,command:t.command})}o(gh,"seed");async function yh(t,e){let n=await ae(t.runId,"command_ack",()=>El(e,t.runId,15e3));if(n.outcome==="rejected")throw new je(t.runId,"command_ack",`the extension refused the command envelope: ${n.reason}`);re.info("Command envelope dispatched by the extension",{runId:t.runId,userDataDir:t.userDataDir,kind:t.command.kind})}o(yh,"awaitDispatchAck");async function _n(t,e){let n=Date.now(),r="closed",i=null,s=null;if(e.context!==null){let g=await cr(e.context,e.timeoutMs);g.settled==="closed"?r="closed":g.settled==="timeout"?(r="timeout-force-killed",re.error("context.close() did not settle before the deadline \u2014 force-killing",{runId:e.instanceKey,timeoutMs:e.timeoutMs,userDataDir:e.userDataDir})):(r="close-failed-force-killed",re.error("context.close() rejected \u2014 force-killing",{runId:e.instanceKey,userDataDir:e.userDataDir,err:g.error instanceof Error?g.error.message:String(g.error)}))}if(r!=="closed"||e.trigger==="instance_lost"||e.trigger==="dispose_during_launch")try{i=await Bt(e.userDataDir)}catch(g){s=g,re.error("Force-kill of the run process tree failed",{runId:e.instanceKey,userDataDir:e.userDataDir,trigger:e.trigger,disposeOutcome:r,err:g instanceof Error?g.message:String(g)})}let c=s===null&&(i===null||i.survivorPids.length===0),a=null,d=!1;if(c)try{t.release(e.instanceKey),d=!0}catch(g){a=g,re.error("Failed to remove the instance directory after teardown",{runId:e.instanceKey,userDataDir:e.userDataDir,err:g instanceof Error?g.message:String(g)})}else re.error("Instance directory KEPT \u2014 the force-kill is unconfirmed and the startup sweep must still be able to find this tree",{runId:e.instanceKey,userDataDir:e.userDataDir,disposeOutcome:r,killFailed:s!==null,survivorPids:i===null?null:i.survivorPids});let u={runId:e.instanceKey,outcome:r,kill:i,instanceReleased:d,durationMs:Date.now()-n},m={runId:u.runId,disposeOutcome:u.outcome,trigger:e.trigger,contextPresent:e.context!==null,kill:u.kill,killFailed:s!==null,instanceReleased:u.instanceReleased,durationMs:u.durationMs};return s!==null||a!==null?re.error("Instance disposed with a failed cleanup step",m):re.info("Instance disposed",m),{result:u,killConfirmed:c,failure:wh(e,i,s,a)}}o(_n,"tearDownBrowser");function Nr(t,e){let{instanceKey:n}=e;if(!e.killConfirmed)throw re.error("Dispose repeated for an instance whose force-kill was never confirmed \u2014 the instance directory stays for the startup sweep",{runId:n,disposeOutcome:e.result.outcome,kill:e.result.kill,instanceReleased:!1}),new Error(`[runtime] the instance directory for ${n} is deliberately retained: the force-kill of its process tree was never confirmed, and this runtime does not retry it. The startup sweep (CONTRACT-la \xA715 A3 rule 2) is the next eraser.`);let r=Date.now();re.warn("Dispose repeated for an instance whose directory survived \u2014 retrying",{runId:n,disposeOutcome:e.result.outcome}),t.release(n);let i={...e.result,instanceReleased:!0,durationMs:Date.now()-r};return re.info("Instance released on a repeated dispose",{runId:n,disposeOutcome:i.outcome,instanceReleased:!0,durationMs:i.durationMs}),i}o(Nr,"retryRetainedRelease");function wh(t,e,n,r){return r!==null?xl(r):n!==null?xl(n):e!==null&&e.survivorPids.length>0?new Error(`[runtime] force-kill for run ${t.instanceKey} left ${e.survivorPids.length} process(es) alive after the settle delay (${e.survivorPids.join(", ")}). The instance directory ${t.userDataDir} is kept so the startup sweep can re-discover them (CONTRACT-la \xA715 A3 rule 2).`):null}o(wh,"teardownFailure");function xl(t){return t instanceof Error?t:new Error(String(t))}o(xl,"asError");async function ae(t,e,n){try{return await n()}catch(r){throw r instanceof je||r instanceof We?r:new je(t,e,r instanceof Error?r.message:String(r),r)}}o(ae,"stage");async function Sh(t,e){await(await Il(t)).goto(e,{waitUntil:"domcontentloaded"})}o(Sh,"navigateToEntry");async function Eh(t){await Il(t)}o(Eh,"prepareEmptyTab");async function Il(t){let e=t.pages()[0],n=e===void 0?await t.newPage():e;return await wa(t,n),n}o(Il,"sizedFirstPage");import Lr from"node:os";import{createRequire as vh}from"node:module";var Ol=vh(import.meta.url);function bh(){let t=Ol.resolve("playwright-core/package.json"),e=Ol(t);if(typeof e!="object"||e===null)throw new Error(`[runtime] ${t} did not parse into an object.`);let n=e.version;if(typeof n!="string"||n==="")throw new Error(`[runtime] ${t} declares no version string.`);return n}o(bh,"readPlaywrightCoreVersion");function Al(t){return{node:process.version,platform:`${Lr.platform()} ${Lr.release()} ${Lr.arch()}`,cpus:Lr.cpus().length,playwrightCore:bh(),chromiumExecutable:rt.executablePath(),channel:wn,extensionDist:t}}o(Al,"buildEnvFingerprint");async function Dr(t){let e=new Date().toISOString(),r=t.serviceWorkers()[0];if(r===void 0)return{ok:!1,observedAt:e,reason:"service_worker_absent",detail:"the browser context exposes no service worker \u2014 the extension is not running"};try{let i=await Ie({operation:"read playback, job pulse and identity detach from chrome.storage.session",timeoutMs:1e4,evaluate:o(()=>r.evaluate(async s=>{let l=await new Promise(g=>chrome.storage.session.get(["tabStates",s,"agent:detached-identity"],g)),c=l.tabStates,a=typeof c!="object"||c===null?[]:Object.entries(c).map(([g,E])=>{let S=typeof E=="object"&&E!==null?E.playback:null;if(typeof S!="object"||S===null)return{tabId:g,playback:null};let b=S;return{tabId:g,playback:{runId:typeof b.runId=="string"?b.runId:null,status:typeof b.status=="string"?b.status:null,currentStepIndex:typeof b.currentStepIndex=="number"?b.currentStepIndex:null}}}),d=l[s],u=typeof d!="object"||d===null?null:(()=>{let g=d;return{agentJobId:typeof g.agentJobId=="string"?g.agentJobId:null,updatedAt:typeof g.updatedAt=="string"?g.updatedAt:null}})(),m=l["agent:detached-identity"];if(m===void 0)return{tabs:a,agentJob:u};if(typeof m!="object"||m===null||!("agentJobId"in m)||typeof m.agentJobId!="string"||!("identityId"in m)||typeof m.identityId!="string")throw new Error("Unreadable identity detach acknowledgement in chrome.storage.session");return{tabs:a,agentJob:u,detachedIdentity:{agentJobId:m.agentJobId,identityId:m.identityId}}},cs),"evaluate")});return{ok:!0,observedAt:e,...i}}catch(i){return{ok:!1,observedAt:e,reason:"evaluate_failed",detail:i instanceof Error?i.message:String(i)}}}o(Dr,"probePlaybackSession");var Wt=w("task-browser-instances"),fi=class extends Error{static{o(this,"TaskBrowserLaunchAbortedError")}subjectId;constructor(e){super(`[runtime] launch of the instance of task browser subject ${e} was aborted: the instance was disposed while the browser was still coming up, so it was torn down instead of being kept.`),this.name="TaskBrowserLaunchAbortedError",this.subjectId=e}},Ht=class{static{o(this,"TaskBrowserInstances")}#e;#t;#n;#r;#i;#a;#s=new Map;#o=new Map;constructor(e){this.#e=e.registry,this.#t=e.extensionDist,this.#n=e.allowInsecureHttps,this.#r=e.disableBrowserSandbox,this.#i=e.onLost,this.#a=e.kind}subjectIdsWithInstance(){return[...this.#s.keys()]}async start(e,n,r,i){let s=this.#s.get(n);if(s!==void 0)throw new Error(`[runtime] task browser subject ${n} already has an instance in state ${s.state}`);let l=this.#m(e.jobId,n),c=await ae(e.jobId,"instance_reserve",()=>{let u=this.#o.get(l);return u!==void 0&&this.#d(u),this.#e.reserve(l,e.deadlineAt)}),a={subjectId:n,jobId:e.jobId,instanceKey:l,userDataDir:c.userDataDir,state:"launching",context:null,contextAtTeardown:null,teardown:null};this.#s.set(n,a),Wt.info("Launching the browser task browser instance",{runId:e.jobId,workflowId:e.workflowId,subjectId:n,headful:e.headful,userDataDir:c.userDataDir,deadlineAt:e.deadlineAt});let d=Date.now();try{let u=await Pr({runId:e.jobId,userDataDir:c.userDataDir,extensionDist:this.#t,headful:e.headful,allowInsecureHttps:this.#n,disableBrowserSandbox:this.#r,keepBackgroundWindowsRendering:!0,extensionSession:r,command:i,entryUrl:i.kind==="task_launch"?e.entryUrl:null,onContext:o(m=>{a.context=m},"onContext"),assertNotAborted:o(()=>this.#l(a),"assertNotAborted")});this.#l(a),a.state="active",this.#u(a,u.context),Wt.info("Task browser instance launched",{runId:e.jobId,subjectId:n,chromeVersion:u.chromeVersion,extensionId:u.extensionId,readinessAttempts:u.readinessAttempts,readyAfterMs:u.readyAfterMs,launchDurationMs:Date.now()-d})}catch(u){let m=o(g=>{Wt.error("Teardown after a failed task browser launch did not finish",{runId:e.jobId,subjectId:n,err:g instanceof Error?g.message:String(g)})},"logTeardownFailure");if(a.teardown===null)await this.#c(a,"launch_failure").catch(m);else if(await a.teardown.catch(m),a.context!==null&&a.context!==a.contextAtTeardown){let g=await _n(this.#e,{instanceKey:a.instanceKey,context:a.context,userDataDir:a.userDataDir,timeoutMs:2e4,trigger:"dispose_during_launch"});this.#p(a,g),g.failure!==null&&m(g.failure)}throw u}}async dispose(e,n){let r=this.#s.get(n);if(r!==void 0&&r.jobId===e){if(r.teardown!==null)return r.teardown;let s=r.state==="launching"?"dispose_during_launch":"dispose";return this.#c(r,s)}let i=this.#o.get(this.#m(e,n));return i!==void 0?this.#d(i):null}async disposeAll(e){let n=new Set;for(let s of this.#s.values())s.jobId===e&&n.add(s.subjectId);for(let s of this.#o.values())s.jobId===e&&n.add(s.subjectId);if(n.size===0)return;let i=(await Promise.allSettled([...n].map(s=>this.dispose(e,s)))).find(s=>s.status==="rejected");if(i!==void 0)throw i.reason}async probe(e){let n=this.#s.get(e);return n===void 0||n.state!=="active"||n.context===null?{ok:!1,observedAt:new Date().toISOString(),reason:"service_worker_absent",detail:`the runtime owns no running instance of task browser subject ${e}`}:Dr(n.context)}#l(e){if(e.teardown!==null)throw new fi(e.subjectId)}#u(e,n){let r=o(s=>{if(e.state!=="active"||e.teardown!==null)return;let l=this.#c(e,"instance_lost"),c={jobId:e.jobId,subjectId:e.subjectId,at:new Date().toISOString(),source:s};Wt.warn("Task browser instance disappeared without a dispose",{...c}),l.catch(a=>{Wt.error("Teardown after a lost task browser instance failed",{runId:e.jobId,subjectId:e.subjectId,err:a instanceof Error?a.message:String(a)})}).finally(()=>this.#i(c))},"report");n.on("close",()=>r("context_closed"));let i=n.browser();i!==null&&i.on("disconnected",()=>r("browser_disconnected"))}#c(e,n){e.state="tearing_down",e.contextAtTeardown=e.context;let r=(async()=>{try{let i=await _n(this.#e,{instanceKey:e.instanceKey,context:e.context,userDataDir:e.userDataDir,timeoutMs:2e4,trigger:n});if(Wt.info("Task browser instance closed",{runId:e.jobId,subjectId:e.subjectId,trigger:n,disposeOutcome:i.result.outcome,instanceReleased:i.result.instanceReleased}),this.#p(e,i),i.failure!==null)throw i.failure;return i.result}finally{this.#s.get(e.subjectId)===e&&this.#s.delete(e.subjectId)}})();return e.teardown=r,r}#p(e,n){if(n.result.instanceReleased){this.#o.delete(e.instanceKey);return}this.#o.set(e.instanceKey,{instanceKey:e.instanceKey,jobId:e.jobId,subjectId:e.subjectId,result:n.result,killConfirmed:n.killConfirmed})}#m(e,n){return this.#a==="identity"?`${e}~${n}`:`${e}~launch~${n}`}#d(e){let n=Nr(this.#e,e);return this.#o.delete(e.instanceKey),n}};var $r=class{static{o(this,"IdentityInstances")}#e;constructor(e){this.#e=new Ht({...e,kind:"identity",onLost:o(({subjectId:n,...r})=>e.onLost({...r,identityId:n}),"onLost")})}identityIdsWithInstance(){return this.#e.subjectIdsWithInstance()}async start(e,n,r){await this.#e.start(e,n,r,{v:1,kind:"task_identity",runId:e.jobId,issuedAt:new Date().toISOString(),workflowId:e.workflowId,identityId:n})}dispose(e,n){return this.#e.dispose(e,n)}disposeAll(e){return this.#e.disposeAll(e)}probe(e){return this.#e.probe(e)}};var Ur=class{static{o(this,"TaskJobInstances")}identities;launches;constructor(e){this.identities=new $r(e),this.launches=new Ht({...e,kind:"launch",onLost:o(({subjectId:n,...r})=>e.onLaunchLost({...r,launchId:n}),"onLost")})}async startLaunch(e,n,r){await this.launches.start(e,n,r,{v:1,kind:"task_launch",runId:e.jobId,issuedAt:new Date().toISOString(),workflowId:e.workflowId,launchId:n})}async disposeAll(e){let n=await Promise.allSettled([this.identities.disposeAll(e),this.launches.disposeAll(e)]);for(let r of n)if(r.status==="rejected")throw r.reason}};import{mkdirSync as Cl,lstatSync as kh,readdirSync as Rh,readFileSync as Th,renameSync as xh,rmSync as Ih,writeFileSync as Oh}from"node:fs";import{join as kn}from"node:path";var dt=w("instance-registry");function Mr(t){return typeof t=="string"&&t!==""}o(Mr,"isNonEmptyString");function Ah(t,e){if(typeof t!="object"||t===null)throw new Error(`[instance-registry] ${e} does not contain a JSON object.`);let n=t;if(n.v!==1)throw new Error(`[instance-registry] ${e} has version ${JSON.stringify(n.v)}, expected 1.`);if(!Mr(n.runId))throw new Error(`[instance-registry] ${e} has a missing or empty runId.`);if(!Mr(n.userDataDir))throw new Error(`[instance-registry] ${e} has a missing or empty userDataDir.`);if(!Mr(n.startedAt)||!Mr(n.deadlineAt))throw new Error(`[instance-registry] ${e} has a missing or empty timestamp field.`);if(typeof n.agentPid!="number"||!Number.isInteger(n.agentPid))throw new Error(`[instance-registry] ${e} has a non-integer agentPid.`);return{v:1,runId:n.runId,agentPid:n.agentPid,userDataDir:n.userDataDir,startedAt:n.startedAt,deadlineAt:n.deadlineAt}}o(Ah,"parseInstanceRecord");function Ch(t,e){let n=`${t}.tmp`;Oh(n,JSON.stringify(e,null,2),{encoding:"utf8",mode:384}),xh(n,t)}o(Ch,"writeMarkerAtomically");var ut=class{static{o(this,"InstanceRegistry")}#e;#t;constructor(e){this.#t=e,this.#e=kn(e,ar)}get instancesRoot(){return this.#e}userDataDirFor(e){return kn(this.#e,e)}reserve(e,n){Cl(this.#e,{recursive:!0,mode:448});let r=this.userDataDirFor(e);try{Cl(r,{recursive:!1,mode:448})}catch(s){throw typeof s=="object"&&s!==null&&s.code==="EEXIST"?new We(e,r,s):s}let i=new Date().toISOString();try{kr(this.#t,e),Ch(kn(r,lr),{v:1,runId:e,agentPid:process.pid,userDataDir:r,startedAt:i,deadlineAt:n})}catch(s){try{this.release(e)}catch(l){dt.error("Failed to roll back the instance directory after a failed reservation",{runId:e,userDataDir:r,err:l instanceof Error?l.message:String(l)})}throw s}return dt.info("Instance reserved",{runId:e,userDataDir:r,deadlineAt:n}),{runId:e,userDataDir:r,startedAt:i,deadlineAt:n}}read(e){return this.#r(kn(this.userDataDirFor(e),lr))}release(e){let n=this.userDataDirFor(e);try{kh(n)}catch(i){if(!P(i))throw i;ri(this.#t,e);return}let r=kr(this.#t,e);try{Ih(n,{recursive:!0,force:!0})}catch(i){throw r||kr(this.#t,e),i}ri(this.#t,e),dt.info("Instance released",{runId:e,userDataDir:n})}listRunIds(){let e;try{e=Rh(this.#e,{withFileTypes:!0})}catch(n){if(typeof n=="object"&&n!==null&&n.code==="ENOENT")return[];throw n}return e.filter(n=>n.isDirectory()).map(n=>n.name)}async sweepOrphans(){let e=new Date().toISOString(),n=[];for(let r of this.listRunIds())n.push(await this.#n(r));return n.length>0?dt.warn("Startup sweep found leftover browser instances",{instancesRoot:this.#e,count:n.length,outcomes:n}):dt.info("Startup sweep found no leftover browser instances",{instancesRoot:this.#e}),{scannedAt:e,instancesRoot:this.#e,outcomes:n}}async#n(e){let n=this.userDataDirFor(e),r=kn(n,lr),i=null,s;try{i=this.#r(r),s="valid"}catch(c){s=(typeof c=="object"&&c!==null?c.code:null)==="ENOENT"?"missing":"unreadable",dt.warn("Leftover instance marker is unusable \u2014 killing by directory path anyway",{runId:e,userDataDir:n,marker:s,err:c instanceof Error?c.message:String(c)})}let l=await Bt(n);return dt.warn("Leftover browser instance swept",{runId:e,userDataDir:n,marker:s,kill:l}),this.release(e),{runId:e,userDataDir:n,marker:s,record:i,kill:l,removed:!0}}#r(e){let n=Th(e,"utf8");return Ah(JSON.parse(n),e)}};var Oe=w("playwright-execution-runtime"),hi=class extends Error{static{o(this,"LaunchAbortedError")}runId;constructor(e){super(`[runtime] launch of run ${e} was aborted: the instance was disposed while the browser was still coming up, so it was torn down instead of being published (CONTRACT-la \xA715 A3, A19.1).`),this.name="LaunchAbortedError",this.runId=e}},Gr=class{static{o(this,"PlaywrightExecutionRuntime")}#e;#t;#n;#r;#i;#a;#s;#o;#l=null;#u=null;#c=null;#p=!1;#m=null;#d=null;constructor(e){dr(e.extensionDist),this.#e=e.extensionDist,this.#t=e.headfulOverride,this.#n=e.allowInsecureHttps,this.#r=e.disableBrowserSandbox,this.#i=e.onInstanceLost,this.#a=new ut(e.stateDir),this.#s=Al(e.extensionDist),this.#o=new Ur({registry:this.#a,extensionDist:e.extensionDist,allowInsecureHttps:e.allowInsecureHttps,disableBrowserSandbox:e.disableBrowserSandbox,onLost:e.onIdentityInstanceLost,onLaunchLost:e.onLaunchInstanceLost}),Oe.info("Execution runtime constructed",{stateDir:e.stateDir,instancesRoot:this.#a.instancesRoot,headfulOverride:e.headfulOverride,allowInsecureHttps:e.allowInsecureHttps,envFingerprint:this.#s})}getActiveInstance(){let e=this.#l;return e===null?null:{runId:e.runId,userDataDir:e.userDataDir,headful:e.headful,extensionId:e.extensionId,chromeVersion:e.chromeVersion,startedAt:e.startedAt,deadlineAt:e.deadlineAt}}async startIdentityInstance(e,n,r){await this.#o.identities.start(this.#g(e),n,r)}async startLaunchInstance(e,n,r){await this.#o.startLaunch(this.#g(e),n,r)}disposeLaunchInstance(e,n){return this.#o.launches.dispose(e,n)}launchIdsWithInstance(){return this.#o.launches.subjectIdsWithInstance()}async disposeIdentityInstance(e,n){return this.#o.identities.dispose(e,n)}async probeIdentityInstance(e){return this.#o.identities.probe(e)}identityIdsWithInstance(){return this.#o.identities.identityIdsWithInstance()}async sweepOrphanInstances(){return this.#a.sweepOrphans()}async probePlaybackSession(){let e=this.#l;return e===null?{ok:!1,observedAt:new Date().toISOString(),reason:"service_worker_absent",detail:"the runtime owns no browser instance"}:Dr(e.context)}prepareTaskJob(e){if(e.command.kind!=="swarm"||e.entryUrl===null)throw new Error(`[runtime] job ${e.runId} is not a task claim with an entry address`);let n=this.#u?.jobId??this.#l?.runId??this.#c?.runId;if(n!==void 0)throw new jt(e.runId,n);let r=Pl(e);return this.#u={jobId:e.runId,workflowId:e.command.workflowId,entryUrl:e.entryUrl,headful:this.#h(e),deadlineAt:r},r}#g(e){let n=this.#u;if(n===null||n.jobId!==e)throw new Error(`[runtime] job ${e} is not the claimed task job`);return n}async startRun(e){let n=this.#l;if(n!==null)throw new jt(e.runId,n.runId);let r=Date.now();e.command.kind==="swarm"&&this.#u===null&&this.prepareTaskJob(e);let i=this.#u;if(i!==null&&i.jobId!==e.runId)throw new jt(e.runId,i.jobId);let s=i?.deadlineAt??Pl(e),l=this.#h(e),c=await ae(e.runId,"instance_reserve",()=>this.#a.reserve(e.runId,s));this.#d?.runId===e.runId&&(this.#d=null);let a={runId:e.runId,userDataDir:c.userDataDir,context:null,disposeRequested:!1};this.#c=a;let d=e.command.kind==="swarm"||e.command.kind==="conversation";Oe.info("Launching browser for run",{runId:e.runId,headful:l,requestHeadful:e.headful,headfulOverride:this.#t,keepBackgroundWindowsRendering:d,userDataDir:c.userDataDir,maxRunDurationSec:e.maxRunDurationSec,deadlineAt:s,envFingerprint:this.#s});let u=null;try{let m=await Pr({runId:e.runId,userDataDir:c.userDataDir,extensionDist:this.#e,headful:l,allowInsecureHttps:this.#n,disableBrowserSandbox:this.#r,keepBackgroundWindowsRendering:d,extensionSession:e.extensionSession,command:e.command,entryUrl:e.command.kind==="swarm"?null:e.entryUrl,onContext:o(E=>{u=E,a.context=E},"onContext"),assertNotAborted:o(()=>this.#w(a),"assertNotAborted")}),g={runId:e.runId,context:m.context,userDataDir:c.userDataDir,headful:l,extensionId:m.extensionId,chromeVersion:m.chromeVersion,startedAt:c.startedAt,deadlineAt:s};this.#w(a),this.#S(g),this.#l=g,this.#c===a&&(this.#c=null),Oe.info("Run launched",{runId:e.runId,chromeVersion:m.chromeVersion,extensionId:m.extensionId,readinessAttempts:m.readinessAttempts,readyAfterMs:m.readyAfterMs,launchDurationMs:Date.now()-r})}catch(m){throw this.#c===a&&(this.#c=null),await this.#y({runId:e.runId,context:u,userDataDir:c.userDataDir,timeoutMs:2e4,trigger:a.disposeRequested?"dispose_during_launch":"launch_failure"}),m}finally{this.#c===a&&(this.#c=null)}}async cancelRun(e){await this.disposeRun(e)}async disposeRun(e,n=2e4){this.#u?.jobId===e&&(this.#u=null);let[r,i]=await Promise.allSettled([this.#o.disposeAll(e),this.#f(e,n)]);if(i.status==="rejected")throw i.reason;if(r.status==="rejected")throw r.reason;return i.value}async#f(e,n){let r=this.#m;if(r!==null&&r.runId===e)return Oe.info("Dispose requested for a lost instance \u2014 joining the teardown already running",{runId:e}),r.promise;let i=this.#c;if(i!==null&&i.runId===e)return i.disposeRequested=!0,Oe.warn("Dispose requested for a run that is still launching \u2014 aborting the launch",{runId:e,userDataDir:i.userDataDir,contextPresent:i.context!==null}),this.#y({runId:e,context:i.context,userDataDir:i.userDataDir,timeoutMs:n,trigger:"dispose_during_launch"});let s=this.#l;return s===null||s.runId!==e?this.#v(e):(this.#l=null,this.#y({runId:e,context:s.context,userDataDir:s.userDataDir,timeoutMs:n,trigger:"dispose"}))}#h(e){return e.headful||this.#t}#w(e){if(e.disposeRequested)throw new hi(e.runId)}#S(e){let n=o(i=>{if(this.#p||this.#l?.runId!==e.runId)return;this.#l=null;let s=this.#y({runId:e.runId,context:e.context,userDataDir:e.userDataDir,timeoutMs:2e4,trigger:"instance_lost"});this.#m={runId:e.runId,promise:s},s.catch(c=>{Oe.error("Teardown after a lost browser instance failed",{runId:e.runId,userDataDir:e.userDataDir,err:c instanceof Error?c.message:String(c)})}).finally(()=>{this.#m?.promise===s&&(this.#m=null)});let l={runId:e.runId,at:new Date().toISOString(),source:i};Oe.error("Browser instance disappeared without a dispose",{...l}),this.#i(l)},"report");e.context.on("close",()=>n("context_closed"));let r=e.context.browser();r!==null&&r.on("disconnected",()=>n("browser_disconnected"))}#v(e){let n=this.#d;if(n===null||n.runId!==e)return Oe.info("Dispose requested for a run this runtime does not own \u2014 no-op",{requestedRunId:e,activeRunId:this.#l===null?null:this.#l.runId,disposeOutcome:"closed"}),{runId:e,outcome:"closed",kill:null,instanceReleased:!1,durationMs:0};if(n.result.instanceReleased)return Oe.info("Dispose repeated for a run already torn down \u2014 replaying its outcome",{runId:e,disposeOutcome:n.result.outcome,instanceReleased:!0}),n.result;let r=Nr(this.#a,{instanceKey:e,result:n.result,killConfirmed:n.killConfirmed});return this.#d={runId:e,result:r,killConfirmed:!0},r}async#y(e){this.#p=!0;try{let n=await _n(this.#a,{instanceKey:e.runId,context:e.context,userDataDir:e.userDataDir,timeoutMs:e.timeoutMs,trigger:e.trigger});if(this.#d={runId:e.runId,result:n.result,killConfirmed:n.killConfirmed},n.failure!==null)throw n.failure;return n.result}finally{this.#p=!1}}};function Pl(t){return new Date(Date.now()+t.maxRunDurationSec*1e3).toISOString()}o(Pl,"deadlineOf");import{setTimeout as Ph}from"node:timers/promises";var He=w("supervisor-identity");function gi(t){if(t.initialToken!==void 0)return{source:"env_token",agentToken:t.initialToken};let e=L(t.stateDir);return e===null?null:(Gh(e.serverUrl,t.serverUrl),{source:"state_file",agentToken:e.agentToken,agentId:e.agentId})}o(gi,"selectExistingCredential");async function Fr(t){let{config:e}=t,n=gi(e);if(n?.source==="env_token")return Nh(e,n.agentToken);if(n?.source==="state_file")return He.info("Agent identity loaded from the state file",{agentId:n.agentId}),{agentToken:n.agentToken,agentId:n.agentId,pollWaitSec:void 0,source:"state_file"};if(e.enrollmentCode!==void 0)return Dh(t,e.enrollmentCode);throw new p(`[progon-agent] This machine has no agent identity, so the daemon cannot start.
|
|
92
92
|
There is no state file in ${e.stateDir} and neither PROGON_AGENT_TOKEN nor PROGON_AGENT_ENROLL_CODE is set.
|
|
93
|
-
To enroll: create the agent in Progon (Settings \u2192 Agents), mint its enrollment code, then start the daemon once with PROGON_AGENT_ENROLL_CODE=<code>. The code is one-shot and expires in 15 minutes (CONTRACT-la \xA75.1); the minted pgat_ token is persisted to the state file, so later starts need neither variable.`)}o(Fr,"resolveAgentIdentity");function
|
|
94
|
-
Mint a fresh code in Progon (Settings \u2192 Agents) once the server is reachable, then run 'progon-agent enroll <code>' again.`,{cause:l});He.warn("Enrollment attempt failed \u2014 backing off and retrying",{attempt:s,retryInMs:c.delayMs,err:l.message}),await
|
|
93
|
+
To enroll: create the agent in Progon (Settings \u2192 Agents), mint its enrollment code, then start the daemon once with PROGON_AGENT_ENROLL_CODE=<code>. The code is one-shot and expires in 15 minutes (CONTRACT-la \xA75.1); the minted pgat_ token is persisted to the state file, so later starts need neither variable.`)}o(Fr,"resolveAgentIdentity");function Nh(t,e){return t.enrollmentCode!==void 0&&He.warn("Both PROGON_AGENT_TOKEN and PROGON_AGENT_ENROLL_CODE are set \u2014 the token wins and the enrollment code is NOT redeemed (it stays valid until it expires)"),He.info("Agent identity taken from PROGON_AGENT_TOKEN",{stateFile:Lh(t.stateDir)}),{agentToken:e,agentId:null,pollWaitSec:void 0,source:"env_token"}}o(Nh,"identityFromEnvToken");function Lh(t){try{return L(t)===null?"absent":"present"}catch(e){return He.warn("The state file could not be read \u2014 continuing on PROGON_AGENT_TOKEN, which does not need it. The persisted credential is NOT usable: once this variable is unset, the daemon will refuse to start until the file is removed and the machine re-enrolled",{stateDir:t,err:e instanceof Error?e.message:String(e)}),"unreadable"}}o(Lh,"describeStateFile");async function Dh(t,e){let{config:n,machine:r}=t;He.info("No agent identity found \u2014 redeeming the enrollment code",{hostname:r.hostname,platform:r.platform,arch:r.arch,agentVersion:r.agentVersion});let i=new Ut(t.fetchImpl===void 0?{serverUrl:n.serverUrl,machine:r}:{serverUrl:n.serverUrl,machine:r,fetchImpl:t.fetchImpl}),s=await Uh(i,e,t.rng,t.signal);return It(n.stateDir,{agentId:s.agentId,agentToken:s.agentToken,protocolVersion:s.protocolVersion,serverUrl:n.serverUrl,tokenRotatedAt:null}),He.info("Agent identity persisted \u2014 PROGON_AGENT_ENROLL_CODE is no longer needed",{agentId:s.agentId,stateDir:n.stateDir}),{agentToken:s.agentToken,agentId:s.agentId,pollWaitSec:s.pollWaitSec,source:"enrollment"}}o(Dh,"enrollThisMachine");var Nl=900*1e3,$h=3e4;async function Uh(t,e,n,r){let i=Date.now()+Nl;for(let s=0;;s+=1)try{return await Mh(t,e,r)}catch(l){if(r?.throwIfAborted(),!(l instanceof A))throw l;let c=Be({attempt:s,error:l,rng:n});if(!c.retry)throw He.warn("Enrollment refused definitively \u2014 not retrying",{attempt:s,reason:c.reason,err:l.message}),l;if(Date.now()+c.delayMs>=i)throw new p(`[progon-agent] Enrollment kept failing for the ${Nl/6e4} minutes an enrollment code stays valid (CONTRACT-la \xA75.1), so this code can no longer be redeemed. Last failure: ${l.message}
|
|
94
|
+
Mint a fresh code in Progon (Settings \u2192 Agents) once the server is reachable, then run 'progon-agent enroll <code>' again.`,{cause:l});He.warn("Enrollment attempt failed \u2014 backing off and retrying",{attempt:s,retryInMs:c.delayMs,err:l.message}),await Ph(c.delayMs,void 0,{signal:r}).catch(a=>{throw r?.throwIfAborted(),a})}}o(Uh,"enrollWithRetry");async function Mh(t,e,n){if(n===void 0)return t.enroll(e);n.throwIfAborted();let r=new AbortController,i,s=o(()=>{i=setTimeout(()=>r.abort(n.reason),$h)},"onStop");n.addEventListener("abort",s,{once:!0});try{return await t.enroll(e,{signal:r.signal})}finally{n.removeEventListener("abort",s),clearTimeout(i)}}o(Mh,"enrollOnce");function Ll(t,e){if(t.source==="enrollment")return;let n=" The code itself was not spent and stays valid until it expires.";throw t.source==="env_token"?new p(`[progon-agent] The enrollment code was not redeemed: PROGON_AGENT_TOKEN is set, and a credential supplied that way takes precedence over any code (CONTRACT-la \xA78).
|
|
95
95
|
Unset PROGON_AGENT_TOKEN, then run the same command again. A separate state directory does NOT help here: the variable is read before any state file and wins wherever that file lives.
|
|
96
96
|
`+n):new p(`[progon-agent] The enrollment code was not redeemed: this machine already holds a credential enrolled against ${e.serverUrl}, and a persisted credential takes precedence over a code (CONTRACT-la \xA78).
|
|
97
97
|
To enroll this machine as a SECOND agent \u2014 for another deployment, or as another agent record \u2014 give it its own state directory: PROGON_RUNNER_STATE_DIR=<dir> progon-agent enroll <code> --server <url> (and give 'progon-agent start' the same variable).
|
|
98
98
|
To REPLACE the credential it already holds, remove the state file in ${e.stateDir}, then run: progon-agent enroll <code> --server ${e.serverUrl} \u2014 with that file gone this machine no longer names that deployment itself, and --server is what keeps the new enrollment pointed at it.
|
|
99
|
-
`+n)}o(
|
|
100
|
-
Either point PROGON_SERVER_URL back at ${t} \u2014 or unset it entirely, since an enrolled machine reads the server from its own state file (CONTRACT-la \xA78) \u2014 or move this machine to ${e}: run 'progon-agent enroll <code> --server ${e}' in a terminal, which offers to reset this enrollment (revoking it on ${t}) first. To keep BOTH, enroll the second one under its own PROGON_RUNNER_STATE_DIR rather than replacing this credential.`)}o(Bh,"assertServerMatchesEnrollment");import{hostname as jh}from"node:os";var Ll=["darwin","linux","win32"],Dl=["x64","arm64"];function Wh(t){return Ll.includes(t)}o(Wh,"isSupportedPlatform");function Hh(t){return Dl.includes(t)}o(Hh,"isSupportedArch");function Ke(){let t=process.platform;if(!Wh(t))throw new Error(`[supervisor] Unsupported platform ${JSON.stringify(t)}. The local agent runs on ${Ll.join(", ")} (CONTRACT-la \xA75.1, \xA710.3).`);let e=process.arch;if(!Hh(e))throw new Error(`[supervisor] Unsupported CPU architecture ${JSON.stringify(e)}. The local agent runs on ${Dl.join(", ")} (CONTRACT-la \xA75.1).`);let n=jh();if(n==="")throw new Error("[supervisor] os.hostname() returned an empty string, so this machine cannot be named on the enroll wire (CONTRACT-la \xA75.1 requires a non-empty hostname). Fix the host's network configuration.");return{hostname:n,platform:t,arch:e,agentVersion:te()}}o(Ke,"describeAgentMachine");var $l=o(()=>{},"noop"),Br=class{static{o(this,"ActionQueue")}#e=Promise.resolve();run(e){let n=this.#e.then(e,e);return this.#e=n.then($l,$l),n}};var Ul=w("supervisor-deadline"),kn=class extends Error{static{o(this,"DeadlineExceededError")}operation;timeoutMs;constructor(e,n){super(`[supervisor] ${e} did not settle within ${n}ms`),this.name="DeadlineExceededError",this.operation=e,this.timeoutMs=n}};async function Je(t){let e=t.work(),n=!1;e.then(()=>{n&&Ul.warn("Abandoned work settled successfully after its deadline had passed",{operation:t.operation,timeoutMs:t.timeoutMs})},s=>{n&&Ul.warn("Abandoned work rejected after its deadline had passed",{operation:t.operation,timeoutMs:t.timeoutMs,err:s instanceof Error?s.message:String(s)})});let r,i=new Promise((s,l)=>{r=setTimeout(()=>{n=!0,l(new kn(t.operation,t.timeoutMs))},t.timeoutMs)});try{return await Promise.race([e,i])}finally{r!==void 0&&clearTimeout(r)}}o(Je,"withDeadline");function oe(t,e){return new Promise(n=>{if(e.aborted){n();return}let r=setTimeout(()=>{e.removeEventListener("abort",i),n()},t);function i(){clearTimeout(r),n()}o(i,"onAbort"),e.addEventListener("abort",i,{once:!0})})}o(oe,"sleep");var Ve=w("fail-reporter"),jr=class{static{o(this,"RunFailureReporter")}#e;#t=null;#n=null;constructor(e){this.#e=e}hasVerdictFor(e){return this.#n===e}async report(e){if(this.#n===e.runId){Ve.warn("Ignoring a second terminal verdict for a run this agent already reported",{runId:e.runId,ignoredReason:e.body.reason,stillUndelivered:this.#t!==null});return}let n=this.#t;n!==null&&n.runId!==e.runId&&Ve.warn("Dropping an undelivered fail verdict \u2014 a different run needs one now",{droppedRunId:n.runId,droppedReason:n.body.reason,runId:e.runId}),this.#t={...e,attempt:0,nextAttemptAtMs:0},this.#n=e.runId,Ve.error("Reporting run failure to the gateway",{runId:e.runId,...e.body}),await this.#r()}async retryPending(){let e=this.#t;e!==null&&(Date.now()<e.nextAttemptAtMs||await this.#r())}discardIfNotPublished(e){let n=this.#t;n!==null&&n.runId!==e&&(Ve.info("Undelivered fail verdict discarded \u2014 its run is already terminal server-side",{runId:n.runId,reason:n.body.reason,publishedRunId:e}),this.#t=null)}async#r(){let e=this.#t;if(e!==null)try{let n=await this.#e.failRun(e.runId,e.body);Ve.info("Fail verdict delivered",{runId:e.runId,reason:e.body.reason,status:n.status,attempts:e.attempt+1}),this.#t=null}catch(n){if(n instanceof T)throw n;if(n instanceof O)throw Ve.error("Fail verdict abandoned \u2014 the gateway no longer accepts this credential as current",{runId:e.runId,reason:e.body.reason,err:n.message}),this.#t=null,n;if(!(n instanceof A))throw n;let r=Be({attempt:e.attempt,error:n});if(!r.retry){Ve.error("Fail verdict abandoned \u2014 the gateway refused it definitively",{runId:e.runId,reason:e.body.reason,noRetryReason:r.reason,err:n.message}),this.#t=null;return}this.#t={runId:e.runId,body:e.body,attempt:e.attempt+1,nextAttemptAtMs:Date.now()+r.delayMs},Ve.warn("Fail verdict not delivered \u2014 held for retry",{runId:e.runId,reason:e.body.reason,attempt:e.attempt+1,retryInMs:r.delayMs,err:n.message})}}};var Wr=120,Ht=Wr*1e3,wi=3e4,Kt=3,Si=45*1e3,Ei="agent shutdown";var Hr=w("task-launch-reconciler"),Kr=class{static{o(this,"TaskLaunchReconciler")}#e;#t=null;constructor(e){this.#e=e}async apply(e,n){let r=this.#t;(r===null||r.jobId!==e)&&(r={jobId:e,desired:new Set,attempted:new Set,closing:new Set},this.#t=r),r.desired=new Set(n);for(let i of this.#e.runtime.launchIdsWithInstance())r.desired.has(i)||r.closing.has(i)||this.#r(r,i);for(let i of r.desired)r.attempted.has(i)||(r.attempted.add(i),this.#n(r,i))}forgetJob(){this.#t=null}async handleLost(e){Hr.warn("Verification browser lost; its launch lease will end it, no restart or job fail",{...e})}async#n(e,n){let r=null;try{let i=await this.#e.client.issueLaunchSession(e.jobId,n);if(this.#t!==e||!e.desired.has(n))return;try{await Je({operation:`startLaunchInstance(${e.jobId}, ${n})`,timeoutMs:Ht,work:o(()=>this.#e.runtime.startLaunchInstance(e.jobId,n,i),"work")})}catch(s){r={stage:"launch",error:s}}}catch(i){r={stage:"session",error:i}}finally{await this.#e.detach(async()=>{if(r!==null){if(Hr.error("Verification browser could not start; the first-claim deadline ends its launch",{runId:e.jobId,launchId:n,stage:r.stage,err:r.error instanceof Error?r.error.message:String(r.error)}),r.stage==="launch"&&await this.#i(e,n),r.error instanceof T||r.error instanceof O)throw r.error;return}(this.#t!==e||!e.desired.has(n))&&await this.#i(e,n)})}}#r(e,n){e.closing.add(n),this.#i(e,n).finally(()=>{this.#e.detach(async()=>{e.closing.delete(n)})})}async#i(e,n){try{let r=await this.#e.runtime.disposeLaunchInstance(e.jobId,n);r!==null&&Hr.info("Verification browser disposed",{runId:e.jobId,launchId:n,disposeOutcome:r.outcome,instanceReleased:r.instanceReleased})}catch(r){Hr.error("Verification browser cleanup failed",{runId:e.jobId,launchId:n,err:r instanceof Error?r.message:String(r)})}}};var Jt=w("run-monitor");function Jh(t,e){let n=Date.now();return e.ok?e.tabs.some(i=>i.playback!==null&&i.playback.runId===t)?{healthy:!0}:Vh(t,e.agentJob,n)?{healthy:!0}:{healthy:!1,reason:"playback_absent",detail:`the extension answered but nothing it holds describes a live run of ours (${qh(e.tabs)}; ${Yh(e.agentJob,n)})`}:{healthy:!1,reason:e.reason,detail:e.detail}}o(Jh,"judgeProbe");function Vh(t,e,n){if(e===null||e.agentJobId!==t||e.updatedAt===null)return!1;let r=Date.parse(e.updatedAt);return Number.isNaN(r)?!1:n-r<=Si}o(Vh,"isJobPulseStanding");function qh(t){if(t.length===0)return"tabStates is empty";let e=t.map(n=>n.playback===null?"none":n.playback.runId);return`${t.length} tab(s), playback run ids: ${e.join(", ")}`}o(qh,"describeTabs");function Yh(t,e){if(t===null)return"no job pulse is standing";if(t.updatedAt===null)return`job pulse: agentJobId=${t.agentJobId??"unreadable"}, updatedAt=unreadable`;let n=Date.parse(t.updatedAt),r=Number.isNaN(n)?"unparsable":`${String(e-n)}ms old`;return`job pulse: agentJobId=${t.agentJobId??"unreadable"}, ${r} (stale past ${String(Si)}ms)`}o(Yh,"describeJobMarker");var Vt=class{static{o(this,"RunMonitor")}#e;#t;#n=null;#r=null;#i=0;#a=!1;constructor(e){this.#e=e;let n=Date.parse(e.deadlineAt);if(Number.isNaN(n))throw new Error(`[run-monitor] run ${e.runId} has an unparseable deadlineAt ${JSON.stringify(e.deadlineAt)} \u2014 the run deadline (CONTRACT-la \xA715 A7) cannot be armed.`);this.#t=n}get runId(){return this.#e.runId}start(){let e=Math.max(0,this.#t-Date.now());Jt.info("Monitoring launched run",{runId:this.#e.runId,identityId:this.#e.identityId,deadlineAt:this.#e.deadlineAt,deadlineInMs:e,probeIntervalMs:wi,probeStrikeLimit:Kt}),this.#n=setInterval(()=>{this.#l()},wi),this.#n.unref();let n=this.#e;n.identityId===null&&(this.#r=setTimeout(()=>{this.#a||(this.stop(),Jt.error("Run reached its server-authored deadline",{runId:this.#e.runId,identityId:this.#e.identityId,deadlineAt:this.#e.deadlineAt}),n.onDeadline())},e),this.#r.unref())}stop(){this.#a=!0,this.#n!==null&&(clearInterval(this.#n),this.#n=null),this.#r!==null&&(clearTimeout(this.#r),this.#r=null)}async#l(){if(this.#a)return;let e=await this.#o();if(this.#a)return;let n=e.ok?e.detachedIdentity:void 0;if(this.#e.identityId!==null&&n?.agentJobId===this.#e.runId&&n.identityId===this.#e.identityId){this.stop(),this.#e.onIdentityDetached();return}let r=Jh(this.#e.runId,e);if(r.healthy){this.#i>0&&Jt.info("Liveness probe recovered",{runId:this.#e.runId,identityId:this.#e.identityId,clearedStrikes:this.#i}),this.#i=0;return}this.#i+=1;let i=`${r.reason}: ${r.detail}`;Jt.warn("Liveness probe failed",{runId:this.#e.runId,identityId:this.#e.identityId,strike:this.#i,strikeLimit:Kt,reason:r.reason,detail:r.detail}),!(this.#i<Kt)&&(this.stop(),Jt.error("Liveness probe failed the strike limit \u2014 the browser is gone",{runId:this.#e.runId,identityId:this.#e.identityId,strikes:Kt,detail:i}),this.#e.onBrowserGone(`${Kt} consecutive liveness probes failed (${i})`))}async#o(){try{return await this.#e.probe()}catch(e){let n=e instanceof Error?e.message:String(e);return Jt.error("Liveness probe threw instead of reporting an observation",{runId:this.#e.runId,identityId:this.#e.identityId,err:n}),{ok:!1,observedAt:new Date().toISOString(),reason:"evaluate_failed",detail:n}}}};var Ee=w("identity-reconciler"),Jr=class{static{o(this,"IdentityReconciler")}#e;#t;#n;#r=null;constructor(e){this.#e=e.runtime,this.#t=e.client,this.#n=e.detach}async apply(e,n,r){let i=this.#r;(i===null||i.jobId!==e)&&(this.forgetJob(),i={jobId:e,deadlineAt:n,desired:new Set,launching:new Set,closing:new Set,monitors:new Map},this.#r=i);let s=new Set(r),l=s.size!==i.desired.size||[...s].some(c=>!i.desired.has(c));i.desired=s,l&&Ee.info("Identities of the task job changed",{runId:e,identityIds:[...s],identityIdsWithInstance:this.#e.identityIdsWithInstance()});for(let c of this.#e.identityIdsWithInstance())s.has(c)||i.launching.has(c)||this.#u(i,c,"identity_left_run_block");for(let c of s)i.launching.has(c)||i.closing.has(c)||this.#e.identityIdsWithInstance().includes(c)||this.#i(i,c)}forgetJob(e){let n=this.#r;if(n!==null){if(n.jobId===e){let r=this.#e.identityIdsWithInstance().filter(i=>n.monitors.has(i)||n.launching.has(i));r.length>0&&Ee.error("Job deadline reached with identity journal and capture delivery unconfirmed",{event:"runner.identity_delivery_timeout",runId:n.jobId,identityIds:r,deadlineAt:n.deadlineAt})}for(let r of n.monitors.values())r.stop();n.monitors.clear(),this.#r=null}}async handleLost(e){let n=this.#r;if(n===null||n.jobId!==e.jobId){Ee.info("An identity instance of a finished job went away \u2014 nothing to relaunch",{...e});return}this.#m(n,e.identityId),this.#c(n,e.identityId,`the instance disappeared (${e.source})`)}#i(e,n){e.launching.add(n),this.#a(e,n)}async#a(e,n){let r=null;try{let i=await this.#t.issueIdentitySession(e.jobId,n);try{await Je({operation:`startIdentityInstance(${e.jobId}, ${n})`,timeoutMs:Ht,work:o(()=>this.#e.startIdentityInstance(e.jobId,n,i),"work")})}catch(s){r={stage:"launch",err:s}}}catch(i){r={stage:"session",err:i}}await this.#n(()=>this.#l(e,n,r))}async#l(e,n,r){e.launching.delete(n);let i=this.#r===e;if(r!==null){if(Ee.error("The instance of an identity could not be launched \u2014 no fail is reported",{runId:e.jobId,identityId:n,stage:r.stage,jobStillRunning:i,stillInRunBlock:e.desired.has(n),err:r.err instanceof Error?r.err.message:String(r.err)}),r.stage==="session"){if(r.err instanceof T||r.err instanceof O)throw r.err;return}await this.#d(e,n,"launch_failure");return}if(!i){await this.#d(e,n,"job_gone");return}if(!e.desired.has(n)){this.#u(e,n,"identity_left_run_block");return}this.#o(e,n)}#o(e,n){let r=new Vt({runId:e.jobId,identityId:n,deadlineAt:e.deadlineAt,probe:o(()=>this.#e.probeIdentityInstance(n),"probe"),onBrowserGone:o(i=>{this.#n(()=>this.#s(e,n,i))},"onBrowserGone"),onIdentityDetached:o(()=>{this.#n(async()=>{this.#r!==e||e.monitors.get(n)!==r||this.#u(e,n,"identity_detached")})},"onIdentityDetached")});e.monitors.set(n,r),r.start(),Ee.info("Identity instance is up and monitored",{runId:e.jobId,identityId:n})}async#s(e,n,r){this.#r===e&&(e.monitors.delete(n),Ee.error("An identity instance lost its identity \u2014 closing it, no fail is reported",{runId:e.jobId,identityId:n,detail:r}),await this.#d(e,n,"pulse_lost"),this.#c(e,n,r))}#c(e,n,r){if(this.#r===e){if(!e.desired.has(n)){Ee.info("A lost identity instance is not relaunched \u2014 the identity left the run block",{runId:e.jobId,identityId:n,cause:r});return}e.launching.has(n)||e.closing.has(n)||(Ee.warn("Relaunching the instance of an identity that is still in the run block",{runId:e.jobId,identityId:n,cause:r}),this.#i(e,n))}}#u(e,n,r){e.closing.has(n)||(e.closing.add(n),this.#m(e,n),this.#p(e,n,r))}async#p(e,n,r){await this.#d(e,n,r),await this.#n(async()=>{e.closing.delete(n),this.#c(e,n,"the departed instance finished closing")})}#m(e,n){e.monitors.get(n)?.stop(),e.monitors.delete(n)}async#d(e,n,r){try{let i=await this.#e.disposeIdentityInstance(e.jobId,n);if(i===null)return;Ee.info("Identity instance disposed",{runId:e.jobId,identityId:n,trigger:r,disposeOutcome:i.outcome,instanceReleased:i.instanceReleased,durationMs:i.durationMs})}catch(i){Ee.error("Identity instance dispose finished with a failed cleanup step",{runId:e.jobId,identityId:n,trigger:r,err:i instanceof Error?i.message:String(i)})}}};var ve=w("launch-run");async function Fl(t){let e;try{e=await Xh(t)}finally{t.onClaimAnswered()}return e.kind!=="claimed"?e:Zh(t,e.payload)}o(Fl,"claimAndLaunch");async function Xh(t){try{let e=await t.client.claimRun(t.runId);return ve.info("Run claimed",zh(e)),{kind:"claimed",payload:e}}catch(e){if(e instanceof T)throw e;if(e instanceof O)throw ve.error("Claim refused as superseded \u2014 not launching, leaving it to the sweep",{runId:t.runId,err:e.message}),e;if(e instanceof Ct||e instanceof it)return ve.info("Claim refused \u2014 the desired-state snapshot was stale, not launching",{runId:t.runId,err:e.message}),{kind:"claim_refused"};if(!(e instanceof A))throw e;return ve.error("Claim produced no usable answer \u2014 not launching, leaving it to the sweep",{runId:t.runId,err:e.message}),{kind:"claim_unavailable"}}}o(Xh,"claimRun");function zh(t){if(!("kind"in t))return{kind:"playback",runId:t.runId,scenarioId:t.scenarioId,projectId:t.projectId,runPurpose:t.runPurpose,headful:t.headful,maxRunDurationSec:t.maxRunDurationSec};if(t.kind==="swarm")return{kind:t.kind,runId:t.runId,workflowId:t.command.workflowId,headful:t.headful,maxRunDurationSec:t.maxRunDurationSec};if(t.kind==="scenario_launch")return{kind:t.kind,runId:t.runId,projectId:t.command.projectId,launchId:t.command.launchId,headful:t.headful,maxRunDurationSec:t.maxRunDurationSec};if(t.kind==="conversation")return{kind:t.kind,runId:t.runId,conversationId:t.command.conversationId,headful:t.headful,maxRunDurationSec:t.maxRunDurationSec};let e=t;throw new Error(`Unexpected claim kind: ${JSON.stringify(e,["kind"])}`)}o(zh,"describeClaim");function Qh(t){if(!("kind"in t))return t.entryUrl;switch(t.kind){case"swarm":case"scenario_launch":return t.entryUrl;case"conversation":return null;default:{let e=t;throw new Error(`Unexpected claim kind: ${JSON.stringify(e,["kind"])}`)}}}o(Qh,"entryUrlOf");async function Zh(t,e){try{await Je({operation:`startRun(${e.runId})`,timeoutMs:Ht,work:o(()=>t.runtime.startRun({runId:e.runId,entryUrl:Qh(e),headful:e.headful,maxRunDurationSec:e.maxRunDurationSec,extensionSession:e.extensionSession,command:e.command}),"work")})}catch(r){return{kind:"failed",body:tg(t.runId,r)}}let n=t.runtime.getActiveInstance();return n===null||n.runId!==e.runId?(ve.error("The launched instance was already gone when the supervisor read it back",{runId:e.runId,activeRunId:n===null?null:n.runId}),{kind:"instance_lost_immediately",runId:e.runId}):{kind:"launched",instance:n}}o(Zh,"launchClaimedRun");var Ml=500,Gl="\u2026";function eg(t){return t.length<=Ml?t:t.slice(0,Ml-Gl.length)+Gl}o(eg,"fitFailMessageToWire");function tg(t,e){if(e instanceof je){let n=mi(e),r=e.stage==="browser_launch"?Rl(n)??n:n,i=eg(`stage ${e.stage}: ${r}`);if(e.stage==="entry_navigation"){let s=Tl(e);return ve.error("Launch failed",{runId:t,stage:e.stage,failReason:e.failReason,entryFailure:s,err:e.message}),{reason:e.failReason,message:i,entryFailure:s}}return ve.error("Launch failed",{runId:t,stage:e.stage,failReason:e.failReason,err:e.message}),{reason:e.failReason,message:i}}return e instanceof kn?(ve.error("Launch exceeded the agent-side launch deadline \u2014 disposing and failing",{runId:t,launchTimeoutSec:Wr,err:e.message}),{reason:"launch_error",message:`launch did not complete within ${Wr}s`}):e instanceof We?(ve.error("Launch refused by the instance fence \u2014 the run cannot be started here",{runId:t,userDataDir:e.userDataDir,err:e.message}),{reason:"launch_error",message:"a leftover instance directory blocks this run"}):(ve.error("Launch failed with an unexpected error class",{runId:t,errName:e instanceof Error?e.name:typeof e,err:e instanceof Error?e.message:String(e)}),{reason:"launch_error",message:"launch failed with an unexpected error"})}o(tg,"describeLaunchFailure");var be=w("instance-reconciler");function ng(t){let e=o(()=>{},"markSettled"),n=new Promise(l=>{e=l}),r=o(()=>{},"resolveClaimAnswer"),i=new Promise(l=>{r=l}),s={runId:t,cancelledBy:null,claimAnswered:!1,claimAnswer:i,markClaimAnswered:o(()=>{s.claimAnswered=!0,r()},"markClaimAnswered"),settled:n,markSettled:e};return s}o(ng,"createPendingLaunch");var Oe={kind:"reconciled"},Vr=class{static{o(this,"InstanceReconciler")}#e;#t;#n;#r;#i=new Set;#a=null;#l=null;#o=null;#s;#c;#u=null;constructor(e){this.#e=e.client,this.#t=e.runtime,this.#n=e.reporter,this.#r=e.detach,this.#c=new Kr(e),this.#s=new Jr({runtime:e.runtime,client:e.client,detach:e.detach})}get activeRunId(){let e=this.#t.getActiveInstance();return e===null?null:e.runId}async sweepAtStartup(){let e=await this.#t.sweepOrphanInstances();this.#i=new Set(e.outcomes.map(n=>n.runId)),be.info("Startup sweep finished",{instancesRoot:e.instancesRoot,leftoverCount:e.outcomes.length,sweptRunIds:[...this.#i]})}async reconcile(e){let n=e.run;this.#n.discardIfNotPublished(n===null?null:n.runId),this.#u=n===null?null:{runId:n.runId,identityIds:Bl(n),launchIds:jl(n)};let r=this.#l;if(r!==null)return n!==null&&n.runId===r.runId?n.phase!=="queued"?Oe:{kind:"claim_issued",runId:n.runId,claimAnswer:r.claimAnswered?null:r.claimAnswer}:(r.cancelledBy!==null||await this.#f(r,n===null?"desired_state_run_absent":"desired_state_runid_mismatch"),Oe);let i=this.#t.getActiveInstance();return n===null?(i!==null&&await this.dispose(i.runId,"desired_state_run_absent"),Oe):i!==null?i.runId===n.runId?(await this.#s.apply(i.runId,i.deadlineAt,Bl(n)),await this.#c.apply(i.runId,jl(n)),Oe):(await this.dispose(i.runId,"desired_state_runid_mismatch"),Oe):this.#n.hasVerdictFor(n.runId)?Oe:n.phase==="queued"?this.#o===n.runId?(be.info("Not re-claiming a run this agent has already attempted (one-shot CAS)",{runId:n.runId}),{kind:"claim_issued",runId:n.runId,claimAnswer:null}):(this.#o=n.runId,this.#p(n.runId),Oe):(await this.#w(n.runId,n.phase),Oe)}async cancelLaunchAndSettle(e){let n=this.#l;return n===null?null:(be.warn("Stopping a launch that is still in flight",{runId:n.runId,trigger:e}),n.cancelledBy=e,this.#r(()=>this.dispose(n.runId,e)),await n.settled,n.runId)}async handleIdentityInstanceLost(e){await this.#s.handleLost(e)}async handleLaunchInstanceLost(e){await this.#c.handleLost(e)}async handleInstanceLost(e){be.error("The runtime reported a lost browser instance",{...e}),await this.#h(e.runId,"browser_gone",`the browser instance disappeared (${e.source})`,"browser_gone")}async dispose(e,n){this.stopMonitor(),this.#s.forgetJob(n==="max_duration"?e:void 0),this.#c.forgetJob();try{let r=await this.#t.disposeRun(e);be.info("Instance disposed",{runId:e,trigger:n,disposeOutcome:r.outcome,instanceReleased:r.instanceReleased,kill:r.kill,durationMs:r.durationMs})}catch(r){be.error("Dispose finished with a failed cleanup step",{runId:e,trigger:n,err:r instanceof Error?r.message:String(r)})}}stopMonitor(){this.#a?.stop(),this.#a=null}#p(e){let n=ng(e);this.#l=n,this.#m(n)}async#m(e){try{let n=await this.#d(e);await this.#r(()=>this.#g(e,n))}finally{e.markSettled()}}async#d(e){try{return{kind:"outcome",outcome:await Fl({client:this.#e,runtime:this.#t,runId:e.runId,onClaimAnswered:e.markClaimAnswered})}}catch(n){return{kind:"thrown",error:n}}}async#g(e,n){if(this.#l===e&&(this.#l=null),n.kind==="thrown")throw n.error;let r=n.outcome;switch(r.kind){case"launched":if(e.cancelledBy!==null){be.warn("A cancelled launch completed anyway \u2014 disposing what it brought up",{runId:e.runId,trigger:e.cancelledBy}),await this.dispose(e.runId,e.cancelledBy);return}this.#y(r.instance.runId,r.instance.deadlineAt),this.#u?.runId===r.instance.runId&&(await this.#s.apply(r.instance.runId,r.instance.deadlineAt,this.#u.identityIds),await this.#c.apply(r.instance.runId,this.#u.launchIds));return;case"claim_refused":case"claim_unavailable":case"instance_lost_immediately":return;case"failed":if(await this.dispose(e.runId,"launch_failure"),e.cancelledBy!==null){be.info("A cancelled launch failed on the way down \u2014 no verdict is sent",{runId:e.runId,trigger:e.cancelledBy,suppressedReason:r.body.reason});return}await this.#n.report({runId:e.runId,body:r.body});return}}async#f(e,n){be.warn("The desired state withdrew a run that is still launching \u2014 disposing",{runId:e.runId,trigger:n}),e.cancelledBy=n,await this.dispose(e.runId,n)}#y(e,n){this.#a=new Vt({runId:e,identityId:null,deadlineAt:n,probe:o(()=>this.#t.probePlaybackSession(),"probe"),onBrowserGone:o(r=>{this.#r(()=>this.#h(e,"browser_gone",r,"browser_gone"))},"onBrowserGone"),onDeadline:o(()=>{this.#r(()=>this.#h(e,"max_duration","the run reached its server-authored deadline","max_duration"))},"onDeadline")}),this.#a.start()}async#w(e,n){let r=this.#i.has(e),i=r?"browser_gone":"launch_error";be.error("The server publishes a run this agent is not carrying \u2014 reporting it",{runId:e,phase:n,sweptAtStartup:r,reason:i}),await this.#n.report({runId:e,body:{reason:i,message:r?"a leftover browser instance for this run was killed by the agent startup sweep":"this agent holds no browser instance for the run"}})}async#h(e,n,r,i){await this.dispose(e,i),await this.#n.report({runId:e,body:{reason:n,message:r}})}};function Bl(t){return t.identities===void 0?[]:t.identities.map(e=>e.identityId)}o(Bl,"identityIdsOf");function jl(t){return t.launches===void 0?[]:t.launches.map(e=>e.launchId)}o(jl,"launchIdsOf");function vi(t,e){return t!==78?t:e==="linux"?78:0}o(vi,"serviceExitCode");var Wl="Create a new enrollment code in Progon (Settings \u2192 Agents) and run 'progon-agent enroll <code>' to enroll this machine again. The wipe removed the state file, so an installed package now takes the deployment it was built for; on a source checkout add --server <url>.",Hl={revoked:{exitCode:78,level:"error",message:"progon-agent stopped: this agent was revoked and its credential has been wiped. "+Wl},reenroll_required:{exitCode:78,level:"error",message:"progon-agent stopped: this machine's agent token was superseded and the server no longer accepts it, so the credential has been wiped. This is not a revocation \u2014 the token was replaced and the replacement could not be kept. "+Wl},credential_unusable:{exitCode:78,level:"error",message:"progon-agent stopped: the server no longer accepts the agent token this daemon was given in PROGON_AGENT_TOKEN, and a credential the operator owns is not one this daemon can replace. NOTHING WAS WIPED \u2014 the state directory belongs to an enrollment this mode never reads and may still be perfectly valid. Set PROGON_AGENT_TOKEN to a current token and start the daemon again, or unset it and enroll this machine so the daemon can rotate on its own."},upgrade_required:{exitCode:78,level:"error",message:"progon-agent stopped: the server no longer accepts this version of the agent. The line before names the minimum. Update with 'progon-agent update' and start again. Nothing was wiped: this machine stays enrolled."},fatal:{exitCode:1,level:"error",message:"progon-agent stopped: the desired-state poll was refused definitively and no repetition can change that answer, so the daemon has disposed its browser and stopped instead of live-locking. The preceding error line names the reason and the server's own message. Restarting is the process supervisor's call once that condition has been fixed."},stopped:{exitCode:null,level:"info",message:"progon-agent stopped"}},Kl={revoked:"agent_revoked",reenroll_required:"agent_superseded",credential_unusable:"agent_superseded",upgrade_required:"shutdown",fatal:"shutdown",stopped:"shutdown"};var H=w("token-rotation"),Jl=1440*60*1e3,qt=class{static{o(this,"TokenRotationCoordinator")}#e;#t;#n;#r=null;#i=!1;#a=!1;constructor(e){this.#e=e.client,this.#t=e.stateDir,this.#n=e.identitySource}async runCycle(e){let n=this.#r;if(n!==null)return n;let r=this.#l(e);this.#r=r;try{return await r}finally{this.#r=null}}get canDiagnoseFromTheWire(){return this.#n!=="env_token"}async diagnoseSuperseded(e){if(this.#n==="env_token")return H.error("The agent token in PROGON_AGENT_TOKEN has been superseded and the server no longer accepts it. This daemon owns no copy of it and will not touch the state directory: set PROGON_AGENT_TOKEN to a current token and restart, or unset it and enroll this machine so the daemon can rotate on its own."),"alive";try{return await this.#e.getTokenRotationStatus({signal:e}),"alive"}catch(n){if(n instanceof O)return"reenroll_required";if(n instanceof T)throw n;if(n instanceof A)return H.warn("The superseded probe could not be answered \u2014 treating the credential as still usable, because only an explicit agents.token_superseded ends this identity",{operation:n.operation,err:n.message}),"alive";throw n}}async settle(){let e=this.#r;e!==null&&await e.then(()=>{},()=>{})}async#l(e){if(this.#n==="one_shot")return{kind:"unsupported_one_shot"};if(this.#n==="env_token")return this.#i||(this.#i=!0,H.warn("Agent token rotation is not available: this daemon runs on PROGON_AGENT_TOKEN, so the operator owns the credential and there is nowhere to persist a replacement. Rotate it by setting PROGON_AGENT_TOKEN to a new token and restarting, or enroll this machine so the daemon can rotate on its own.")),{kind:"unsupported_env_token"};if(this.#a)return{kind:"superseded_in_grace"};let n=this.#g();if(n.kind!=="identity")return this.#f(n);let r=n.identity,i=await this.#o(e);return i.kind!=="status"?i.outcome:i.value.rotationDue?await this.#c(r,i.value.tokenRotatedAt,e):this.#s(r,i.value.tokenRotatedAt)}async#o(e){try{return{kind:"status",value:e===void 0?await this.#e.getTokenRotationStatus():await this.#e.getTokenRotationStatus({signal:e})}}catch(n){if(n instanceof O)return H.error("This agent token has been superseded and no longer authenticates \u2014 the token family is dead and this machine must be enrolled again"),{kind:"outcome",outcome:{kind:"reenroll_required"}};if(n instanceof T)throw n;if(n instanceof A)return H.warn("The rotation status check failed \u2014 retrying on the next scheduled cycle",{operation:n.operation,err:n.message}),{kind:"outcome",outcome:{kind:"status_unavailable"}};throw n}}#s(e,n){return e.tokenRotatedAt===n?{kind:"not_due"}:e.tokenRotatedAt===null?(this.#d({...e,tokenRotatedAt:n},"first observed rotation marker"),{kind:"not_due"}):(this.#a=!0,H.error("The server reports a newer generation of this agent token than this daemon holds \u2014 either a rotation response was lost before it could be persisted, or another process rotated this identity. The current token keeps working until the server closes its rotation grace window; after that this machine must be enrolled again. No further rotation will be attempted with the current credential.",{observedTokenRotatedAt:e.tokenRotatedAt,serverTokenRotatedAt:n}),{kind:"superseded_in_grace"})}async#c(e,n,r){let i;try{i=(await this.#e.rotateToken()).agentToken}catch(l){if(l instanceof T)throw l;if(l instanceof O)return await this.#u(r);if(l instanceof A)return H.warn("The rotation request produced no usable answer \u2014 probing what the server actually committed",{operation:l.operation,err:l.message}),await this.#p(n);throw l}this.#d({...e,agentToken:i,tokenRotatedAt:null},"rotated agent token"),this.#e.useAgentToken(i);let s=await this.#m();return s.kind==="reenroll_required"?s:(s.kind==="observed"&&this.#d({...e,agentToken:i,tokenRotatedAt:s.tokenRotatedAt},"rotation marker of the new agent token"),H.info("Agent token rotated"),{kind:"rotated"})}async#u(e){return await this.diagnoseSuperseded(e)==="reenroll_required"?{kind:"reenroll_required"}:(this.#a=!0,H.error("This agent token is no longer the current generation, so it could not be rotated. It still authenticates for now \u2014 the server closes its rotation grace window shortly after, and this machine must then be enrolled again. No further rotation will be attempted with the current credential."),{kind:"superseded_in_grace"})}async#p(e){let n=await this.#o(void 0);return n.kind!=="status"?n.outcome:n.value.tokenRotatedAt===e?(H.warn("The rotation request never reached the server \u2014 nothing was committed and the current token is unchanged. The next scheduled check will try again."),{kind:"not_committed"}):(this.#a=!0,H.error("The rotation was committed by the server but its response was lost, so the new token cannot be recovered \u2014 the server hands out the plaintext exactly once. The current token keeps working until the server closes its rotation grace window; after that this machine must be enrolled again.",{anchorTokenRotatedAt:e,serverTokenRotatedAt:n.value.tokenRotatedAt}),{kind:"superseded_in_grace"})}async#m(){let e=await this.#o(void 0);return e.kind==="status"?{kind:"observed",tokenRotatedAt:e.value.tokenRotatedAt}:e.outcome.kind==="reenroll_required"?{kind:"reenroll_required"}:(H.warn("The rotated token could not be confirmed against the server, so its generation marker was not recorded. The next scheduled check re-establishes it."),{kind:"unconfirmed"})}#d(e,n){try{return It(this.#t,e),!0}catch(r){return H.error(`The ${n} could not be written to the state directory. This process keeps using the credential it holds, but a restart would fall back to the token on disk, which the server will refuse once its rotation grace window closes. Fix the permissions on the state directory BEFORE restarting the daemon; if it has already been restarted, enroll this machine again.`,{stateDir:this.#t,err:r instanceof Error?r.message:String(r)}),!1}}#g(){let e;try{e=L(this.#t)}catch(n){return{kind:"unreadable",err:n instanceof Error?n.message:String(n)}}return e===null?{kind:"absent"}:{kind:"identity",identity:e}}#f(e){return e.kind==="unreadable"?(H.error("The agent identity in the state directory cannot be read, so the credential this daemon is running on can neither be rotated nor replaced. The daemon keeps working on the token it holds in memory and will look again on the next scheduled check \u2014 restore the state directory from a backup, or enroll this machine again before restarting the daemon.",{stateDir:this.#t,identitySource:this.#n,err:e.err}),{kind:"identity_unavailable"}):(H.error("The agent identity is no longer in the state directory, so the credential this daemon is running on can neither be rotated nor replaced. The daemon keeps working on the token it holds in memory and will look again on the next scheduled check \u2014 restore the state directory, or enroll this machine again before restarting the daemon.",{stateDir:this.#t,identitySource:this.#n}),{kind:"identity_unavailable"})}};var B=w("run-supervisor"),qr=o(()=>Promise.resolve(),"noVerdictOwed"),Yr=class{static{o(this,"RunSupervisor")}#e;#t;#n;#r=new Br;#i;#a;#l;#o=null;#s=0;#c=0;#u=!1;#p=new AbortController;#m=null;#d=!1;#g=!1;#f;#y=null;#w=null;constructor(e){this.#e=e.client,this.#i=e.stateDir,this.#a=e.pollWaitSec,this.#l=e.capabilitiesDeclared,this.#f=e.tokenRotation,this.#t=new jr(e.client),this.#p.signal.addEventListener("abort",()=>this.#$(),{once:!0});let n=e.createRuntime({onInstanceLost:o(r=>{this.#E(()=>this.#n.handleInstanceLost(r))},"onInstanceLost"),onIdentityInstanceLost:o(r=>{this.#E(()=>this.#n.handleIdentityInstanceLost(r))},"onIdentityInstanceLost"),onLaunchInstanceLost:o(r=>{this.#E(()=>this.#n.handleLaunchInstanceLost(r))},"onLaunchInstanceLost")});this.#n=new Vr({client:e.client,runtime:n,reporter:this.#t,detach:o(r=>this.#E(r),"detach")})}get activeRunId(){return this.#n.activeRunId}async run(){await this.#r.run(()=>this.#n.sweepAtStartup());let e=await this.#L();if(e!==null)return e;for(this.#x(),this.#l||await this.#P();!this.#u;){let n=this.#m;if(n!==null)return await this.#_(n),"revoked";if(this.#d)return await this.#k(),"reenroll_required";if(this.#g)return await this.#O(),"credential_unusable";try{await this.#r.run(()=>this.#t.retryPending());let r=await this.#U();this.#s=0;let i=await this.#r.run(()=>this.#n.reconcile(r));await this.#M(i)}catch(r){if(r instanceof T)return await this.#_(r),"revoked";if(r instanceof O&&await this.#I(r))return await this.#k(),"reenroll_required";if(this.#u)break;if(this.#v())continue;let i=await this.#j(r);if(i!==null)return i==="credential_unusable"?await this.#O():i==="upgrade_required"?await this.#F():await this.#B(),i}}return this.#h()}async#h(){let e=this.#w;if(e===null)throw new Error("run-supervisor: the loop ended as stopped, but no shutdown() was ever started");return await e,"stopped"}async#P(){try{await this.#e.declareCapabilities({signal:this.#p.signal})}catch(e){if(await this.#C(e),this.#v())return;if(!(e instanceof A))throw e;B.error("Could not declare capabilities \u2014 job kinds this build supports will not be published to this agent until the next start; playback is unaffected",{err:e.message})}}async shutdown(e){let n=this.#w;if(n!==null)return B.info("A shutdown is already in progress \u2014 joining it",{cause:e}),n;let r=this.#N(e);return this.#w=r,r}async#N(e){B.info("Shutting down",{cause:e}),await this.#S(e==="fatal"?"fatal":"stopped",n=>this.#T(n))}async#S(e,n){this.#u=!0,this.#o?.abort(),this.#p.abort();let r=Kl[e],i=await this.#n.cancelLaunchAndSettle(r);await this.#r.run(async()=>{this.#n.stopMonitor();let s=this.#n.activeRunId;s!==null&&await this.#n.dispose(s,r),await n({activeRunId:s,launchingRunId:i})}),await this.#f.settle()}async#T(e){let{activeRunId:n,launchingRunId:r}=e;if(n!==null){await this.#R(()=>this.#t.report({runId:n,body:{reason:"browser_gone",message:Ei}}));return}if(r!==null){await this.#R(()=>this.#t.report({runId:r,body:{reason:"browser_gone",message:Ei}}));return}await this.#R(()=>this.#t.retryPending())}async#L(){try{if((await this.#f.runCycle(this.#p.signal)).kind!=="reenroll_required")return null}catch(e){if(e instanceof T)return await this.#_(e),"revoked";throw e}return await this.#k(),"reenroll_required"}#x(){if(this.#u||this.#p.signal.aborted)return;let e=setTimeout(()=>{this.#y=null,this.#D().finally(()=>{this.#x()})},Jl);e.unref(),this.#y=e}async#D(){try{if((await this.#f.runCycle(this.#p.signal)).kind!=="reenroll_required")return;this.#d=!0,this.#o?.abort()}catch(e){await this.#A(e)}}#$(){this.#y!==null&&(clearTimeout(this.#y),this.#y=null)}async#I(e){B.warn("A gateway call was refused as superseded \u2014 diagnosing the credential",{operation:e.operation});try{return await this.#f.diagnoseSuperseded(this.#p.signal)==="reenroll_required"}catch(n){if(n instanceof T)return this.#m=n,!1;throw n}}async#U(){let e=new AbortController;this.#o=e;try{return await this.#e.pollDesiredState({waitSec:this.#a,signal:e.signal})}finally{this.#o=null}}async#M(e){if(e.kind==="reconciled"){this.#c=0;return}await this.#G(e.runId,e.claimAnswer)}async#G(e,n){let r=ge(this.#c);B.info("The desired state still names a run whose claim this agent already issued \u2014 pausing before the next poll",{runId:e,attempt:this.#c,waitMs:r,claimOnTheWire:n!==null}),this.#c+=1;let i=new AbortController;if(this.#o=i,this.#p.signal.aborted||this.#v()){this.#o=null;return}n?.then(()=>i.abort());try{await oe(r,i.signal)}finally{this.#o=null}}async#b(){await this.#f.settle(),nr(this.#i)}async#_(e){B.error("This agent has been revoked \u2014 disposing, wiping the credential and stopping",{signal:e.signal}),await this.#S("revoked",qr),await this.#b()}async#O(){B.error("The server refuses the credential this daemon runs on as superseded, and this daemon has no way to replace it \u2014 disposing the browser and stopping so the operator, and the process supervisor, both learn it now. The state directory is left untouched: this credential did not come from there."),await this.#S("credential_unusable",qr)}async#F(){await this.#S("upgrade_required",qr)}async#B(){await this.#S("fatal",e=>this.#T(e))}async#k(){B.error("This agent token has been superseded and its family is no longer accepted \u2014 disposing, wiping the credential and stopping"),await this.#S("reenroll_required",qr),await this.#b()}async#j(e){if(!(e instanceof A))throw e;let n=this.#W(e);return n.kind==="exit"?n.exit:(this.#s+=1,await oe(n.delayMs,this.#p.signal),null)}#W(e){if(e instanceof ee)return B.error("The server refuses this version of the agent \u2014 disposing the browser and stopping",{operation:e.operation,err:e.message}),{kind:"exit",exit:"upgrade_required"};if(e instanceof O){if(!this.#f.canDiagnoseFromTheWire)return{kind:"exit",exit:"credential_unusable"};let r=ge(this.#s);return B.error("The server refused this credential as superseded, but the probe did not confirm the token family is dead \u2014 the daemon keeps polling on the credential it holds. If this repeats, create a new enrollment code in Progon (Settings \u2192 Agents) and enroll this machine again.",{operation:e.operation,attempt:this.#s,retryInMs:r}),{kind:"retry",delayMs:r}}let n=Be({attempt:this.#s,error:e});return n.retry?(B.warn("Desired-state poll failed \u2014 backing off",{attempt:this.#s,retryInMs:n.delayMs,err:e.message}),{kind:"retry",delayMs:n.delayMs}):(B.error("The desired-state poll was refused definitively and no repetition can change that \u2014 the daemon cannot reconcile without a snapshot, so it is disposing its browser and stopping. Restart duty belongs to the process supervisor.",{reason:n.reason,operation:e.operation,err:e.message}),{kind:"exit",exit:"fatal"})}#E(e){return this.#r.run(e).catch(n=>this.#A(n))}async#A(e){await this.#C(e)||B.error("A background supervisor action failed",{err:e instanceof Error?e.message:String(e)})}async#C(e){if(e instanceof T)return this.#m=e,this.#o?.abort(),!0;if(!(e instanceof O))return!1;try{await this.#I(e)?this.#d=!0:this.#f.canDiagnoseFromTheWire||(this.#g=!0)}catch(n){return B.error("The superseded diagnosis failed after a gateway refusal off the poll",{operation:e.operation,err:n instanceof Error?n.message:String(n)}),!0}return this.#v()&&this.#o?.abort(),!0}#v(){return this.#m!==null||this.#d||this.#g}async#R(e){try{await e()}catch(n){if(n instanceof O){B.error("This agent token is no longer accepted as current, so the run could not be reported. The credential on disk is left alone \u2014 the next start diagnoses it and will say whether this machine has to be enrolled again.",{operation:n.operation});return}if(n instanceof T){await this.#b(),B.error("This agent was revoked, so the run could not be reported and the credential has been wiped. Create a new enrollment code in Progon (Settings \u2192 Agents) and start the daemon once with PROGON_AGENT_ENROLL_CODE=<code> to enroll this machine again.",{signal:n.signal});return}throw n}}};var Vl=w("supervisor-boot");async function ql(t){t?.throwIfAborted();let e=Me();Vl.info("Config loaded",{serverUrlOrigin:new URL(e.serverUrl).origin,serverUrlSource:e.serverUrlSource,stateDir:e.stateDir,headfulOverride:e.headfulOverride,allowInsecureHttps:e.allowInsecureHttps,disableBrowserSandbox:e.disableBrowserSandbox});let n=Ke(),r=await Fr({config:e,machine:n,signal:t});t?.throwIfAborted(),Vl.info("Agent identity resolved",{source:r.source,agentId:r.agentId,hostname:n.hostname,platform:n.platform,arch:n.arch,agentVersion:n.agentVersion});let i=Rr({overridePath:e.extensionDistOverride,stateDir:e.stateDir,agentId:r.agentId});await Or({disableBrowserSandbox:e.disableBrowserSandbox,signal:t}),t?.throwIfAborted();let s=new Ge({serverUrl:e.serverUrl,agentToken:r.agentToken}),l=new qt({client:s,stateDir:e.stateDir,identitySource:r.source});return bi({client:s,stateDir:e.stateDir,pollWaitSec:r.pollWaitSec,tokenRotation:l,extensionDist:i,browserEnv:e,capabilitiesDeclared:!1})}o(ql,"bootRunSupervisor");function bi(t){let{client:e,stateDir:n,pollWaitSec:r,tokenRotation:i,extensionDist:s,browserEnv:l}=t;return new Yr({client:e,stateDir:n,pollWaitSec:r,tokenRotation:i,capabilitiesDeclared:t.capabilitiesDeclared,createRuntime:o(({onInstanceLost:c,onIdentityInstanceLost:a,onLaunchInstanceLost:d})=>new Gr({stateDir:n,extensionDist:s,headfulOverride:l.headfulOverride,allowInsecureHttps:l.allowInsecureHttps,disableBrowserSandbox:l.disableBrowserSandbox,onInstanceLost:c,onIdentityInstanceLost:a,onLaunchInstanceLost:d}),"createRuntime")})}o(bi,"wireRunSupervisor");import{z as Rn}from"zod";var rg="scenario_launches.scenarios_not_launchable",og=Rn.object({items:Rn.array(Rn.object({scenarioId:Rn.string(),notStartedReason:Rn.string()}))});function Yl(t){if(t.errorCode!==rg)return[];let e=og.safeParse(t.params);return e.success?e.data.items.map(n=>` NOT STARTED scenario ${n.scenarioId} - ${n.notStartedReason}`):["Progon did not say which scenarios cannot start."]}o(Yl,"refusedScenarioLines");import{stripVTControlCharacters as dg}from"node:util";import{appendFileSync as ig,statSync as sg}from"node:fs";var ag=1024*1024,Xl=`
|
|
99
|
+
`+n)}o(Ll,"assertEnrollmentCodeWasRedeemed");function Gh(t,e){if(!Ue(t,e))throw new p(`[progon-agent] The persisted agent credential was enrolled against ${t}, but PROGON_SERVER_URL is ${e}. A pgat_ token is meaningless at a different deployment (CONTRACT-la \xA78), so the daemon refuses to authenticate blind.
|
|
100
|
+
Either point PROGON_SERVER_URL back at ${t} \u2014 or unset it entirely, since an enrolled machine reads the server from its own state file (CONTRACT-la \xA78) \u2014 or move this machine to ${e}: run 'progon-agent enroll <code> --server ${e}' in a terminal, which offers to reset this enrollment (revoking it on ${t}) first. To keep BOTH, enroll the second one under its own PROGON_RUNNER_STATE_DIR rather than replacing this credential.`)}o(Gh,"assertServerMatchesEnrollment");import{hostname as Fh}from"node:os";var Dl=["darwin","linux","win32"],$l=["x64","arm64"];function Bh(t){return Dl.includes(t)}o(Bh,"isSupportedPlatform");function jh(t){return $l.includes(t)}o(jh,"isSupportedArch");function Je(){let t=process.platform;if(!Bh(t))throw new Error(`[supervisor] Unsupported platform ${JSON.stringify(t)}. The local agent runs on ${Dl.join(", ")} (CONTRACT-la \xA75.1, \xA710.3).`);let e=process.arch;if(!jh(e))throw new Error(`[supervisor] Unsupported CPU architecture ${JSON.stringify(e)}. The local agent runs on ${$l.join(", ")} (CONTRACT-la \xA75.1).`);let n=Fh();if(n==="")throw new Error("[supervisor] os.hostname() returned an empty string, so this machine cannot be named on the enroll wire (CONTRACT-la \xA75.1 requires a non-empty hostname). Fix the host's network configuration.");return{hostname:n,platform:t,arch:e,agentVersion:te()}}o(Je,"describeAgentMachine");var Ul=o(()=>{},"noop"),Br=class{static{o(this,"ActionQueue")}#e=Promise.resolve();run(e){let n=this.#e.then(e,e);return this.#e=n.then(Ul,Ul),n}};var Ml=w("supervisor-deadline"),Rn=class extends Error{static{o(this,"DeadlineExceededError")}operation;timeoutMs;constructor(e,n){super(`[supervisor] ${e} did not settle within ${n}ms`),this.name="DeadlineExceededError",this.operation=e,this.timeoutMs=n}};async function Ke(t){let e=t.work(),n=!1;e.then(()=>{n&&Ml.warn("Abandoned work settled successfully after its deadline had passed",{operation:t.operation,timeoutMs:t.timeoutMs})},s=>{n&&Ml.warn("Abandoned work rejected after its deadline had passed",{operation:t.operation,timeoutMs:t.timeoutMs,err:s instanceof Error?s.message:String(s)})});let r,i=new Promise((s,l)=>{r=setTimeout(()=>{n=!0,l(new Rn(t.operation,t.timeoutMs))},t.timeoutMs)});try{return await Promise.race([e,i])}finally{r!==void 0&&clearTimeout(r)}}o(Ke,"withDeadline");function oe(t,e){return new Promise(n=>{if(e.aborted){n();return}let r=setTimeout(()=>{e.removeEventListener("abort",i),n()},t);function i(){clearTimeout(r),n()}o(i,"onAbort"),e.addEventListener("abort",i,{once:!0})})}o(oe,"sleep");var Ve=w("fail-reporter"),jr=class{static{o(this,"RunFailureReporter")}#e;#t=null;#n=null;constructor(e){this.#e=e}hasVerdictFor(e){return this.#n===e}async report(e){if(this.#n===e.runId){Ve.warn("Ignoring a second terminal verdict for a run this agent already reported",{runId:e.runId,ignoredReason:e.body.reason,stillUndelivered:this.#t!==null});return}let n=this.#t;n!==null&&n.runId!==e.runId&&Ve.warn("Dropping an undelivered fail verdict \u2014 a different run needs one now",{droppedRunId:n.runId,droppedReason:n.body.reason,runId:e.runId}),this.#t={...e,attempt:0,nextAttemptAtMs:0},this.#n=e.runId,Ve.error("Reporting run failure to the gateway",{runId:e.runId,...e.body}),await this.#r()}async retryPending(){let e=this.#t;e!==null&&(Date.now()<e.nextAttemptAtMs||await this.#r())}discardIfNotPublished(e){let n=this.#t;n!==null&&n.runId!==e&&(Ve.info("Undelivered fail verdict discarded \u2014 its run is already terminal server-side",{runId:n.runId,reason:n.body.reason,publishedRunId:e}),this.#t=null)}async#r(){let e=this.#t;if(e!==null)try{let n=await this.#e.failRun(e.runId,e.body);Ve.info("Fail verdict delivered",{runId:e.runId,reason:e.body.reason,status:n.status,attempts:e.attempt+1}),this.#t=null}catch(n){if(n instanceof T)throw n;if(n instanceof O)throw Ve.error("Fail verdict abandoned \u2014 the gateway no longer accepts this credential as current",{runId:e.runId,reason:e.body.reason,err:n.message}),this.#t=null,n;if(!(n instanceof A))throw n;let r=Be({attempt:e.attempt,error:n});if(!r.retry){Ve.error("Fail verdict abandoned \u2014 the gateway refused it definitively",{runId:e.runId,reason:e.body.reason,noRetryReason:r.reason,err:n.message}),this.#t=null;return}this.#t={runId:e.runId,body:e.body,attempt:e.attempt+1,nextAttemptAtMs:Date.now()+r.delayMs},Ve.warn("Fail verdict not delivered \u2014 held for retry",{runId:e.runId,reason:e.body.reason,attempt:e.attempt+1,retryInMs:r.delayMs,err:n.message})}}};var Wr=120,Jt=Wr*1e3,yi=3e4,Kt=3,wi=45*1e3,Si="agent shutdown";var Hr=w("task-launch-reconciler"),Jr=class{static{o(this,"TaskLaunchReconciler")}#e;#t=null;constructor(e){this.#e=e}async apply(e,n){let r=this.#t;(r===null||r.jobId!==e)&&(r={jobId:e,desired:new Set,attempted:new Set,closing:new Set},this.#t=r),r.desired=new Set(n);for(let i of this.#e.runtime.launchIdsWithInstance())r.desired.has(i)||r.closing.has(i)||this.#r(r,i);for(let i of r.desired)r.attempted.has(i)||(r.attempted.add(i),this.#n(r,i))}forgetJob(){this.#t=null}async handleLost(e){Hr.warn("Verification browser lost; its launch lease will end it, no restart or job fail",{...e})}async#n(e,n){let r=null;try{let i=await this.#e.client.issueLaunchSession(e.jobId,n);if(this.#t!==e||!e.desired.has(n))return;try{await Ke({operation:`startLaunchInstance(${e.jobId}, ${n})`,timeoutMs:Jt,work:o(()=>this.#e.runtime.startLaunchInstance(e.jobId,n,i),"work")})}catch(s){r={stage:"launch",error:s}}}catch(i){r={stage:"session",error:i}}finally{await this.#e.detach(async()=>{if(r!==null){if(Hr.error("Verification browser could not start; the first-claim deadline ends its launch",{runId:e.jobId,launchId:n,stage:r.stage,err:r.error instanceof Error?r.error.message:String(r.error)}),r.stage==="launch"&&await this.#i(e,n),r.error instanceof T||r.error instanceof O)throw r.error;return}(this.#t!==e||!e.desired.has(n))&&await this.#i(e,n)})}}#r(e,n){e.closing.add(n),this.#i(e,n).finally(()=>{this.#e.detach(async()=>{e.closing.delete(n)})})}async#i(e,n){try{let r=await this.#e.runtime.disposeLaunchInstance(e.jobId,n);r!==null&&Hr.info("Verification browser disposed",{runId:e.jobId,launchId:n,disposeOutcome:r.outcome,instanceReleased:r.instanceReleased})}catch(r){Hr.error("Verification browser cleanup failed",{runId:e.jobId,launchId:n,err:r instanceof Error?r.message:String(r)})}}};var Vt=w("run-monitor");function Hh(t,e){let n=Date.now();return e.ok?e.tabs.some(i=>i.playback!==null&&i.playback.runId===t)?{healthy:!0}:Jh(t,e.agentJob,n)?{healthy:!0}:{healthy:!1,reason:"playback_absent",detail:`the extension answered but nothing it holds describes a live run of ours (${Kh(e.tabs)}; ${Vh(e.agentJob,n)})`}:{healthy:!1,reason:e.reason,detail:e.detail}}o(Hh,"judgeProbe");function Jh(t,e,n){if(e===null||e.agentJobId!==t||e.updatedAt===null)return!1;let r=Date.parse(e.updatedAt);return Number.isNaN(r)?!1:n-r<=wi}o(Jh,"isJobPulseStanding");function Kh(t){if(t.length===0)return"tabStates is empty";let e=t.map(n=>n.playback===null?"none":n.playback.runId);return`${t.length} tab(s), playback run ids: ${e.join(", ")}`}o(Kh,"describeTabs");function Vh(t,e){if(t===null)return"no job pulse is standing";if(t.updatedAt===null)return`job pulse: agentJobId=${t.agentJobId??"unreadable"}, updatedAt=unreadable`;let n=Date.parse(t.updatedAt),r=Number.isNaN(n)?"unparsable":`${String(e-n)}ms old`;return`job pulse: agentJobId=${t.agentJobId??"unreadable"}, ${r} (stale past ${String(wi)}ms)`}o(Vh,"describeJobMarker");var qt=class{static{o(this,"RunMonitor")}#e;#t;#n=null;#r=null;#i=0;#a=!1;constructor(e){this.#e=e;let n=Date.parse(e.deadlineAt);if(Number.isNaN(n))throw new Error(`[run-monitor] run ${e.runId} has an unparseable deadlineAt ${JSON.stringify(e.deadlineAt)} \u2014 the run deadline (CONTRACT-la \xA715 A7) cannot be armed.`);this.#t=n}get runId(){return this.#e.runId}start(){let e=Math.max(0,this.#t-Date.now());Vt.info("Monitoring launched run",{runId:this.#e.runId,identityId:this.#e.identityId,deadlineAt:this.#e.deadlineAt,deadlineInMs:e,probeIntervalMs:yi,probeStrikeLimit:Kt});let n=this.#e.probe;n!==null&&(this.#n=setInterval(()=>{this.#s(n)},yi),this.#n.unref());let r=this.#e;r.identityId===null&&(this.#r=setTimeout(()=>{this.#a||(this.stop(),Vt.error("Run reached its server-authored deadline",{runId:this.#e.runId,identityId:this.#e.identityId,deadlineAt:this.#e.deadlineAt}),r.onDeadline())},e),this.#r.unref())}stop(){this.#a=!0,this.#n!==null&&(clearInterval(this.#n),this.#n=null),this.#r!==null&&(clearTimeout(this.#r),this.#r=null)}async#s(e){if(this.#a)return;let n=await this.#o(e);if(this.#a)return;let r=n.ok?n.detachedIdentity:void 0;if(this.#e.identityId!==null&&r?.agentJobId===this.#e.runId&&r.identityId===this.#e.identityId){this.stop(),this.#e.onIdentityDetached();return}let i=Hh(this.#e.runId,n);if(i.healthy){this.#i>0&&Vt.info("Liveness probe recovered",{runId:this.#e.runId,identityId:this.#e.identityId,clearedStrikes:this.#i}),this.#i=0;return}this.#i+=1;let s=`${i.reason}: ${i.detail}`;Vt.warn("Liveness probe failed",{runId:this.#e.runId,identityId:this.#e.identityId,strike:this.#i,strikeLimit:Kt,reason:i.reason,detail:i.detail}),!(this.#i<Kt)&&(this.stop(),Vt.error("Liveness probe failed the strike limit \u2014 the browser is gone",{runId:this.#e.runId,identityId:this.#e.identityId,strikes:Kt,detail:s}),this.#e.onBrowserGone(`${Kt} consecutive liveness probes failed (${s})`))}async#o(e){try{return await e()}catch(n){let r=n instanceof Error?n.message:String(n);return Vt.error("Liveness probe threw instead of reporting an observation",{runId:this.#e.runId,identityId:this.#e.identityId,err:r}),{ok:!1,observedAt:new Date().toISOString(),reason:"evaluate_failed",detail:r}}}};var ve=w("identity-reconciler"),Kr=class{static{o(this,"IdentityReconciler")}#e;#t;#n;#r=null;constructor(e){this.#e=e.runtime,this.#t=e.client,this.#n=e.detach}async apply(e,n,r){let i=this.#r;(i===null||i.jobId!==e)&&(this.forgetJob(),i={jobId:e,deadlineAt:n,desired:new Set,launching:new Set,closing:new Set,monitors:new Map},this.#r=i);let s=new Set(r),l=s.size!==i.desired.size||[...s].some(c=>!i.desired.has(c));i.desired=s,l&&ve.info("Identities of the task job changed",{runId:e,identityIds:[...s],identityIdsWithInstance:this.#e.identityIdsWithInstance()});for(let c of this.#e.identityIdsWithInstance())s.has(c)||i.launching.has(c)||this.#c(i,c,"identity_left_run_block");for(let c of s)i.launching.has(c)||i.closing.has(c)||this.#e.identityIdsWithInstance().includes(c)||this.#i(i,c)}forgetJob(e){let n=this.#r;if(n!==null){if(n.jobId===e){let r=this.#e.identityIdsWithInstance().filter(i=>n.monitors.has(i)||n.launching.has(i));r.length>0&&ve.error("Job deadline reached with identity journal and capture delivery unconfirmed",{event:"runner.identity_delivery_timeout",runId:n.jobId,identityIds:r,deadlineAt:n.deadlineAt})}for(let r of n.monitors.values())r.stop();n.monitors.clear(),this.#r=null}}async handleLost(e){let n=this.#r;if(n===null||n.jobId!==e.jobId){ve.info("An identity instance of a finished job went away \u2014 nothing to relaunch",{...e});return}this.#m(n,e.identityId),this.#u(n,e.identityId,`the instance disappeared (${e.source})`)}#i(e,n){e.launching.add(n),this.#a(e,n)}async#a(e,n){let r=null;try{let i=await this.#t.issueIdentitySession(e.jobId,n);try{await Ke({operation:`startIdentityInstance(${e.jobId}, ${n})`,timeoutMs:Jt,work:o(()=>this.#e.startIdentityInstance(e.jobId,n,i),"work")})}catch(s){r={stage:"launch",err:s}}}catch(i){r={stage:"session",err:i}}await this.#n(()=>this.#s(e,n,r))}async#s(e,n,r){e.launching.delete(n);let i=this.#r===e;if(r!==null){if(ve.error("The instance of an identity could not be launched \u2014 no fail is reported",{runId:e.jobId,identityId:n,stage:r.stage,jobStillRunning:i,stillInRunBlock:e.desired.has(n),err:r.err instanceof Error?r.err.message:String(r.err)}),r.stage==="session"){if(r.err instanceof T||r.err instanceof O)throw r.err;return}await this.#d(e,n,"launch_failure");return}if(!i){await this.#d(e,n,"job_gone");return}if(!e.desired.has(n)){this.#c(e,n,"identity_left_run_block");return}this.#o(e,n)}#o(e,n){let r=new qt({runId:e.jobId,identityId:n,deadlineAt:e.deadlineAt,probe:o(()=>this.#e.probeIdentityInstance(n),"probe"),onBrowserGone:o(i=>{this.#n(()=>this.#l(e,n,i))},"onBrowserGone"),onIdentityDetached:o(()=>{this.#n(async()=>{this.#r!==e||e.monitors.get(n)!==r||this.#c(e,n,"identity_detached")})},"onIdentityDetached")});e.monitors.set(n,r),r.start(),ve.info("Identity instance is up and monitored",{runId:e.jobId,identityId:n})}async#l(e,n,r){this.#r===e&&(e.monitors.delete(n),ve.error("An identity instance lost its identity \u2014 closing it, no fail is reported",{runId:e.jobId,identityId:n,detail:r}),await this.#d(e,n,"pulse_lost"),this.#u(e,n,r))}#u(e,n,r){if(this.#r===e){if(!e.desired.has(n)){ve.info("A lost identity instance is not relaunched \u2014 the identity left the run block",{runId:e.jobId,identityId:n,cause:r});return}e.launching.has(n)||e.closing.has(n)||(ve.warn("Relaunching the instance of an identity that is still in the run block",{runId:e.jobId,identityId:n,cause:r}),this.#i(e,n))}}#c(e,n,r){e.closing.has(n)||(e.closing.add(n),this.#m(e,n),this.#p(e,n,r))}async#p(e,n,r){await this.#d(e,n,r),await this.#n(async()=>{e.closing.delete(n),this.#u(e,n,"the departed instance finished closing")})}#m(e,n){e.monitors.get(n)?.stop(),e.monitors.delete(n)}async#d(e,n,r){try{let i=await this.#e.disposeIdentityInstance(e.jobId,n);if(i===null)return;ve.info("Identity instance disposed",{runId:e.jobId,identityId:n,trigger:r,disposeOutcome:i.outcome,instanceReleased:i.instanceReleased,durationMs:i.durationMs})}catch(i){ve.error("Identity instance dispose finished with a failed cleanup step",{runId:e.jobId,identityId:n,trigger:r,err:i instanceof Error?i.message:String(i)})}}};var be=w("launch-run");async function Bl(t){let e;try{e=await qh(t)}finally{t.onClaimAnswered()}if(e.kind!=="claimed")return e;let n=Xh(e.payload);return n.command.kind==="swarm"?{kind:"task_claimed",request:n}:Ei(t.runtime,n)}o(Bl,"claimAndLaunch");async function qh(t){try{let e=await t.client.claimRun(t.runId);return be.info("Run claimed",Yh(e)),{kind:"claimed",payload:e}}catch(e){if(e instanceof T)throw e;if(e instanceof O)throw be.error("Claim refused as superseded \u2014 not launching, leaving it to the sweep",{runId:t.runId,err:e.message}),e;if(e instanceof Ct||e instanceof it)return be.info("Claim refused \u2014 the desired-state snapshot was stale, not launching",{runId:t.runId,err:e.message}),{kind:"claim_refused"};if(!(e instanceof A))throw e;return be.error("Claim produced no usable answer \u2014 not launching, leaving it to the sweep",{runId:t.runId,err:e.message}),{kind:"claim_unavailable"}}}o(qh,"claimRun");function Yh(t){if(!("kind"in t))return{kind:"playback",runId:t.runId,scenarioId:t.scenarioId,projectId:t.projectId,runPurpose:t.runPurpose,headful:t.headful,maxRunDurationSec:t.maxRunDurationSec};if(t.kind==="swarm")return{kind:t.kind,runId:t.runId,workflowId:t.command.workflowId,headful:t.headful,maxRunDurationSec:t.maxRunDurationSec};if(t.kind==="scenario_launch")return{kind:t.kind,runId:t.runId,projectId:t.command.projectId,launchId:t.command.launchId,headful:t.headful,maxRunDurationSec:t.maxRunDurationSec};if(t.kind==="conversation")return{kind:t.kind,runId:t.runId,conversationId:t.command.conversationId,headful:t.headful,maxRunDurationSec:t.maxRunDurationSec};let e=t;throw new Error(`Unexpected claim kind: ${JSON.stringify(e,["kind"])}`)}o(Yh,"describeClaim");function Xh(t){return{runId:t.runId,entryUrl:"kind"in t&&t.kind==="conversation"?null:t.entryUrl,headful:t.headful,maxRunDurationSec:t.maxRunDurationSec,extensionSession:t.extensionSession,command:t.command}}o(Xh,"launchRequestOf");async function Ei(t,e){try{await Ke({operation:`startRun(${e.runId})`,timeoutMs:Jt,work:o(()=>t.startRun(e),"work")})}catch(r){return{kind:"failed",body:Qh(e.runId,r)}}let n=t.getActiveInstance();return n===null||n.runId!==e.runId?(be.error("The launched instance was already gone when the supervisor read it back",{runId:e.runId,activeRunId:n===null?null:n.runId}),{kind:"instance_lost_immediately",runId:e.runId}):{kind:"launched",instance:n}}o(Ei,"launchClaimedRun");var Gl=500,Fl="\u2026";function zh(t){return t.length<=Gl?t:t.slice(0,Gl-Fl.length)+Fl}o(zh,"fitFailMessageToWire");function Qh(t,e){if(e instanceof je){let n=mi(e),r=e.stage==="browser_launch"?Rl(n)??n:n,i=zh(`stage ${e.stage}: ${r}`);if(e.stage==="entry_navigation"){let s=Tl(e);return be.error("Launch failed",{runId:t,stage:e.stage,failReason:e.failReason,entryFailure:s,err:e.message}),{reason:e.failReason,message:i,entryFailure:s}}return be.error("Launch failed",{runId:t,stage:e.stage,failReason:e.failReason,err:e.message}),{reason:e.failReason,message:i}}return e instanceof Rn?(be.error("Launch exceeded the agent-side launch deadline \u2014 disposing and failing",{runId:t,launchTimeoutSec:Wr,err:e.message}),{reason:"launch_error",message:`launch did not complete within ${Wr}s`}):e instanceof We?(be.error("Launch refused by the instance fence \u2014 the run cannot be started here",{runId:t,userDataDir:e.userDataDir,err:e.message}),{reason:"launch_error",message:"a leftover instance directory blocks this run"}):(be.error("Launch failed with an unexpected error class",{runId:t,errName:e instanceof Error?e.name:typeof e,err:e instanceof Error?e.message:String(e)}),{reason:"launch_error",message:"launch failed with an unexpected error"})}o(Qh,"describeLaunchFailure");var _e=w("instance-reconciler");function Zh(t){let e=o(()=>{},"markSettled"),n=new Promise(l=>{e=l}),r=o(()=>{},"resolveClaimAnswer"),i=new Promise(l=>{r=l}),s={runId:t,cancelledBy:null,claimAnswered:!1,claimAnswer:i,markClaimAnswered:o(()=>{s.claimAnswered=!0,r()},"markClaimAnswered"),settled:n,markSettled:e};return s}o(Zh,"createPendingLaunch");var ye={kind:"reconciled"},Vr=class{static{o(this,"InstanceReconciler")}#e;#t;#n;#r;#i=new Set;#a=null;#s=null;#o=null;#l=null;#u;#c;#p=null;constructor(e){this.#e=e.client,this.#t=e.runtime,this.#n=e.reporter,this.#r=e.detach,this.#c=new Jr(e),this.#u=new Kr({runtime:e.runtime,client:e.client,detach:e.detach})}get activeRunId(){return this.#o?.runId??this.#t.getActiveInstance()?.runId??null}async sweepAtStartup(){let e=await this.#t.sweepOrphanInstances();this.#i=new Set(e.outcomes.map(({runId:n})=>n.replace(/~.*$/,""))),_e.info("Startup sweep finished",{instancesRoot:e.instancesRoot,leftoverCount:e.outcomes.length,sweptRunIds:[...this.#i]})}async reconcile(e){let n=e.run;this.#n.discardIfNotPublished(n===null?null:n.runId),this.#p=n===null?null:{runId:n.runId,main:n.main===!0,identityIds:eg(n),launchIds:tg(n)};let r=this.#s;if(r!==null)return n!==null&&n.runId===r.runId?(await this.#h(),n.phase!=="queued"?ye:{kind:"claim_issued",runId:n.runId,claimAnswer:r.claimAnswered?null:r.claimAnswer}):(r.cancelledBy!==null||await this.#w(r,n===null?"desired_state_run_absent":"desired_state_runid_mismatch"),ye);let i=this.#o;if(i!==null)return n?.runId===i.runId?(await this.#h(),n.phase==="queued"?{kind:"claim_issued",runId:i.runId,claimAnswer:null}:ye):(await this.dispose(i.runId,n===null?"desired_state_run_absent":"desired_state_runid_mismatch"),ye);let s=this.#t.getActiveInstance();return n===null?(s!==null&&await this.dispose(s.runId,"desired_state_run_absent"),ye):s!==null?(s.runId===n.runId||await this.dispose(s.runId,"desired_state_runid_mismatch"),ye):this.#n.hasVerdictFor(n.runId)?ye:n.phase==="queued"?this.#l===n.runId?(_e.info("Not re-claiming a run this agent has already attempted (one-shot CAS)",{runId:n.runId}),{kind:"claim_issued",runId:n.runId,claimAnswer:null}):(this.#l=n.runId,this.#m(n.runId),ye):(await this.#v(n.runId,n.phase),ye)}async cancelLaunchAndSettle(e){let n=this.#s;return n===null?null:(_e.warn("Stopping a launch that is still in flight",{runId:n.runId,trigger:e}),n.cancelledBy=e,this.#r(()=>this.dispose(n.runId,e)),await n.settled,n.runId)}async handleIdentityInstanceLost(e){await this.#u.handleLost(e)}async handleLaunchInstanceLost(e){await this.#c.handleLost(e)}async handleInstanceLost(e){_e.error("The runtime reported a lost browser instance",{...e}),await this.#y(e.runId,"browser_gone",`the browser instance disappeared (${e.source})`,"browser_gone")}async dispose(e,n){this.stopMonitor(),this.#o?.runId===e&&(this.#o=null),this.#s?.runId===e&&(this.#s.cancelledBy??=n),this.#u.forgetJob(n==="max_duration"?e:void 0),this.#c.forgetJob();try{let r=await this.#t.disposeRun(e);_e.info("Instance disposed",{runId:e,trigger:n,disposeOutcome:r.outcome,instanceReleased:r.instanceReleased,kill:r.kill,durationMs:r.durationMs})}catch(r){_e.error("Dispose finished with a failed cleanup step",{runId:e,trigger:n,err:r instanceof Error?r.message:String(r)})}}stopMonitor(){this.#a?.stop(),this.#a=null}#m(e,n){let r=Zh(e);this.#s=r,n!==void 0&&r.markClaimAnswered();let i=n===void 0?()=>Bl({client:this.#e,runtime:this.#t,runId:e,onClaimAnswered:r.markClaimAnswered}):()=>Ei(this.#t,n);this.#d(r,i)}async#d(e,n){try{let r=await this.#g(n);await this.#r(()=>this.#f(e,r))}finally{e.markSettled()}}async#g(e){try{return{kind:"outcome",outcome:await e()}}catch(n){return{kind:"thrown",error:n}}}async#f(e,n){if(this.#s===e&&(this.#s=null),n.kind==="thrown")throw n.error;let r=n.outcome;switch(r.kind){case"task_claimed":{if(e.cancelledBy!==null)return;let i=this.#t.prepareTaskJob(r.request);this.#o={runId:e.runId,deadlineAt:i,mainRequest:r.request},this.#S(e.runId,i,!1),await this.#h();return}case"launched":if(e.cancelledBy!==null){_e.warn("A cancelled launch completed anyway \u2014 disposing what it brought up",{runId:e.runId,trigger:e.cancelledBy}),await this.dispose(e.runId,e.cancelledBy);return}this.#S(r.instance.runId,r.instance.deadlineAt);return;case"claim_refused":case"claim_unavailable":case"instance_lost_immediately":return;case"failed":if(await this.dispose(e.runId,"launch_failure"),e.cancelledBy!==null){_e.info("A cancelled launch failed on the way down \u2014 no verdict is sent",{runId:e.runId,trigger:e.cancelledBy,suppressedReason:r.body.reason});return}await this.#n.report({runId:e.runId,body:r.body});return}}async#h(){let e=this.#o,n=this.#p;if(!(e===null||n?.runId!==e.runId)&&(await this.#u.apply(e.runId,e.deadlineAt,n.identityIds),await this.#c.apply(e.runId,n.launchIds),n.main&&e.mainRequest!==null&&this.#s===null)){let r=e.mainRequest;e.mainRequest=null,this.#m(e.runId,r)}}async#w(e,n){_e.warn("The desired state withdrew a run that is still launching \u2014 disposing",{runId:e.runId,trigger:n}),e.cancelledBy=n,await this.dispose(e.runId,n)}#S(e,n,r=!0){this.stopMonitor(),this.#a=new qt({runId:e,identityId:null,deadlineAt:n,probe:r?()=>this.#t.probePlaybackSession():null,onBrowserGone:o(i=>{this.#r(()=>this.#y(e,"browser_gone",i,"browser_gone"))},"onBrowserGone"),onDeadline:o(()=>{this.#r(()=>this.#y(e,"max_duration","the run reached its server-authored deadline","max_duration"))},"onDeadline")}),this.#a.start()}async#v(e,n){let r=this.#i.has(e),i=r?"browser_gone":"launch_error";_e.error("The server publishes a run this agent is not carrying \u2014 reporting it",{runId:e,phase:n,sweptAtStartup:r,reason:i}),await this.#n.report({runId:e,body:{reason:i,message:r?"a leftover browser instance for this run was killed by the agent startup sweep":"this agent holds no browser instance for the run"}})}async#y(e,n,r,i){await this.dispose(e,i),await this.#n.report({runId:e,body:{reason:n,message:r}})}};function eg(t){return t.identities===void 0?[]:t.identities.map(e=>e.identityId)}o(eg,"identityIdsOf");function tg(t){return t.launches===void 0?[]:t.launches.map(e=>e.launchId)}o(tg,"launchIdsOf");function vi(t,e){return t!==78?t:e==="linux"?78:0}o(vi,"serviceExitCode");var jl="Create a new enrollment code in Progon (Settings \u2192 Agents) and run 'progon-agent enroll <code>' to enroll this machine again. The wipe removed the state file, so an installed package now takes the deployment it was built for; on a source checkout add --server <url>.",Wl={revoked:{exitCode:78,level:"error",message:"progon-agent stopped: this agent was revoked and its credential has been wiped. "+jl},reenroll_required:{exitCode:78,level:"error",message:"progon-agent stopped: this machine's agent token was superseded and the server no longer accepts it, so the credential has been wiped. This is not a revocation \u2014 the token was replaced and the replacement could not be kept. "+jl},credential_unusable:{exitCode:78,level:"error",message:"progon-agent stopped: the server no longer accepts the agent token this daemon was given in PROGON_AGENT_TOKEN, and a credential the operator owns is not one this daemon can replace. NOTHING WAS WIPED \u2014 the state directory belongs to an enrollment this mode never reads and may still be perfectly valid. Set PROGON_AGENT_TOKEN to a current token and start the daemon again, or unset it and enroll this machine so the daemon can rotate on its own."},upgrade_required:{exitCode:78,level:"error",message:"progon-agent stopped: the server no longer accepts this version of the agent. The line before names the minimum. Update with 'progon-agent update' and start again. Nothing was wiped: this machine stays enrolled."},fatal:{exitCode:1,level:"error",message:"progon-agent stopped: the desired-state poll was refused definitively and no repetition can change that answer, so the daemon has disposed its browser and stopped instead of live-locking. The preceding error line names the reason and the server's own message. Restarting is the process supervisor's call once that condition has been fixed."},stopped:{exitCode:null,level:"info",message:"progon-agent stopped"}},Hl={revoked:"agent_revoked",reenroll_required:"agent_superseded",credential_unusable:"agent_superseded",upgrade_required:"shutdown",fatal:"shutdown",stopped:"shutdown"};var H=w("token-rotation"),Jl=1440*60*1e3,Yt=class{static{o(this,"TokenRotationCoordinator")}#e;#t;#n;#r=null;#i=!1;#a=!1;constructor(e){this.#e=e.client,this.#t=e.stateDir,this.#n=e.identitySource}async runCycle(e){let n=this.#r;if(n!==null)return n;let r=this.#s(e);this.#r=r;try{return await r}finally{this.#r=null}}get canDiagnoseFromTheWire(){return this.#n!=="env_token"}async diagnoseSuperseded(e){if(this.#n==="env_token")return H.error("The agent token in PROGON_AGENT_TOKEN has been superseded and the server no longer accepts it. This daemon owns no copy of it and will not touch the state directory: set PROGON_AGENT_TOKEN to a current token and restart, or unset it and enroll this machine so the daemon can rotate on its own."),"alive";try{return await this.#e.getTokenRotationStatus({signal:e}),"alive"}catch(n){if(n instanceof O)return"reenroll_required";if(n instanceof T)throw n;if(n instanceof A)return H.warn("The superseded probe could not be answered \u2014 treating the credential as still usable, because only an explicit agents.token_superseded ends this identity",{operation:n.operation,err:n.message}),"alive";throw n}}async settle(){let e=this.#r;e!==null&&await e.then(()=>{},()=>{})}async#s(e){if(this.#n==="one_shot")return{kind:"unsupported_one_shot"};if(this.#n==="env_token")return this.#i||(this.#i=!0,H.warn("Agent token rotation is not available: this daemon runs on PROGON_AGENT_TOKEN, so the operator owns the credential and there is nowhere to persist a replacement. Rotate it by setting PROGON_AGENT_TOKEN to a new token and restarting, or enroll this machine so the daemon can rotate on its own.")),{kind:"unsupported_env_token"};if(this.#a)return{kind:"superseded_in_grace"};let n=this.#g();if(n.kind!=="identity")return this.#f(n);let r=n.identity,i=await this.#o(e);return i.kind!=="status"?i.outcome:i.value.rotationDue?await this.#u(r,i.value.tokenRotatedAt,e):this.#l(r,i.value.tokenRotatedAt)}async#o(e){try{return{kind:"status",value:e===void 0?await this.#e.getTokenRotationStatus():await this.#e.getTokenRotationStatus({signal:e})}}catch(n){if(n instanceof O)return H.error("This agent token has been superseded and no longer authenticates \u2014 the token family is dead and this machine must be enrolled again"),{kind:"outcome",outcome:{kind:"reenroll_required"}};if(n instanceof T)throw n;if(n instanceof A)return H.warn("The rotation status check failed \u2014 retrying on the next scheduled cycle",{operation:n.operation,err:n.message}),{kind:"outcome",outcome:{kind:"status_unavailable"}};throw n}}#l(e,n){return e.tokenRotatedAt===n?{kind:"not_due"}:e.tokenRotatedAt===null?(this.#d({...e,tokenRotatedAt:n},"first observed rotation marker"),{kind:"not_due"}):(this.#a=!0,H.error("The server reports a newer generation of this agent token than this daemon holds \u2014 either a rotation response was lost before it could be persisted, or another process rotated this identity. The current token keeps working until the server closes its rotation grace window; after that this machine must be enrolled again. No further rotation will be attempted with the current credential.",{observedTokenRotatedAt:e.tokenRotatedAt,serverTokenRotatedAt:n}),{kind:"superseded_in_grace"})}async#u(e,n,r){let i;try{i=(await this.#e.rotateToken()).agentToken}catch(l){if(l instanceof T)throw l;if(l instanceof O)return await this.#c(r);if(l instanceof A)return H.warn("The rotation request produced no usable answer \u2014 probing what the server actually committed",{operation:l.operation,err:l.message}),await this.#p(n);throw l}this.#d({...e,agentToken:i,tokenRotatedAt:null},"rotated agent token"),this.#e.useAgentToken(i);let s=await this.#m();return s.kind==="reenroll_required"?s:(s.kind==="observed"&&this.#d({...e,agentToken:i,tokenRotatedAt:s.tokenRotatedAt},"rotation marker of the new agent token"),H.info("Agent token rotated"),{kind:"rotated"})}async#c(e){return await this.diagnoseSuperseded(e)==="reenroll_required"?{kind:"reenroll_required"}:(this.#a=!0,H.error("This agent token is no longer the current generation, so it could not be rotated. It still authenticates for now \u2014 the server closes its rotation grace window shortly after, and this machine must then be enrolled again. No further rotation will be attempted with the current credential."),{kind:"superseded_in_grace"})}async#p(e){let n=await this.#o(void 0);return n.kind!=="status"?n.outcome:n.value.tokenRotatedAt===e?(H.warn("The rotation request never reached the server \u2014 nothing was committed and the current token is unchanged. The next scheduled check will try again."),{kind:"not_committed"}):(this.#a=!0,H.error("The rotation was committed by the server but its response was lost, so the new token cannot be recovered \u2014 the server hands out the plaintext exactly once. The current token keeps working until the server closes its rotation grace window; after that this machine must be enrolled again.",{anchorTokenRotatedAt:e,serverTokenRotatedAt:n.value.tokenRotatedAt}),{kind:"superseded_in_grace"})}async#m(){let e=await this.#o(void 0);return e.kind==="status"?{kind:"observed",tokenRotatedAt:e.value.tokenRotatedAt}:e.outcome.kind==="reenroll_required"?{kind:"reenroll_required"}:(H.warn("The rotated token could not be confirmed against the server, so its generation marker was not recorded. The next scheduled check re-establishes it."),{kind:"unconfirmed"})}#d(e,n){try{return It(this.#t,e),!0}catch(r){return H.error(`The ${n} could not be written to the state directory. This process keeps using the credential it holds, but a restart would fall back to the token on disk, which the server will refuse once its rotation grace window closes. Fix the permissions on the state directory BEFORE restarting the daemon; if it has already been restarted, enroll this machine again.`,{stateDir:this.#t,err:r instanceof Error?r.message:String(r)}),!1}}#g(){let e;try{e=L(this.#t)}catch(n){return{kind:"unreadable",err:n instanceof Error?n.message:String(n)}}return e===null?{kind:"absent"}:{kind:"identity",identity:e}}#f(e){return e.kind==="unreadable"?(H.error("The agent identity in the state directory cannot be read, so the credential this daemon is running on can neither be rotated nor replaced. The daemon keeps working on the token it holds in memory and will look again on the next scheduled check \u2014 restore the state directory from a backup, or enroll this machine again before restarting the daemon.",{stateDir:this.#t,identitySource:this.#n,err:e.err}),{kind:"identity_unavailable"}):(H.error("The agent identity is no longer in the state directory, so the credential this daemon is running on can neither be rotated nor replaced. The daemon keeps working on the token it holds in memory and will look again on the next scheduled check \u2014 restore the state directory, or enroll this machine again before restarting the daemon.",{stateDir:this.#t,identitySource:this.#n}),{kind:"identity_unavailable"})}};var B=w("run-supervisor"),qr=o(()=>Promise.resolve(),"noVerdictOwed"),Yr=class{static{o(this,"RunSupervisor")}#e;#t;#n;#r=new Br;#i;#a;#s;#o=null;#l=0;#u=0;#c=!1;#p=new AbortController;#m=null;#d=!1;#g=!1;#f;#h=null;#w=null;constructor(e){this.#e=e.client,this.#i=e.stateDir,this.#a=e.pollWaitSec,this.#s=e.capabilitiesDeclared,this.#f=e.tokenRotation,this.#t=new jr(e.client),this.#p.signal.addEventListener("abort",()=>this.#$(),{once:!0});let n=e.createRuntime({onInstanceLost:o(r=>{this.#b(()=>this.#n.handleInstanceLost(r))},"onInstanceLost"),onIdentityInstanceLost:o(r=>{this.#b(()=>this.#n.handleIdentityInstanceLost(r))},"onIdentityInstanceLost"),onLaunchInstanceLost:o(r=>{this.#b(()=>this.#n.handleLaunchInstanceLost(r))},"onLaunchInstanceLost")});this.#n=new Vr({client:e.client,runtime:n,reporter:this.#t,detach:o(r=>this.#b(r),"detach")})}get activeRunId(){return this.#n.activeRunId}async run(){await this.#r.run(()=>this.#n.sweepAtStartup());let e=await this.#L();if(e!==null)return e;for(this.#O(),this.#s||await this.#v();!this.#c;){let n=this.#m;if(n!==null)return await this.#R(n),"revoked";if(this.#d)return await this.#T(),"reenroll_required";if(this.#g)return await this.#C(),"credential_unusable";try{await this.#r.run(()=>this.#t.retryPending());let r=await this.#U();this.#l=0;let i=await this.#r.run(()=>this.#n.reconcile(r));await this.#M(i)}catch(r){if(r instanceof T)return await this.#R(r),"revoked";if(r instanceof O&&await this.#A(r))return await this.#T(),"reenroll_required";if(this.#c)break;if(this.#_())continue;let i=await this.#j(r);if(i!==null)return i==="credential_unusable"?await this.#C():i==="upgrade_required"?await this.#F():await this.#B(),i}}return this.#S()}async#S(){let e=this.#w;if(e===null)throw new Error("run-supervisor: the loop ended as stopped, but no shutdown() was ever started");return await e,"stopped"}async#v(){try{await this.#e.declareCapabilities({signal:this.#p.signal})}catch(e){if(await this.#N(e),this.#_())return;if(!(e instanceof A))throw e;B.error("Could not declare capabilities \u2014 job kinds this build supports will not be published to this agent until the next start; playback is unaffected",{err:e.message})}}async shutdown(e){let n=this.#w;if(n!==null)return B.info("A shutdown is already in progress \u2014 joining it",{cause:e}),n;let r=this.#y(e);return this.#w=r,r}async#y(e){B.info("Shutting down",{cause:e}),await this.#E(e==="fatal"?"fatal":"stopped",n=>this.#I(n))}async#E(e,n){this.#c=!0,this.#o?.abort(),this.#p.abort();let r=Hl[e],i=await this.#n.cancelLaunchAndSettle(r);await this.#r.run(async()=>{this.#n.stopMonitor();let s=this.#n.activeRunId;s!==null&&await this.#n.dispose(s,r),await n({activeRunId:s,launchingRunId:i})}),await this.#f.settle()}async#I(e){let{activeRunId:n,launchingRunId:r}=e;if(n!==null){await this.#x(()=>this.#t.report({runId:n,body:{reason:"browser_gone",message:Si}}));return}if(r!==null){await this.#x(()=>this.#t.report({runId:r,body:{reason:"browser_gone",message:Si}}));return}await this.#x(()=>this.#t.retryPending())}async#L(){try{if((await this.#f.runCycle(this.#p.signal)).kind!=="reenroll_required")return null}catch(e){if(e instanceof T)return await this.#R(e),"revoked";throw e}return await this.#T(),"reenroll_required"}#O(){if(this.#c||this.#p.signal.aborted)return;let e=setTimeout(()=>{this.#h=null,this.#D().finally(()=>{this.#O()})},Jl);e.unref(),this.#h=e}async#D(){try{if((await this.#f.runCycle(this.#p.signal)).kind!=="reenroll_required")return;this.#d=!0,this.#o?.abort()}catch(e){await this.#P(e)}}#$(){this.#h!==null&&(clearTimeout(this.#h),this.#h=null)}async#A(e){B.warn("A gateway call was refused as superseded \u2014 diagnosing the credential",{operation:e.operation});try{return await this.#f.diagnoseSuperseded(this.#p.signal)==="reenroll_required"}catch(n){if(n instanceof T)return this.#m=n,!1;throw n}}async#U(){let e=new AbortController;this.#o=e;try{return await this.#e.pollDesiredState({waitSec:this.#a,signal:e.signal})}finally{this.#o=null}}async#M(e){if(e.kind==="reconciled"){this.#u=0;return}await this.#G(e.runId,e.claimAnswer)}async#G(e,n){let r=ge(this.#u);B.info("The desired state still names a run whose claim this agent already issued \u2014 pausing before the next poll",{runId:e,attempt:this.#u,waitMs:r,claimOnTheWire:n!==null}),this.#u+=1;let i=new AbortController;if(this.#o=i,this.#p.signal.aborted||this.#_()){this.#o=null;return}n?.then(()=>i.abort());try{await oe(r,i.signal)}finally{this.#o=null}}async#k(){await this.#f.settle(),rr(this.#i)}async#R(e){B.error("This agent has been revoked \u2014 disposing, wiping the credential and stopping",{signal:e.signal}),await this.#E("revoked",qr),await this.#k()}async#C(){B.error("The server refuses the credential this daemon runs on as superseded, and this daemon has no way to replace it \u2014 disposing the browser and stopping so the operator, and the process supervisor, both learn it now. The state directory is left untouched: this credential did not come from there."),await this.#E("credential_unusable",qr)}async#F(){await this.#E("upgrade_required",qr)}async#B(){await this.#E("fatal",e=>this.#I(e))}async#T(){B.error("This agent token has been superseded and its family is no longer accepted \u2014 disposing, wiping the credential and stopping"),await this.#E("reenroll_required",qr),await this.#k()}async#j(e){if(!(e instanceof A))throw e;let n=this.#W(e);return n.kind==="exit"?n.exit:(this.#l+=1,await oe(n.delayMs,this.#p.signal),null)}#W(e){if(e instanceof ee)return B.error("The server refuses this version of the agent \u2014 disposing the browser and stopping",{operation:e.operation,err:e.message}),{kind:"exit",exit:"upgrade_required"};if(e instanceof O){if(!this.#f.canDiagnoseFromTheWire)return{kind:"exit",exit:"credential_unusable"};let r=ge(this.#l);return B.error("The server refused this credential as superseded, but the probe did not confirm the token family is dead \u2014 the daemon keeps polling on the credential it holds. If this repeats, create a new enrollment code in Progon (Settings \u2192 Agents) and enroll this machine again.",{operation:e.operation,attempt:this.#l,retryInMs:r}),{kind:"retry",delayMs:r}}let n=Be({attempt:this.#l,error:e});return n.retry?(B.warn("Desired-state poll failed \u2014 backing off",{attempt:this.#l,retryInMs:n.delayMs,err:e.message}),{kind:"retry",delayMs:n.delayMs}):(B.error("The desired-state poll was refused definitively and no repetition can change that \u2014 the daemon cannot reconcile without a snapshot, so it is disposing its browser and stopping. Restart duty belongs to the process supervisor.",{reason:n.reason,operation:e.operation,err:e.message}),{kind:"exit",exit:"fatal"})}#b(e){return this.#r.run(e).catch(n=>this.#P(n))}async#P(e){await this.#N(e)||B.error("A background supervisor action failed",{err:e instanceof Error?e.message:String(e)})}async#N(e){if(e instanceof T)return this.#m=e,this.#o?.abort(),!0;if(!(e instanceof O))return!1;try{await this.#A(e)?this.#d=!0:this.#f.canDiagnoseFromTheWire||(this.#g=!0)}catch(n){return B.error("The superseded diagnosis failed after a gateway refusal off the poll",{operation:e.operation,err:n instanceof Error?n.message:String(n)}),!0}return this.#_()&&this.#o?.abort(),!0}#_(){return this.#m!==null||this.#d||this.#g}async#x(e){try{await e()}catch(n){if(n instanceof O){B.error("This agent token is no longer accepted as current, so the run could not be reported. The credential on disk is left alone \u2014 the next start diagnoses it and will say whether this machine has to be enrolled again.",{operation:n.operation});return}if(n instanceof T){await this.#k(),B.error("This agent was revoked, so the run could not be reported and the credential has been wiped. Create a new enrollment code in Progon (Settings \u2192 Agents) and start the daemon once with PROGON_AGENT_ENROLL_CODE=<code> to enroll this machine again.",{signal:n.signal});return}throw n}}};var Kl=w("supervisor-boot");async function Vl(t){t?.throwIfAborted();let e=Me();Kl.info("Config loaded",{serverUrlOrigin:new URL(e.serverUrl).origin,serverUrlSource:e.serverUrlSource,stateDir:e.stateDir,headfulOverride:e.headfulOverride,allowInsecureHttps:e.allowInsecureHttps,disableBrowserSandbox:e.disableBrowserSandbox});let n=Je(),r=await Fr({config:e,machine:n,signal:t});t?.throwIfAborted(),Kl.info("Agent identity resolved",{source:r.source,agentId:r.agentId,hostname:n.hostname,platform:n.platform,arch:n.arch,agentVersion:n.agentVersion});let i=Tr({overridePath:e.extensionDistOverride,stateDir:e.stateDir,agentId:r.agentId});await Ar({disableBrowserSandbox:e.disableBrowserSandbox,signal:t}),t?.throwIfAborted();let s=new Ge({serverUrl:e.serverUrl,agentToken:r.agentToken}),l=new Yt({client:s,stateDir:e.stateDir,identitySource:r.source});return bi({client:s,stateDir:e.stateDir,pollWaitSec:r.pollWaitSec,tokenRotation:l,extensionDist:i,browserEnv:e,capabilitiesDeclared:!1})}o(Vl,"bootRunSupervisor");function bi(t){let{client:e,stateDir:n,pollWaitSec:r,tokenRotation:i,extensionDist:s,browserEnv:l}=t;return new Yr({client:e,stateDir:n,pollWaitSec:r,tokenRotation:i,capabilitiesDeclared:t.capabilitiesDeclared,createRuntime:o(({onInstanceLost:c,onIdentityInstanceLost:a,onLaunchInstanceLost:d})=>new Gr({stateDir:n,extensionDist:s,headfulOverride:l.headfulOverride,allowInsecureHttps:l.allowInsecureHttps,disableBrowserSandbox:l.disableBrowserSandbox,onInstanceLost:c,onIdentityInstanceLost:a,onLaunchInstanceLost:d}),"createRuntime")})}o(bi,"wireRunSupervisor");import{z as Tn}from"zod";var ng="scenario_launches.scenarios_not_launchable",rg=Tn.object({items:Tn.array(Tn.object({scenarioId:Tn.string(),notStartedReason:Tn.string()}))});function ql(t){if(t.errorCode!==ng)return[];let e=rg.safeParse(t.params);return e.success?e.data.items.map(n=>` NOT STARTED scenario ${n.scenarioId} - ${n.notStartedReason}`):["Progon did not say which scenarios cannot start."]}o(ql,"refusedScenarioLines");import{stripVTControlCharacters as cg}from"node:util";import{appendFileSync as og,statSync as ig}from"node:fs";var sg=1024*1024,Yl=`
|
|
101
101
|
### Progon
|
|
102
102
|
|
|
103
|
-
`;function
|
|
103
|
+
`;function Ql(t,e){let n;try{n=ig(t).size}catch(i){return{kind:"failed",reason:zl(i)}}let r=ag(e,sg-n);if(r===null)return{kind:"no_room",fileBytes:n};try{og(t,r,"utf8")}catch(i){return{kind:"failed",reason:zl(i)}}return{kind:"written"}}o(Ql,"appendStepSummary");function ag(t,e){let n=t.result.map(Xr).join(""),r=t.reportUrl===null?"":`
|
|
104
104
|
Report: <${t.reportUrl}>
|
|
105
|
-
`,i=pt(
|
|
106
|
-
`}o(Xr,"codeLine");function
|
|
105
|
+
`,i=pt(Yl)+pt(n)+pt(r),s=[];for(let d of t.details){let u=pt(Xr(d));if(i+u>e)break;i+=u,s.push(d)}let l=lg(t.details.slice(s.length));for(;l>0&&i+pt(Xl(l))>e;){let d=s.pop();if(d===void 0)break;i-=pt(Xr(d)),Zl(d)&&(l+=1)}let c=l>0?Xl(l):"",a=Yl+n+s.map(Xr).join("")+c+r;return pt(a)<=e?a:null}o(ag,"fitStepSummary");function Xr(t){return` ${t}
|
|
106
|
+
`}o(Xr,"codeLine");function Xl(t){return`
|
|
107
107
|
${t} more line(s) are in the job log.
|
|
108
|
-
`}o(
|
|
108
|
+
`}o(Xl,"omissionOf");function Zl(t){return t.trim()!==""}o(Zl,"isText");function lg(t){return t.filter(Zl).length}o(lg,"countText");function pt(t){return Buffer.byteLength(t,"utf8")}o(pt,"byteLength");function zl(t){return t instanceof Error?t.message:String(t)}o(zl,"describeError");var dg=/[\t\n\v\f\r\u0085\u2028\u2029]+/gu,ug=/[\p{Cc}\p{Bidi_Control}]/gu,pg=/^(\s*):(?=:)/u,mg=/##(?=[a-z]*\[)/giu;function fg(t){return cg(t).replace(dg," ").replace(ug,"")}o(fg,"toSingleLine");function hg(t){return t.replace(pg,"$1: ").replace(mg,"# #")}o(hg,"defuseCiCommands");function F(t,e){return{result:t,details:[],reportUrl:e}}o(F,"finalOf");var zr=class{constructor(e,n){this.stepSummaryPath=n;e!==null&&this.secrets.add(e)}static{o(this,"CiOutput")}secrets=new Set;lastLineAt=Date.now();addSecret(e){this.secrets.add(e)}line(e){this.write("stdout",this.render(e))}silentForMs(){return Date.now()-this.lastLineAt}errorLine(e){this.write("stderr",this.render(e))}final(e,n){let r={result:e.result.map(s=>this.render(s)),details:e.details.map(s=>this.render(s)),reportUrl:e.reportUrl===null?null:this.render(e.reportUrl)},i=o(s=>this.write(n,s),"write");i("");for(let s of[...r.result,...r.details])i(s);r.reportUrl!==null&&(i(""),i(`Report: ${r.reportUrl}`)),this.stepSummaryPath!==null&&this.summarize(this.stepSummaryPath,r)}flush(){return new Promise(e=>process.stdout.write("",()=>e()))}write(e,n){if(e==="stderr"){process.stderr.write(`${n}
|
|
109
109
|
`);return}process.stdout.write(`${n}
|
|
110
|
-
`),this.lastLineAt=Date.now()}summarize(e,n){let r=Zl(e,n);r.kind==="no_room"?this.line(`The step summary has no room for this result: the file of the step already holds ${r.fileBytes} bytes of its 1 MiB. Nothing was written to it.`):r.kind==="failed"&&this.line(`Could not write the step summary: ${r.reason}`)}render(e){return gg(this.mask(hg(e)))}mask(e){let n=C(e);for(let r of this.secrets)n=n.split(r).join("[REDACTED]");return n}};function ki(t){return t.status===Ja||t.status===yr}o(ki,"isItemOver");function Tn(t){return t.status===yr?` NOT STARTED ${t.scenarioName}${_i(t.notStartedReason)}`:t.outcome===Zo?` PASSED ${t.scenarioName}`:t.outcome===ei?` FAILED ${t.scenarioName}${_i(yg(t))}`:` ${t.outcome??"no outcome reported"} ${t.scenarioName}${_i(t.failureReason)}`}o(Tn,"formatItemLine");function _i(t){return t===null||t===""?"":` - ${t}`}o(_i,"detail");function yg(t){let e=[];return t.failedStep!==null&&e.push(`step ${t.failedStep.number} "${t.failedStep.name}"`),t.failureReason!==null&&e.push(t.failureReason),e.join(": ")}o(yg,"describeFailure");function tc(t){let{counts:e,waitingForRunner:n,current:r,status:i}=t;if(n!==null)return`Waiting for the runner: ${n.ahead>0?`${n.ahead} job(s) ahead of this launch`:"next in line"}. ${e.total} scenario(s) in the launch.`;let s=e.finished+e.notStarted,l=r===null?"":`, running: ${r}`;return`Launch ${i}: ${s} of ${e.total} scenario(s) done${l}.`}o(tc,"formatStatusLine");function nc(t){let e={passed:[],failed:[],notStarted:[],other:[]};for(let n of t)n.status===yr?e.notStarted.push(n):n.outcome===Zo?e.passed.push(n):n.outcome===ei?e.failed.push(n):e.other.push(n);return e}o(nc,"groupItems");function rc(t,e){let n=nc(e),r=t.counts.total;return{result:[wg(t.verdict,r,n.failed.length),`Scenarios: ${sc(n)} (of ${r}).`],details:ic(n),reportUrl:t.webUrl}}o(rc,"formatReport");function oc(t,e,n){let{total:r,finished:i,notStarted:s,running:l,queued:c}=e.counts,a=nc(n.filter(ki)),d=[`Latest counts from Progon: ${i} finished, ${s} did not start, ${l} running, ${c} queued (of ${r}).`,`Partial, as this job saw them end: ${sc(a)}.`,...ic(a)];return{result:[t],details:d,reportUrl:e.webUrl}}o(oc,"formatPartialReport");function ic({failed:t,notStarted:e,other:n}){let r=[];return t.length>0&&r.push("","Failed scenarios:",...t.map(Tn)),e.length>0&&r.push("","Did not start:",...e.map(Tn)),n.length>0&&r.push("","Other outcomes:",...n.map(Tn)),r}o(ic,"detailsOf");function sc({passed:t,failed:e,notStarted:n,other:r}){let i=[`${t.length} passed`,`${e.length} failed`];return n.length>0&&i.push(`${n.length} did not start`),r.length>0&&i.push(`${r.length} other`),i.join(", ")}o(sc,"tallyOf");function wg(t,e,n){return t===hr?`Result: PASSED - all ${e} scenario(s) passed.`:t===gr?`Result: FAILED - ${n} of ${e} scenario(s) failed.`:t===Ka?"Result: NO RESULT - the launch ended without a full result.":t===null?"Result: NO RESULT - Progon reported no verdict for this launch.":`Result: NO RESULT - this CLI does not know the verdict "${t}".`}o(wg,"resultLine");var Qr=class{static{o(this,"CiStopControl")}#e=null;#t=new AbortController;#n;#r;constructor(e){if(e===null){this.#n=null,this.#r=null;return}this.#n=performance.now()+e,this.#r=setTimeout(()=>this.#i(),e)}get cause(){return this.#e}get signal(){return this.#t.signal}cancel(){this.#e="cancelled",this.#t.abort()}secondsLeft(){return this.#n===null?null:Math.floor((this.#n-performance.now())/1e3)}launchCreated(){this.close(),this.#e==="timeout"&&(this.#e=null,this.#t=new AbortController)}close(){this.#r!==null&&clearTimeout(this.#r)}#i(){this.#e===null&&(this.#e="timeout",this.#t.abort())}};function mt(t){return t==="timeout"?"--timeout expired.":"The job was cancelled."}o(mt,"describeStopCause");var Y=class extends Error{constructor(n,r){super("ci run ended");this.exitCode=n;this.final=r}static{o(this,"CiRunEnded")}},Yt=class extends Error{static{o(this,"CiReadFailed")}};function ac(t,e,n,r){return cc(t,n,r,i=>t.api.createLaunch(e,i))}o(ac,"createLaunchWithRetry");function lc(t,e){return cc(t,e,bg,n=>t.api.createRunner(n))}o(lc,"createRunnerWithRetry");async function cc(t,e,n,r){let{output:i,timings:s}=t,l=Date.now();for(let c=0;;c+=1){if(e.cause!==null)throw new Y(U,F([`${mt(e.cause)} No launch was confirmed. No result.`],null));try{return await Sg(t,e,r)}catch(a){if(a instanceof lt)throw new Y(U,F([`Progon gave an unreadable answer about ${n.noun}: ${a.message}`,"No result."],null));if(a instanceof he&&!Ri(a)){if(e.cause!==null)throw new Y(U,F([`${mt(e.cause)} Progon refused ${n.noun}: ${Ae(a)}.`,"No launch was created. No result."],null));return Eg(n,a)}if(!dc(a))throw a;let d=uc(a,c),u=Date.now()-l+d<s.createBudgetMs;if(e.cause===null&&u){i.line(`Progon did not take ${n.noun} (${Ae(a)}); repeating in ${Math.ceil(d/1e3)}s.`),await oe(d,e.signal);continue}let m=[`Progon did not take ${n.noun}: ${Ae(a)}. No result.`];throw n.mayExistAfterLostAnswer&&a instanceof Gt&&m.push("It may exist in Progon; this job could not confirm it."),new Y(U,F(m,null))}}}o(cc,"callBeforeLaunchWithRetry");async function Sg(t,e,n){let r=new AbortController,i,s=o(()=>{i=setTimeout(()=>r.abort(),t.timings.signalStopTimeoutMs)},"startGrace");e.cause!==null?s():e.signal.addEventListener("abort",s,{once:!0});try{return await n(r.signal)}finally{clearTimeout(i),e.signal.removeEventListener("abort",s)}}o(Sg,"callWithStopGrace");async function xn(t,e,n,r){let{output:i,timings:s}=t,l=null,c=o(a=>{throw new Yt(`Could not read ${n}: ${Ae(a)}. No result.`)},"endAfterLaunch");for(let a=0;;a+=1)try{return await r(e)}catch(d){if(e.aborted)return null;if(d instanceof lt&&c(d),d instanceof he&&!Ri(d)&&c(d),!dc(d))throw d;let u=Date.now();l===null&&(l=u);let m=uc(d,a);u-l+m>=s.readBudgetMs&&c(d),i.line(`Progon does not answer about ${n} (${Ae(d)}); repeating in ${Math.ceil(m/1e3)}s.`),await oe(m,e)}}o(xn,"readWithRetry");function dc(t){return t instanceof Gt||t instanceof he&&Ri(t)}o(dc,"isTemporaryFailure");function Ri(t){return t.status===429||t.status>=500}o(Ri,"isRepeatableRefusal");function uc(t,e){return t instanceof he&&t.status===429&&t.retryAfterMs!==null?t.retryAfterMs:ge(e)}o(uc,"retryDelayMs");function Eg(t,e){let n=[`Progon refused ${t.noun}: ${Ae(e)}.`],r=e.errorCode===null?void 0:t.hints.get(e.errorCode);throw r!==void 0&&n.push(r),n.push("No launch was created."),new Y(En(e.status,e.errorCode),{result:n,details:Yl(e),reportUrl:null})}o(Eg,"refuseBeforeLaunch");var pc=[["auth.invalid_token","Check the PROGON_CI_KEY secret of this pipeline."],["auth.token_expired","The CI key has expired: create a new one and update PROGON_CI_KEY."],["auth.token_revoked","The CI key was revoked: create a new one and update PROGON_CI_KEY."],["auth.wrong_auth_class","PROGON_CI_KEY must be a CI key of the project."]],vg=new Map([...pc,["agents.offline","Start the CI runner and run the job again."],["agents.queue_full","The queue of the CI runner is full. Run the job again later."],["agents.capability_missing","The CI runner build is too old. Update progon-agent on it."]]),mc=new Map(pc),fc={noun:"the launch",hints:vg,mayExistAfterLostAnswer:!0},hc={noun:"the launch",hints:mc,mayExistAfterLostAnswer:!0},bg={noun:"the runner of this job",hints:mc,mayExistAfterLostAnswer:!1};function Ae(t){return t instanceof he?t.errorCode===null?`${t.message} (HTTP ${t.status})`:`${t.message} (${t.errorCode})`:t.message}o(Ae,"describeFailure");var Tg="progon-agent-job-",xg=new Set(["ENOENT","ENOTDIR","EACCES","EPERM","EROFS"]),eo=class{static{o(this,"CiJobRunner")}#e;#t;#n;#r=Cg();#i=null;#a=null;#l=!1;constructor(e){this.#e=e.deps,this.#t=e.serverUrl,this.#n=e.browserEnv}async start(e,n){await this.#o(e,n),this.#m("Registering the runner of this job in Progon.",n);let{runnerId:r,enrollmentCode:i}=await lc(this.#e,e);this.#e.output.addSecret(i);let s=new Ut({serverUrl:this.#t,machine:Ke()}),l=await this.#s(e,"enroll the runner of this job",()=>s.enroll(i,{signal:e.signal}));this.#e.output.addSecret(l.agentToken);let c=new Ge({serverUrl:this.#t,agentToken:l.agentToken});await this.#s(e,"accept what this runner can run",()=>c.declareCapabilities({signal:e.signal}));let a=Rr({overridePath:this.#n.extensionDistOverride,stateDir:this.#r,agentId:l.agentId});return this.#d(e),this.#c(bi({client:c,stateDir:this.#r,pollWaitSec:l.pollWaitSec,tokenRotation:new qt({client:c,stateDir:this.#r,identitySource:"one_shot"}),extensionDist:a,browserEnv:this.#n,capabilitiesDeclared:!0})),r}async dispose(){this.#l=!0;let{output:e}=this.#e,n=this.#i;if(n!==null)try{await n.shutdown("job_finished"),await this.#a}catch(r){e.line(`The browser of this job may still be running: ${Zr(r)}`)}try{kg(this.#r,{recursive:!0,force:!0})}catch(r){e.line(`Could not remove ${this.#r}: ${Zr(r)}`)}}async#o(e,n){this.#m("Preparing the browser inside this job.",n),this.#n.disableBrowserSandbox&&this.#e.output.line("PROGON_AGENT_DISABLE_BROWSER_SANDBOX is set: no browser sandbox.");try{await Or({disableBrowserSandbox:this.#n.disableBrowserSandbox,signal:e.signal})}catch(r){throw this.#d(e),r instanceof Q?new Y(U,F([`The browser could not be prepared: ${r.message}`,"No launch was created."],null)):r}this.#d(e)}async#s(e,n,r){let{output:i,timings:s}=this.#e,l=Date.now();for(let c=0;;c+=1){this.#d(e);try{return await r()}catch(a){if(!(a instanceof A))throw a;a instanceof Z&&this.#d(e);let d=Ig(a,c);if(d!==null&&e.cause===null&&Date.now()-l+d<s.createBudgetMs){i.line(`Progon did not ${n} (${a.message}); repeating in ${Math.ceil(d/1e3)}s.`),await oe(d,e.signal);continue}throw new Y(e.cause===null?Og(a):U,F([`Progon did not ${n}: ${a.message}`,"No launch was created."],null))}}}#c(e){this.#i=e,this.#a=e.run().then(n=>this.#u(n),n=>this.#p(n))}#u(e){this.#l||e==="stopped"||e==="revoked"||this.#e.output.line(`The runner of this job stopped (${e}). Waiting for Progon to end the launch.`)}async#p(e){let{output:n}=this.#e;if(n.errorLine(`progon-agent: the runner of this job failed: ${Zr(e)}`),!this.#l)try{await this.#i?.shutdown("fatal")}catch(r){n.line(`The browser of this job may still be running: ${Zr(r)}`)}}#m(e,n){n(e),this.#e.output.line(e)}#d(e){if(e.cause!==null)throw new Y(U,F([`${mt(e.cause)} No launch was created. No result.`],null))}};function Ig(t,e){if(t instanceof x&&t.status===429)return t.retryAfterMs??ge(e);let n=Be({attempt:e,error:t});return n.retry?n.delayMs:null}o(Ig,"gatewayRetryDelayMs");function Og(t){return t instanceof x?En(t.status,t.errorCode):t instanceof T?En(403,"agents.revoked"):U}o(Og,"exitCodeOfGatewayFailure");function Ag(){let t=Rg();try{return _g(gc(t,Tg))}catch(e){let n=e instanceof Error?e.code:void 0;throw e instanceof Error&&n!==void 0&&xg.has(n)?new p(`The temporary folder ${t} cannot be used: ${e.message}. Set TMPDIR to a writable folder in this pipeline.`,{cause:e}):e}}o(Ag,"createJobStateDir");function Cg(){let t=Ag();return process.env.XDG_CONFIG_HOME=gc(t,"xdg-config"),t}o(Cg,"prepareJobStateDir");function Zr(t){return t instanceof Error?t.message:String(t)}o(Zr,"describeError");var to=class{static{o(this,"CiItemTracker")}api;output;known=new Map;printed=new Set;firstUnprinted=0;readRevision=null;morePages=!1;constructor(e){this.api=e.api,this.output=e.output}async syncPage(e,n){if(this.readRevision!==null&&e.revision<=this.readRevision&&!this.morePages)return;let r=this.firstUnprinted,i=await this.api.listItems(e.id,r,n);this.morePages=this.recordPage(r,i),this.readRevision=e.revision}async drain(e,n){if(this.readRevision!==null&&e.revision<=this.readRevision&&this.firstUnprinted>=e.counts.total)return;let r=this.firstUnprinted;for(;;){let i=await this.api.listItems(e.id,r,n);if(this.recordPage(r,i),r+=i.items.length,i.items.length===0||r>=i.total)break}this.readRevision=e.revision,this.morePages=!1}items(){return[...this.known.entries()].sort(([e],[n])=>e-n).map(([,e])=>e)}recordPage(e,n){let r=this.firstUnprinted;for(n.items.forEach((i,s)=>{let l=e+s;this.known.set(l,i),ki(i)&&!this.printed.has(l)&&(this.printed.add(l),this.output.line(Tn(i)))});this.printed.has(this.firstUnprinted);)this.firstUnprinted+=1;return this.firstUnprinted>r&&e+n.items.length<n.total}};var yc=new AbortController().signal;async function wc(t,e,n,r,i){let s="Creating the launch in Progon.",l=setInterval(()=>{t.output.silentForMs()>=t.timings.statusQuietMs&&t.output.line(s)},t.timings.statusCheckMs),c=o(a=>{s=a},"setStatus");try{let a=i===null?e.runnerId:await i.start(n,c);c("Creating the launch in Progon.");let d=Ng(e,r,a,Pg(n));return await Lg(t,d,n,c,i!==null)}catch(a){if(a instanceof Y)return{exitCode:a.exitCode,final:a.final};throw a}finally{clearInterval(l)}}o(wc,"runCiLaunch");function Pg(t){let e=t.secondsLeft();if(e!==null&&e<1)throw new Y(U,F(["--timeout left less than one second for the launch. No launch was created. No result."],null));return e}o(Pg,"timeoutSecOf");function Ng(t,e,n,r){let i=t.selection.kind==="spec"?{specNodeId:t.selection.specNodeId}:{scenarioIds:t.selection.scenarioIds};return{idempotencyKey:e.idempotencyKey,...i,...t.environmentId===null?{}:{environmentId:t.environmentId},...t.entryUrl===null?{}:{entryUrl:t.entryUrl},...n===null?{}:{runnerId:n},...r===null?{}:{timeoutSec:r},...e.ci===null?{}:{ci:e.ci}}}o(Ng,"createBody");async function Lg(t,e,n,r,i){let{output:s,timings:l}=t,a=await ac(t,e,n,i?hc:fc);n.launchCreated(),s.line(`Launch ${a.id} created. Report: ${a.webUrl}`);let d=new to(t),u=!1;try{for(;;){if(n.cause!==null)return await Dg(t,a,d,i,r);if(a.status===fr){let S=a;if(await xn(t,n.signal,"the scenarios of the launch",I=>d.drain(S,I))===null)continue;return Sc(a,d)}let m=tc(a);r(m),a.waitingForRunner!==null!==u&&(u=a.waitingForRunner!==null,s.line(m));let g=a;if(await xn(t,n.signal,"the scenarios of the launch",S=>d.syncPage(g,S)),await oe(l.pollIntervalMs,n.signal),n.cause!==null)continue;let E=await xn(t,n.signal,"the state of the launch",S=>t.api.getLaunch(g.id,S));E!==null&&(a=E)}}catch(m){if(m instanceof Yt)return Xt(m.message,a,d);throw m}}o(Lg,"driveLaunch");function Sc(t,e){return{exitCode:Ya(t.verdict),final:rc(t,e.items())}}o(Sc,"reportAndExit");async function Dg(t,e,n,r,i){let{api:s,output:l,timings:c}=t;l.line(`${mt("cancelled")} Stopping launch ${e.id}.`);let a;try{a=await s.stopLaunch(e.id,c.signalStopTimeoutMs)}catch(d){if(d instanceof he&&d.errorCode==="scenario_launches.not_running")return Ug(t,e,n);if(d instanceof Fe)return Xt(`Could not stop the launch: ${Ae(d)}. No result.`,e,n);throw d}return r?$g(t,a,n,i):Xt("The launch was stopped; no verdict was waited for. No result.",a,n)}o(Dg,"stopLaunchOnce");async function $g(t,e,n,r){let{api:i,output:s,timings:l}=t,c=e;if(c.status!==fr){let a=`Launch ${c.id} is stopping; the browser of this job stays up until it ends.`;s.line(a),r(a)}try{for(;c.status!==fr;){await oe(l.pollIntervalMs,yc);let{id:a}=c,d=await xn(t,yc,"the state of the launch",u=>i.getLaunch(a,u));if(d===null)throw new Error("a read that nothing interrupts returned the interrupted answer");c=d}}catch(a){if(a instanceof Yt)return Xt(a.message,c,n);throw a}return Xt("The launch was stopped and has ended. No result.",c,n)}o($g,"awaitStoppedLaunch");async function Ug(t,e,n){try{let r=await t.api.getLaunch(e.id,void 0);return await n.drain(r,void 0),Sc(r,n)}catch(r){if(r instanceof Fe)return Xt(`Could not read the ended launch: ${Ae(r)}. No result.`,e,n);throw r}}o(Ug,"reportEndedLaunch");function Xt(t,e,n){return{exitCode:U,final:oc(t,e,n.items())}}o(Xt,"noResult");var Gg=3e4,Fg={pollIntervalMs:1e4,statusCheckMs:1e4,statusQuietMs:4e4,createBudgetMs:12e4,readBudgetMs:3e5,signalStopTimeoutMs:5e3},Bg=25e3;async function bc(t){Xn();let e=D(process.env,"PROGON_CI_KEY"),n=new zr(e,D(process.env,"GITHUB_STEP_SUMMARY")),r={current:null},i=o(s=>{vc(n,s),Jg(r.current)},"onDefect");process.on("uncaughtException",i),process.on("unhandledRejection",i);try{let s=await jg(t,e,n,r);return await n.flush(),s}catch(s){return s instanceof p?(n.final(F([s.message],null),"stdout"),await n.flush(),ct):(vc(n,s),await n.flush(),U)}}o(bc,"runCiCommand");async function jg(t,e,n,r){let i=qa(t);if(i.kind==="help")return Ec(l=>n.line(l)),ti;if(i.kind==="refused")return Ec(l=>n.errorLine(l)),n.final(F([`progon-agent: ${i.reason}`],null),"stderr"),ct;if(e===null)return n.final(F(["PROGON_CI_KEY is not set. Add the CI key of the project to the secrets of this pipeline."],null),"stdout"),ct;if(/[^\x21-\x7e]/.test(e))return n.final(F(["PROGON_CI_KEY contains whitespace or an invalid character. Paste the key again, whole."],null),"stdout"),ct;zn(process.env),er(process.env);let s=i.options.inJob?Wg():null;return Kg(i.options,e,Hg(s),s,n,r)}o(jg,"runParsedCommand");function Wg(){let t=hn();return t.extensionDistOverride!==void 0&&cr(t.extensionDistOverride),t}o(Wg,"loadJobBrowserEnv");function Hg(t){let e=D(process.env,"PROGON_SERVER_URL");if(e===null){let n=Tt();if(n!==null)return n;throw new p("PROGON_SERVER_URL is not set and this package has no built-in address of Progon. Set PROGON_SERVER_URL in this pipeline.")}if(ke(e),t!==null&&t.extensionDistOverride===void 0){let n=Tt();if(n!==null&&!Ue(e,n))throw new p(`--in-job: PROGON_SERVER_URL is ${e}, but the extension in this package works only with ${n}. Remove PROGON_SERVER_URL, or install the progon-agent package of ${e}.`)}return e}o(Hg,"resolveCiServerUrl");async function Kg(t,e,n,r,i,s){let l=new Qr(t.timeoutMs),c=o(()=>l.cancel(),"onSignal");for(let g of ir)process.on(g,c);let d={api:new wr({serverUrl:n,key:e,requestTimeoutMs:Gg}),output:i,timings:Fg},u={idempotencyKey:Mg(),ci:Xa(process.env)},m=null;try{m=r===null?null:new eo({deps:d,serverUrl:n,browserEnv:r}),s.current=m;let g=await wc(d,t,l,u,m);return i.final(g.final,"stdout"),g.exitCode}finally{l.close(),m!==null&&await m.dispose(),s.current=null;for(let g of ir)process.removeListener(g,c)}}o(Kg,"runWithControls");async function Jg(t){if(t!==null){let e,n=new Promise(r=>{e=setTimeout(r,Bg)});await Promise.race([t.dispose(),n]),clearTimeout(e)}process.exit(U)}o(Jg,"exitAfterDefect");function Ec(t){for(let e of Va.split(`
|
|
111
|
-
`))t(e)}o(
|
|
110
|
+
`),this.lastLineAt=Date.now()}summarize(e,n){let r=Ql(e,n);r.kind==="no_room"?this.line(`The step summary has no room for this result: the file of the step already holds ${r.fileBytes} bytes of its 1 MiB. Nothing was written to it.`):r.kind==="failed"&&this.line(`Could not write the step summary: ${r.reason}`)}render(e){return hg(this.mask(fg(e)))}mask(e){let n=C(e);for(let r of this.secrets)n=n.split(r).join("[REDACTED]");return n}};function ki(t){return t.status===Ka||t.status===wr}o(ki,"isItemOver");function xn(t){return t.status===wr?` NOT STARTED ${t.scenarioName}${_i(t.notStartedReason)}`:t.outcome===Zo?` PASSED ${t.scenarioName}`:t.outcome===ei?` FAILED ${t.scenarioName}${_i(gg(t))}`:` ${t.outcome??"no outcome reported"} ${t.scenarioName}${_i(t.failureReason)}`}o(xn,"formatItemLine");function _i(t){return t===null||t===""?"":` - ${t}`}o(_i,"detail");function gg(t){let e=[];return t.failedStep!==null&&e.push(`step ${t.failedStep.number} "${t.failedStep.name}"`),t.failureReason!==null&&e.push(t.failureReason),e.join(": ")}o(gg,"describeFailure");function ec(t){let{counts:e,waitingForRunner:n,current:r,status:i}=t;if(n!==null)return`Waiting for the runner: ${n.ahead>0?`${n.ahead} job(s) ahead of this launch`:"next in line"}. ${e.total} scenario(s) in the launch.`;let s=e.finished+e.notStarted,l=r===null?"":`, running: ${r}`;return`Launch ${i}: ${s} of ${e.total} scenario(s) done${l}.`}o(ec,"formatStatusLine");function tc(t){let e={passed:[],failed:[],notStarted:[],other:[]};for(let n of t)n.status===wr?e.notStarted.push(n):n.outcome===Zo?e.passed.push(n):n.outcome===ei?e.failed.push(n):e.other.push(n);return e}o(tc,"groupItems");function nc(t,e){let n=tc(e),r=t.counts.total;return{result:[yg(t.verdict,r,n.failed.length),`Scenarios: ${ic(n)} (of ${r}).`],details:oc(n),reportUrl:t.webUrl}}o(nc,"formatReport");function rc(t,e,n){let{total:r,finished:i,notStarted:s,running:l,queued:c}=e.counts,a=tc(n.filter(ki)),d=[`Latest counts from Progon: ${i} finished, ${s} did not start, ${l} running, ${c} queued (of ${r}).`,`Partial, as this job saw them end: ${ic(a)}.`,...oc(a)];return{result:[t],details:d,reportUrl:e.webUrl}}o(rc,"formatPartialReport");function oc({failed:t,notStarted:e,other:n}){let r=[];return t.length>0&&r.push("","Failed scenarios:",...t.map(xn)),e.length>0&&r.push("","Did not start:",...e.map(xn)),n.length>0&&r.push("","Other outcomes:",...n.map(xn)),r}o(oc,"detailsOf");function ic({passed:t,failed:e,notStarted:n,other:r}){let i=[`${t.length} passed`,`${e.length} failed`];return n.length>0&&i.push(`${n.length} did not start`),r.length>0&&i.push(`${r.length} other`),i.join(", ")}o(ic,"tallyOf");function yg(t,e,n){return t===gr?`Result: PASSED - all ${e} scenario(s) passed.`:t===yr?`Result: FAILED - ${n} of ${e} scenario(s) failed.`:t===Ja?"Result: NO RESULT - the launch ended without a full result.":t===null?"Result: NO RESULT - Progon reported no verdict for this launch.":`Result: NO RESULT - this CLI does not know the verdict "${t}".`}o(yg,"resultLine");var Qr=class{static{o(this,"CiStopControl")}#e=null;#t=new AbortController;#n;#r;constructor(e){if(e===null){this.#n=null,this.#r=null;return}this.#n=performance.now()+e,this.#r=setTimeout(()=>this.#i(),e)}get cause(){return this.#e}get signal(){return this.#t.signal}cancel(){this.#e="cancelled",this.#t.abort()}secondsLeft(){return this.#n===null?null:Math.floor((this.#n-performance.now())/1e3)}launchCreated(){this.close(),this.#e==="timeout"&&(this.#e=null,this.#t=new AbortController)}close(){this.#r!==null&&clearTimeout(this.#r)}#i(){this.#e===null&&(this.#e="timeout",this.#t.abort())}};function mt(t){return t==="timeout"?"--timeout expired.":"The job was cancelled."}o(mt,"describeStopCause");var Y=class extends Error{constructor(n,r){super("ci run ended");this.exitCode=n;this.final=r}static{o(this,"CiRunEnded")}},Xt=class extends Error{static{o(this,"CiReadFailed")}};function sc(t,e,n,r){return lc(t,n,r,i=>t.api.createLaunch(e,i))}o(sc,"createLaunchWithRetry");function ac(t,e){return lc(t,e,vg,n=>t.api.createRunner(n))}o(ac,"createRunnerWithRetry");async function lc(t,e,n,r){let{output:i,timings:s}=t,l=Date.now();for(let c=0;;c+=1){if(e.cause!==null)throw new Y(U,F([`${mt(e.cause)} No launch was confirmed. No result.`],null));try{return await wg(t,e,r)}catch(a){if(a instanceof lt)throw new Y(U,F([`Progon gave an unreadable answer about ${n.noun}: ${a.message}`,"No result."],null));if(a instanceof he&&!Ri(a)){if(e.cause!==null)throw new Y(U,F([`${mt(e.cause)} Progon refused ${n.noun}: ${Ae(a)}.`,"No launch was created. No result."],null));return Sg(n,a)}if(!cc(a))throw a;let d=dc(a,c),u=Date.now()-l+d<s.createBudgetMs;if(e.cause===null&&u){i.line(`Progon did not take ${n.noun} (${Ae(a)}); repeating in ${Math.ceil(d/1e3)}s.`),await oe(d,e.signal);continue}let m=[`Progon did not take ${n.noun}: ${Ae(a)}. No result.`];throw n.mayExistAfterLostAnswer&&a instanceof Gt&&m.push("It may exist in Progon; this job could not confirm it."),new Y(U,F(m,null))}}}o(lc,"callBeforeLaunchWithRetry");async function wg(t,e,n){let r=new AbortController,i,s=o(()=>{i=setTimeout(()=>r.abort(),t.timings.signalStopTimeoutMs)},"startGrace");e.cause!==null?s():e.signal.addEventListener("abort",s,{once:!0});try{return await n(r.signal)}finally{clearTimeout(i),e.signal.removeEventListener("abort",s)}}o(wg,"callWithStopGrace");async function In(t,e,n,r){let{output:i,timings:s}=t,l=null,c=o(a=>{throw new Xt(`Could not read ${n}: ${Ae(a)}. No result.`)},"endAfterLaunch");for(let a=0;;a+=1)try{return await r(e)}catch(d){if(e.aborted)return null;if(d instanceof lt&&c(d),d instanceof he&&!Ri(d)&&c(d),!cc(d))throw d;let u=Date.now();l===null&&(l=u);let m=dc(d,a);u-l+m>=s.readBudgetMs&&c(d),i.line(`Progon does not answer about ${n} (${Ae(d)}); repeating in ${Math.ceil(m/1e3)}s.`),await oe(m,e)}}o(In,"readWithRetry");function cc(t){return t instanceof Gt||t instanceof he&&Ri(t)}o(cc,"isTemporaryFailure");function Ri(t){return t.status===429||t.status>=500}o(Ri,"isRepeatableRefusal");function dc(t,e){return t instanceof he&&t.status===429&&t.retryAfterMs!==null?t.retryAfterMs:ge(e)}o(dc,"retryDelayMs");function Sg(t,e){let n=[`Progon refused ${t.noun}: ${Ae(e)}.`],r=e.errorCode===null?void 0:t.hints.get(e.errorCode);throw r!==void 0&&n.push(r),n.push("No launch was created."),new Y(vn(e.status,e.errorCode),{result:n,details:ql(e),reportUrl:null})}o(Sg,"refuseBeforeLaunch");var uc=[["auth.invalid_token","Check the PROGON_CI_KEY secret of this pipeline."],["auth.token_expired","The CI key has expired: create a new one and update PROGON_CI_KEY."],["auth.token_revoked","The CI key was revoked: create a new one and update PROGON_CI_KEY."],["auth.wrong_auth_class","PROGON_CI_KEY must be a CI key of the project."]],Eg=new Map([...uc,["agents.offline","Start the CI runner and run the job again."],["agents.queue_full","The queue of the CI runner is full. Run the job again later."],["agents.capability_missing","The CI runner build is too old. Update progon-agent on it."]]),pc=new Map(uc),mc={noun:"the launch",hints:Eg,mayExistAfterLostAnswer:!0},fc={noun:"the launch",hints:pc,mayExistAfterLostAnswer:!0},vg={noun:"the runner of this job",hints:pc,mayExistAfterLostAnswer:!1};function Ae(t){return t instanceof he?t.errorCode===null?`${t.message} (HTTP ${t.status})`:`${t.message} (${t.errorCode})`:t.message}o(Ae,"describeFailure");var Rg="progon-agent-job-",Tg=new Set(["ENOENT","ENOTDIR","EACCES","EPERM","EROFS"]),eo=class{static{o(this,"CiJobRunner")}#e;#t;#n;#r=Ag();#i=null;#a=null;#s=!1;constructor(e){this.#e=e.deps,this.#t=e.serverUrl,this.#n=e.browserEnv}async start(e,n){await this.#o(e,n),this.#m("Registering the runner of this job in Progon.",n);let{runnerId:r,enrollmentCode:i}=await ac(this.#e,e);this.#e.output.addSecret(i);let s=new Ut({serverUrl:this.#t,machine:Je()}),l=await this.#l(e,"enroll the runner of this job",()=>s.enroll(i,{signal:e.signal}));this.#e.output.addSecret(l.agentToken);let c=new Ge({serverUrl:this.#t,agentToken:l.agentToken});await this.#l(e,"accept what this runner can run",()=>c.declareCapabilities({signal:e.signal}));let a=Tr({overridePath:this.#n.extensionDistOverride,stateDir:this.#r,agentId:l.agentId});return this.#d(e),this.#u(bi({client:c,stateDir:this.#r,pollWaitSec:l.pollWaitSec,tokenRotation:new Yt({client:c,stateDir:this.#r,identitySource:"one_shot"}),extensionDist:a,browserEnv:this.#n,capabilitiesDeclared:!0})),r}async dispose(){this.#s=!0;let{output:e}=this.#e,n=this.#i;if(n!==null)try{await n.shutdown("job_finished"),await this.#a}catch(r){e.line(`The browser of this job may still be running: ${Zr(r)}`)}try{_g(this.#r,{recursive:!0,force:!0})}catch(r){e.line(`Could not remove ${this.#r}: ${Zr(r)}`)}}async#o(e,n){this.#m("Preparing the browser inside this job.",n),this.#n.disableBrowserSandbox&&this.#e.output.line("PROGON_AGENT_DISABLE_BROWSER_SANDBOX is set: no browser sandbox.");try{await Ar({disableBrowserSandbox:this.#n.disableBrowserSandbox,signal:e.signal})}catch(r){throw this.#d(e),r instanceof Q?new Y(U,F([`The browser could not be prepared: ${r.message}`,"No launch was created."],null)):r}this.#d(e)}async#l(e,n,r){let{output:i,timings:s}=this.#e,l=Date.now();for(let c=0;;c+=1){this.#d(e);try{return await r()}catch(a){if(!(a instanceof A))throw a;a instanceof Z&&this.#d(e);let d=xg(a,c);if(d!==null&&e.cause===null&&Date.now()-l+d<s.createBudgetMs){i.line(`Progon did not ${n} (${a.message}); repeating in ${Math.ceil(d/1e3)}s.`),await oe(d,e.signal);continue}throw new Y(e.cause===null?Ig(a):U,F([`Progon did not ${n}: ${a.message}`,"No launch was created."],null))}}}#u(e){this.#i=e,this.#a=e.run().then(n=>this.#c(n),n=>this.#p(n))}#c(e){this.#s||e==="stopped"||e==="revoked"||this.#e.output.line(`The runner of this job stopped (${e}). Waiting for Progon to end the launch.`)}async#p(e){let{output:n}=this.#e;if(n.errorLine(`progon-agent: the runner of this job failed: ${Zr(e)}`),!this.#s)try{await this.#i?.shutdown("fatal")}catch(r){n.line(`The browser of this job may still be running: ${Zr(r)}`)}}#m(e,n){n(e),this.#e.output.line(e)}#d(e){if(e.cause!==null)throw new Y(U,F([`${mt(e.cause)} No launch was created. No result.`],null))}};function xg(t,e){if(t instanceof x&&t.status===429)return t.retryAfterMs??ge(e);let n=Be({attempt:e,error:t});return n.retry?n.delayMs:null}o(xg,"gatewayRetryDelayMs");function Ig(t){return t instanceof x?vn(t.status,t.errorCode):t instanceof T?vn(403,"agents.revoked"):U}o(Ig,"exitCodeOfGatewayFailure");function Og(){let t=kg();try{return bg(hc(t,Rg))}catch(e){let n=e instanceof Error?e.code:void 0;throw e instanceof Error&&n!==void 0&&Tg.has(n)?new p(`The temporary folder ${t} cannot be used: ${e.message}. Set TMPDIR to a writable folder in this pipeline.`,{cause:e}):e}}o(Og,"createJobStateDir");function Ag(){let t=Og();return process.env.XDG_CONFIG_HOME=hc(t,"xdg-config"),t}o(Ag,"prepareJobStateDir");function Zr(t){return t instanceof Error?t.message:String(t)}o(Zr,"describeError");var to=class{static{o(this,"CiItemTracker")}api;output;known=new Map;printed=new Set;firstUnprinted=0;readRevision=null;morePages=!1;constructor(e){this.api=e.api,this.output=e.output}async syncPage(e,n){if(this.readRevision!==null&&e.revision<=this.readRevision&&!this.morePages)return;let r=this.firstUnprinted,i=await this.api.listItems(e.id,r,n);this.morePages=this.recordPage(r,i),this.readRevision=e.revision}async drain(e,n){if(this.readRevision!==null&&e.revision<=this.readRevision&&this.firstUnprinted>=e.counts.total)return;let r=this.firstUnprinted;for(;;){let i=await this.api.listItems(e.id,r,n);if(this.recordPage(r,i),r+=i.items.length,i.items.length===0||r>=i.total)break}this.readRevision=e.revision,this.morePages=!1}items(){return[...this.known.entries()].sort(([e],[n])=>e-n).map(([,e])=>e)}recordPage(e,n){let r=this.firstUnprinted;for(n.items.forEach((i,s)=>{let l=e+s;this.known.set(l,i),ki(i)&&!this.printed.has(l)&&(this.printed.add(l),this.output.line(xn(i)))});this.printed.has(this.firstUnprinted);)this.firstUnprinted+=1;return this.firstUnprinted>r&&e+n.items.length<n.total}};var gc=new AbortController().signal;async function yc(t,e,n,r,i){let s="Creating the launch in Progon.",l=setInterval(()=>{t.output.silentForMs()>=t.timings.statusQuietMs&&t.output.line(s)},t.timings.statusCheckMs),c=o(a=>{s=a},"setStatus");try{let a=i===null?e.runnerId:await i.start(n,c);c("Creating the launch in Progon.");let d=Pg(e,r,a,Cg(n));return await Ng(t,d,n,c,i!==null)}catch(a){if(a instanceof Y)return{exitCode:a.exitCode,final:a.final};throw a}finally{clearInterval(l)}}o(yc,"runCiLaunch");function Cg(t){let e=t.secondsLeft();if(e!==null&&e<1)throw new Y(U,F(["--timeout left less than one second for the launch. No launch was created. No result."],null));return e}o(Cg,"timeoutSecOf");function Pg(t,e,n,r){let i=t.selection.kind==="spec"?{specNodeId:t.selection.specNodeId}:{scenarioIds:t.selection.scenarioIds};return{idempotencyKey:e.idempotencyKey,...i,...t.environmentId===null?{}:{environmentId:t.environmentId},...t.entryUrl===null?{}:{entryUrl:t.entryUrl},...n===null?{}:{runnerId:n},...r===null?{}:{timeoutSec:r},...e.ci===null?{}:{ci:e.ci}}}o(Pg,"createBody");async function Ng(t,e,n,r,i){let{output:s,timings:l}=t,a=await sc(t,e,n,i?fc:mc);n.launchCreated(),s.line(`Launch ${a.id} created. Report: ${a.webUrl}`);let d=new to(t),u=!1;try{for(;;){if(n.cause!==null)return await Lg(t,a,d,i,r);if(a.status===hr){let S=a;if(await In(t,n.signal,"the scenarios of the launch",I=>d.drain(S,I))===null)continue;return wc(a,d)}let m=ec(a);r(m),a.waitingForRunner!==null!==u&&(u=a.waitingForRunner!==null,s.line(m));let g=a;if(await In(t,n.signal,"the scenarios of the launch",S=>d.syncPage(g,S)),await oe(l.pollIntervalMs,n.signal),n.cause!==null)continue;let E=await In(t,n.signal,"the state of the launch",S=>t.api.getLaunch(g.id,S));E!==null&&(a=E)}}catch(m){if(m instanceof Xt)return zt(m.message,a,d);throw m}}o(Ng,"driveLaunch");function wc(t,e){return{exitCode:Ya(t.verdict),final:nc(t,e.items())}}o(wc,"reportAndExit");async function Lg(t,e,n,r,i){let{api:s,output:l,timings:c}=t;l.line(`${mt("cancelled")} Stopping launch ${e.id}.`);let a;try{a=await s.stopLaunch(e.id,c.signalStopTimeoutMs)}catch(d){if(d instanceof he&&d.errorCode==="scenario_launches.not_running")return $g(t,e,n);if(d instanceof Fe)return zt(`Could not stop the launch: ${Ae(d)}. No result.`,e,n);throw d}return r?Dg(t,a,n,i):zt("The launch was stopped; no verdict was waited for. No result.",a,n)}o(Lg,"stopLaunchOnce");async function Dg(t,e,n,r){let{api:i,output:s,timings:l}=t,c=e;if(c.status!==hr){let a=`Launch ${c.id} is stopping; the browser of this job stays up until it ends.`;s.line(a),r(a)}try{for(;c.status!==hr;){await oe(l.pollIntervalMs,gc);let{id:a}=c,d=await In(t,gc,"the state of the launch",u=>i.getLaunch(a,u));if(d===null)throw new Error("a read that nothing interrupts returned the interrupted answer");c=d}}catch(a){if(a instanceof Xt)return zt(a.message,c,n);throw a}return zt("The launch was stopped and has ended. No result.",c,n)}o(Dg,"awaitStoppedLaunch");async function $g(t,e,n){try{let r=await t.api.getLaunch(e.id,void 0);return await n.drain(r,void 0),wc(r,n)}catch(r){if(r instanceof Fe)return zt(`Could not read the ended launch: ${Ae(r)}. No result.`,e,n);throw r}}o($g,"reportEndedLaunch");function zt(t,e,n){return{exitCode:U,final:rc(t,e,n.items())}}o(zt,"noResult");var Mg=3e4,Gg={pollIntervalMs:1e4,statusCheckMs:1e4,statusQuietMs:4e4,createBudgetMs:12e4,readBudgetMs:3e5,signalStopTimeoutMs:5e3},Fg=25e3;async function vc(t){zn();let e=D(process.env,"PROGON_CI_KEY"),n=new zr(e,D(process.env,"GITHUB_STEP_SUMMARY")),r={current:null},i=o(s=>{Ec(n,s),Jg(r.current)},"onDefect");process.on("uncaughtException",i),process.on("unhandledRejection",i);try{let s=await Bg(t,e,n,r);return await n.flush(),s}catch(s){return s instanceof p?(n.final(F([s.message],null),"stdout"),await n.flush(),ct):(Ec(n,s),await n.flush(),U)}}o(vc,"runCiCommand");async function Bg(t,e,n,r){let i=qa(t);if(i.kind==="help")return Sc(l=>n.line(l)),ti;if(i.kind==="refused")return Sc(l=>n.errorLine(l)),n.final(F([`progon-agent: ${i.reason}`],null),"stderr"),ct;if(e===null)return n.final(F(["PROGON_CI_KEY is not set. Add the CI key of the project to the secrets of this pipeline."],null),"stdout"),ct;if(/[^\x21-\x7e]/.test(e))return n.final(F(["PROGON_CI_KEY contains whitespace or an invalid character. Paste the key again, whole."],null),"stdout"),ct;Qn(process.env),tr(process.env);let s=i.options.inJob?jg():null;return Hg(i.options,e,Wg(s),s,n,r)}o(Bg,"runParsedCommand");function jg(){let t=gn();return t.extensionDistOverride!==void 0&&dr(t.extensionDistOverride),t}o(jg,"loadJobBrowserEnv");function Wg(t){let e=D(process.env,"PROGON_SERVER_URL");if(e===null){let n=Tt();if(n!==null)return n;throw new p("PROGON_SERVER_URL is not set and this package has no built-in address of Progon. Set PROGON_SERVER_URL in this pipeline.")}if(Re(e),t!==null&&t.extensionDistOverride===void 0){let n=Tt();if(n!==null&&!Ue(e,n))throw new p(`--in-job: PROGON_SERVER_URL is ${e}, but the extension in this package works only with ${n}. Remove PROGON_SERVER_URL, or install the progon-agent package of ${e}.`)}return e}o(Wg,"resolveCiServerUrl");async function Hg(t,e,n,r,i,s){let l=new Qr(t.timeoutMs),c=o(()=>l.cancel(),"onSignal");for(let g of sr)process.on(g,c);let d={api:new Sr({serverUrl:n,key:e,requestTimeoutMs:Mg}),output:i,timings:Gg},u={idempotencyKey:Ug(),ci:Xa(process.env)},m=null;try{m=r===null?null:new eo({deps:d,serverUrl:n,browserEnv:r}),s.current=m;let g=await yc(d,t,l,u,m);return i.final(g.final,"stdout"),g.exitCode}finally{l.close(),m!==null&&await m.dispose(),s.current=null;for(let g of sr)process.removeListener(g,c)}}o(Hg,"runWithControls");async function Jg(t){if(t!==null){let e,n=new Promise(r=>{e=setTimeout(r,Fg)});await Promise.race([t.dispose(),n]),clearTimeout(e)}process.exit(U)}o(Jg,"exitAfterDefect");function Sc(t){for(let e of Va.split(`
|
|
111
|
+
`))t(e)}o(Sc,"writeUsage");function Ec(t,e){t.final(F([`progon-agent: internal error: ${Kg(e)}`],null),"stderr")}o(Ec,"writeDefect");function Kg(t){return t instanceof Error?t.stack??t.message:String(t)}o(Kg,"describeDefect");import{resolve as Vg}from"node:path";var bc=` progon-agent --version Print this package's version. No network.
|
|
112
112
|
progon-agent status [--state-dir <path>] What is installed, enrolled and running for the
|
|
113
113
|
state directory. No network; changes nothing.
|
|
114
114
|
progon-agent stop [--state-dir <path>] Stop the agent running for the state directory
|
|
@@ -140,20 +140,20 @@ ${t} more line(s) are in the job log.
|
|
|
140
140
|
restart stop, then start
|
|
141
141
|
status what the OS holds for it and what runs
|
|
142
142
|
|
|
143
|
-
'start' also takes --state-dir <path>.`,
|
|
144
|
-
`)).digest("hex")}o(
|
|
145
|
-
`);return}let b=uo(S,
|
|
146
|
-
`);if(b===-1||d)return;let I=a.slice(0,b);a=a.slice(b+1),E(I)}}),i.on("end",()=>{m(u===null?{kind:"silent",reason:"it closed the connection without a greeting"}:{kind:"foreign",reason:"it closed the connection without an answer \u2014 it did not accept the key of this directory"})}),i.on("error",S=>{let b=
|
|
147
|
-
`)}o(h,"say");function
|
|
148
|
-
`).slice(0,3).join(" / ");return`${r} exited ${n.exitCode}${i===""?"":`: ${i}`}`}o(Xe,"describeOsFailure");async function ie(t,e,n={}){let r=await X(t,e,n);if(r.exitCode!==0)throw new _(Xe(t,e,r));return r}o(ie,"runOsCommandOrThrow");var _=class extends Error{static{o(this,"ServiceManagerError")}name="ServiceManagerError"};function
|
|
149
|
-
`),r=t.environment.map(([i,s])=>` <key>${
|
|
150
|
-
<string>${
|
|
143
|
+
'start' also takes --state-dir <path>.`,qg=new Set(["service","status","stop","reset","doctor","update","uninstall"]),Yg=/^\d+\.\d+\.\d+$/;function _c(t){return t==="--version"||qg.has(t)}o(_c,"isLifecycleVerb");function On(t,e){let n=t[e+1];return n===void 0||n===""?{reason:"'--state-dir' needs a directory"}:n.startsWith("-")?{reason:`'--state-dir' needs a directory, got the option '${n}' (a directory named so: ./${n})`}:{path:Vg(n)}}o(On,"readStateDirFlag");var Xg=new Set(["enable","disable","start","stop","restart","status"]);function zg(t){return t!==void 0&&Xg.has(t)}o(zg,"isServiceVerb");function kc(t,e){if(t==="--version")return e.length>0?le("'--version' takes no arguments"):{kind:"invocation",invocation:{command:"version"}};if(t==="service"){let[s,...l]=e;if(!zg(s))return le(s===void 0?"'service' needs a verb: enable, disable, start, stop, restart or status":`unknown verb '${s}' for 'service' (enable, disable, start, stop, restart, status)`);if(l.length===0)return{kind:"invocation",invocation:{command:t,verb:s,stateDir:void 0}};if(l[0]!=="--state-dir")return le(`unknown option '${String(l[0])}' for 'service ${s}'`);let c=On(l,0);return"reason"in c?le(c.reason):l.length>2?le("unexpected arguments after '--state-dir'"):{kind:"invocation",invocation:{command:t,verb:s,stateDir:c.path}}}let n,r=[],i=null;for(let s=0;s<e.length;s+=1){let l=e[s];if(l==="--state-dir"){let c=On(e,s);if("reason"in c)return le(c.reason);if(t==="uninstall")r.push(c.path);else{if(n!==void 0)return le("'--state-dir' is given twice");n=c.path}s+=1;continue}if(l==="--version"&&t==="update"){let c=e[s+1];if(c===void 0)return le("'--version' needs a version, such as 1.6.0");if(!Yg.test(c))return le(`'--version' takes one release as x.y.z, got '${c}'`);if(i!==null)return le("'--version' is given twice");i=c,s+=1;continue}return le(`unknown option '${String(l)}' for '${t}'`)}switch(t){case"status":case"stop":case"reset":case"doctor":return{kind:"invocation",invocation:{command:t,stateDir:n}};case"update":return{kind:"invocation",invocation:{command:t,stateDir:n,version:i}};case"uninstall":return{kind:"invocation",invocation:{command:t,stateDirs:r}};default:return le(`unknown command '${t}'`)}}o(kc,"parseLifecycleArgs");function le(t){return{kind:"refusal",reason:t}}o(le,"refusal");import{accessSync as vw,existsSync as bw,constants as _w,statSync as kw}from"node:fs";import{createHash as gy}from"node:crypto";import{statSync as yy}from"node:fs";import{connect as Gc}from"node:net";import{resolve as wy}from"node:path";import{z as M}from"zod";import{createHmac as Qg,randomBytes as Ti,timingSafeEqual as Zg}from"node:crypto";import{chmodSync as ey,linkSync as ty,readFileSync as ny,statSync as ry,unlinkSync as oy,writeFileSync as iy}from"node:fs";import{join as no}from"node:path";var ft="control.key",sy=32,ay=/^[0-9a-f]{64}$/,ly=16,cy=/^control\.key\.tmp-\d+-[0-9a-f]{8}$/;function Rc(t){return t===ft||cy.test(t)}o(Rc,"isControlKeyEntry");function oo(){return Ti(ly).toString("hex")}o(oo,"newNonce");function Tc(t){return typeof t=="object"&&t!==null?t.code:void 0}o(Tc,"errnoOf");function io(t){if(process.platform==="win32")return;let e=ry(t),n=process.getuid?.();if(n===void 0)throw new Error("[control-auth] process.getuid is unavailable on a POSIX platform");if(e.uid!==n||(e.mode&18)!==0)throw new p(`The state directory ${t} is not private to this user (owner uid ${e.uid}, mode ${(e.mode&511).toString(8)}), so its control channel cannot be trusted. Use a directory of your own: chmod 700 it, or pick another --state-dir.`)}o(io,"assertPrivateStateDir");function xc(t){let e=ro(t);if(e!==null)return e;let n=Ti(sy),r=no(t,`${ft}.tmp-${process.pid}-${Ti(4).toString("hex")}`);iy(r,n.toString("hex"),{mode:384,flag:"wx"});try{ey(r,384),ty(r,no(t,ft))}catch(s){if(Tc(s)!=="EEXIST")throw s}finally{oy(r)}let i=ro(t);if(i===null)throw new Error(`[control-auth] ${no(t,ft)} vanished after creation`);return i}o(xc,"ensureControlKey");function ro(t){let e=no(t,ft),n;try{n=ny(e,"utf8")}catch(r){if(Tc(r)==="ENOENT")return null;throw r}if(!ay.test(n))throw new p(`${e} is not a control key written by progon-agent. Stop any progon-agent of this directory, delete the file and start again.`);return Buffer.from(n,"hex")}o(ro,"readControlKey");function Ic(t,e){return Qg("sha256",t).update(e.join(`
|
|
144
|
+
`)).digest("hex")}o(Ic,"hmac");function so(t,e,n,r){return Ic(t,["progon-agent control request",e,n,r])}o(so,"requestProof");function ao(t,e,n){return Ic(t,["progon-agent control answer",e,n])}o(ao,"answerProof");function lo(t,e){let n=Buffer.from(t,"hex"),r=Buffer.from(e,"hex");return n.length===r.length&&n.length>0&&Zg(n,r)}o(lo,"proofMatches");import{randomBytes as dy}from"node:crypto";import{readdirSync as Ac,readlinkSync as uy,renameSync as py,symlinkSync as my,unlinkSync as Cc}from"node:fs";import{join as ht}from"node:path";var Pc="control.sock",xi=/^control-\d+-[0-9a-f]{8}\.sock$/,Nc=/^control-\d+-[0-9a-f]{8}\.sock\.next$/,Lc=/^control\.sock\.head-\d+-[0-9a-f]{8}\.tmp$/,fy=/^control-\d+-[0-9a-f]{8}\.sock\.pending$/,hy=w("control-socket-chain");function Dc(t){return t===Pc||xi.test(t)||Nc.test(t)||Lc.test(t)||fy.test(t)}o(Dc,"isControlSocketEntry");function co(t){return ht(t,Pc)}o(co,"controlLinkPath");function Ii(t,e){return ht(t,`${e}.next`)}o(Ii,"successorLinkPath");function $c(t,e){let n=ht(t,`control.sock.head-${process.pid}-${dy(4).toString("hex")}.tmp`);my(e,n);try{py(n,co(t))}catch(r){throw Cc(n),r}}o($c,"checkpointControlSocket");async function Uc(t,e,n){let r=[];for(let i of Ac(t,{withFileTypes:!0}))i.isSocket()&&xi.test(i.name)&&r.push(i.name);for(let[i,s]of r.entries()){if(!e()){hy.warn("Control socket cleanup reached the acquisition budget; a later start will continue",{stateDir:t,remainingSockets:r.length-i});return}await n(s)&&qe(ht(t,s))}}o(Uc,"reapControlSockets");function Mc(t,e){for(let n of Ac(t,{withFileTypes:!0}))if(n.isSymbolicLink())if(Nc.test(n.name)){let r=n.name.slice(0,-5);if(r===e)continue;qe(ht(t,n.name)),qe(ht(t,r))}else Lc.test(n.name)&&qe(ht(t,n.name))}o(Mc,"pruneControlHistory");function qe(t){try{Cc(t)}catch(e){if(typeof e!="object"||e===null||e.code!=="ENOENT")throw e}}o(qe,"unlinkControlEntry");function An(t){let e=Oc(co(t));if(e===null)return null;let n=new Set;for(;;){if(!xi.test(e)||n.has(e))throw new Error(`[control-channel] Invalid ownership link in ${t}: ${e}`);n.add(e);let r=Oc(Ii(t,e));if(r===null)return e;e=r}}o(An,"resolveControlSocketName");function Oc(t){try{return uy(t)}catch(e){if((typeof e=="object"&&e!==null?e.code:null)==="ENOENT")return null;throw e}}o(Oc,"readLink");var Ye=5e3,Sy=64*1024,Pn=2,Fc=/^[0-9a-f]{32}$/,Bc=/^[0-9a-f]{64}$/,Ey=M.object({protocol:M.literal(Pn),pid:M.number().int().positive(),version:M.string().min(1),startedAt:M.string().min(1),stateDir:M.string().min(1),phase:M.enum(["starting","running","stopping"]),activeRunId:M.string().min(1).nullable(),service:M.boolean()}),vy=M.object({protocol:M.literal(Pn),challenge:M.string().regex(Fc)}),jc=M.object({type:M.enum(["status","stop"]),nonce:M.string().regex(Fc),proof:M.string().regex(Bc)}),by=M.object({proof:M.string().regex(Bc),status:Ey});function Oi(t){return process.platform==="win32"?{kind:"pipe",name:`\\\\?\\pipe\\progon-agent-${gy("sha256").update(wy(t).toLowerCase()).digest("hex").slice(0,32)}`}:{kind:"unix",dir:t}}o(Oi,"controlAddress");function Wc(t){return Dc(t)||Rc(t)}o(Wc,"isControlChannelEntry");function po(t,e){let n=process.cwd();process.chdir(t);try{return e()}finally{process.chdir(n)}}o(po,"inDir");function Cn(t){return typeof t=="object"&&t!==null?t.code:void 0}o(Cn,"errnoOf");async function $(t,e){return Jc(t,"status",e)}o($,"queryOwner");async function Hc(t){return Jc(t,"stop")}o(Hc,"requestOwnerStop");async function Jc(t,e,n){if(!_y(t))return{kind:"none"};io(t);let r=Oi(t),i;try{let s=r.kind==="unix"?n??An(t):r.name;if(s===null)return{kind:"none"};i=r.kind==="unix"?po(r.dir,()=>Gc(s)):Gc(s)}catch(s){if(Cn(s)==="ENOENT"||Cn(s)==="ENOTDIR")return{kind:"none"};throw s}return new Promise((s,l)=>{let c=!1,a="",d=!1,u=null,m=o(S=>{d||(d=!0,clearTimeout(g),i.destroy(),S instanceof Error?l(S):s(S))},"settle"),g=setTimeout(()=>{m(c?{kind:"silent",reason:`it accepted the connection but did not answer within ${Ye/1e3} s`}:new Error(`[control-channel] Connecting to the control channel of ${t} did not finish within ${Ye/1e3} s.`))},Ye),E=o(S=>{if(u===null){let I=uo(S,vy);if(!I.ok){m({kind:"silent",reason:`its greeting is not one this version reads (${I.reason})`});return}let N;try{N=ro(t)}catch(Et){m(Et instanceof Error?Et:new Error(String(Et)));return}if(N===null){m({kind:"foreign",reason:"the directory has no control key, so the process listening on its channel cannot be its daemon"});return}let z=oo();u={key:N,challenge:I.value.challenge,nonce:z};let ue=so(N,I.value.challenge,z,e);i.write(`${JSON.stringify({type:e,nonce:z,proof:ue})}
|
|
145
|
+
`);return}let b=uo(S,by);if(!b.ok){m({kind:"silent",reason:`its answer is not one this version reads (${b.reason})`});return}if(!lo(ao(u.key,u.challenge,u.nonce),b.value.proof)){m({kind:"foreign",reason:"it could not prove the key of this directory \u2014 it is not this directory's daemon"});return}m({kind:"live",status:b.value.status})},"onLine");i.setEncoding("utf8"),i.on("connect",()=>{c=!0}),i.on("data",S=>{if(a+=S,a.length>Sy){m({kind:"silent",reason:"its answer exceeded the size of a status"});return}for(;;){let b=a.indexOf(`
|
|
146
|
+
`);if(b===-1||d)return;let I=a.slice(0,b);a=a.slice(b+1),E(I)}}),i.on("end",()=>{m(u===null?{kind:"silent",reason:"it closed the connection without a greeting"}:{kind:"foreign",reason:"it closed the connection without an answer \u2014 it did not accept the key of this directory"})}),i.on("error",S=>{let b=Cn(S);if(!c&&(b==="ENOENT"||b==="ECONNREFUSED")){m({kind:"none"});return}if(c){m({kind:"silent",reason:`the connection failed: ${S.message}`});return}m(S)})})}o(Jc,"askOwner");function _y(t){try{return yy(t).isDirectory()}catch(e){if(Cn(e)==="ENOENT"||Cn(e)==="ENOTDIR")return!1;throw e}}o(_y,"directoryExists");function uo(t,e){let n;try{n=JSON.parse(t)}catch{return{ok:!1,reason:"not JSON"}}let r=e.safeParse(n);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:r.error.message}}o(uo,"parseLine");function h(t){process.stdout.write(`${C(t)}
|
|
147
|
+
`)}o(h,"say");function Nn(t){return t.source==="env"?` --state-dir "${t.path}"`:""}o(Nn,"stateDirOption");function j(t){let e=t.phase==="starting"?"starting up":t.phase==="stopping"?"stopping":t.activeRunId===null?"idle":`running ${t.activeRunId}`;return`pid ${t.pid}, version ${t.version}, since ${t.startedAt}, ${e}`}o(j,"describeOwner");function mo(t){try{let e=new URL(t);return e.username===""&&e.password===""?t:(e.username="***",e.password="",e.toString())}catch{return"[unparseable value]"}}o(mo,"maskUrlCredentials");import{spawn as ky}from"node:child_process";import{existsSync as Vc,readFileSync as qc}from"node:fs";import{basename as Ai,dirname as gt,join as Ln}from"node:path";import{fileURLToPath as Ry}from"node:url";var we="progon-agent";function Qt(){let t=Se(gt(Ry(import.meta.url))),e=gt(t);if(Ai(t)!==we||Ai(e)!=="node_modules")return{kind:"not_global",packageRoot:t};let n;if(process.platform==="win32"){if(n=gt(e),!Ty(n))return{kind:"not_global",packageRoot:t}}else{let r=gt(e);if(Ai(r)!=="lib")return{kind:"not_global",packageRoot:t};n=gt(r)}return{kind:"npm_global",packageRoot:t,prefix:n,npmCli:xy(n)}}o(Qt,"locateInstallation");function Ty(t){try{return qc(Ln(t,`${we}.cmd`),"utf8").toLowerCase().includes(`"%dp0%\\node_modules\\${we}\\dist\\supervisor\\cli.js"`)}catch(e){if(P(e))return!1;throw e}}o(Ty,"hasGlobalWindowsShim");function Kc(t){return process.platform==="win32"?Ln(t,"node_modules","npm","bin","npm-cli.js"):Ln(t,"lib","node_modules","npm","bin","npm-cli.js")}o(Kc,"npmCliUnder");function xy(t){let e=gt(process.execPath),n=process.platform==="win32"?e:gt(e);for(let r of[Kc(n),Kc(t)])if(Vc(r))return r;return null}o(xy,"findNpmCli");async function fo(t,e){return Dn(t,e)}o(fo,"runNpm");async function Dn(t,e){return new Promise((n,r)=>{let i=ky(process.execPath,[t,...e],{stdio:"inherit",env:process.env});i.once("error",r),i.once("exit",s=>n(s))})}o(Dn,"runNode");function Ci(t){let e=Ln(t,"package.json"),n;try{n=JSON.parse(qc(e,"utf8"))}catch(a){return{kind:"damaged",reason:a instanceof Error?a.message:String(a)}}let r=typeof n=="object"&&n!==null?n:{},i=r.version,s=r.bin,l=typeof s=="object"&&s!==null?s[we]:void 0;if(typeof i!="string"||typeof l!="string")return{kind:"damaged",reason:`${e} has no version or no '${we}' bin`};let c=Ln(t,l);return Vc(c)?{kind:"installed",version:i,cliPath:c}:{kind:"damaged",reason:`${c} is missing`}}o(Ci,"readInstalledPackage");import{execFile as Iy}from"node:child_process";var $n=3e4;function X(t,e,n={}){let r=n.timeoutMs??$n;return new Promise(i=>{Iy(t,[...e],{timeout:r,windowsHide:!0,encoding:"utf8"},(s,l,c)=>{if(s===null){i({exitCode:0,stdout:l,stderr:c});return}let a=s.code;if(typeof a=="number"){i({exitCode:a,stdout:l,stderr:c});return}i({exitCode:null,stdout:l,stderr:c,failure:a==="ENOENT"?`'${t}' is not installed or not on PATH`:s.killed===!0?`'${t}' did not finish within ${r/1e3} s`:s.message})})})}o(X,"runOsCommand");function Xe(t,e,n){let r=[t,...e].join(" ");if(n.exitCode===null)return`${r}: ${n.failure}`;let i=(n.stderr.trim()||n.stdout.trim()).split(`
|
|
148
|
+
`).slice(0,3).join(" / ");return`${r} exited ${n.exitCode}${i===""?"":`: ${i}`}`}o(Xe,"describeOsFailure");async function ie(t,e,n={}){let r=await X(t,e,n);if(r.exitCode!==0)throw new _(Xe(t,e,r));return r}o(ie,"runOsCommandOrThrow");var _=class extends Error{static{o(this,"ServiceManagerError")}name="ServiceManagerError"};function ke(t,e,n){try{return n()}catch(r){throw Oy(r)?new _(`Could not ${t} ${e}: ${r.message}`,{cause:r}):r}}o(ke,"registrationFileStep");function Oy(t){if(!(t instanceof Error))return!1;let{code:e,syscall:n}=t;return typeof e=="string"&&typeof n=="string"}o(Oy,"isFileSystemError");import{mkdirSync as Gy,readFileSync as Fy,readdirSync as By,renameSync as jy,unlinkSync as Wy,writeFileSync as Hy}from"node:fs";import{homedir as Jy}from"node:os";import{setTimeout as Ky}from"node:timers/promises";import{join as go}from"node:path";import{z as Ni}from"zod";import{setTimeout as Ay}from"node:timers/promises";var Ce=9e4,Cy=250;async function Yc(t,e){let n=await Hc(t);if(n.kind==="none")return{kind:"not_running"};if(n.kind==="silent")throw new p(`A process owns ${t} but did not say which one (${n.reason}), so it cannot be stopped from here. Stop it where it runs (Ctrl-C in its terminal) and run the command again.`);if(n.kind==="foreign")throw new p(`The control channel of ${t} is held by a process that is not its progon-agent (${n.reason}). Nothing was stopped. Find that process \u2014 on Windows, another user's process can hold the channel name \u2014 and end it, then run the command again.`);let{status:r}=n;e(r);let i=Date.now()+Ce;for(;Date.now()<i;){if((await $(t)).kind==="none")return{kind:"stopped",status:r};await Ay(Cy)}throw new p(`progon-agent (pid ${r.pid}) is still shutting down after ${Ce/1e3} s. Its log says what it is waiting for; run the command again once it has exited.`)}o(Yc,"stopStateDirOwner");import{createHash as Py}from"node:crypto";import{realpathSync as Ny}from"node:fs";import{homedir as Ly}from"node:os";import{dirname as Dy,join as Xc,resolve as Pi}from"node:path";import{fileURLToPath as $y}from"node:url";var Uy=Xc("dist","supervisor","cli.js"),ze="service.log",ho="service-error.log";function zc(t){return Zc()?.(t)===!0}o(zc,"isServiceFileEntry");function Qc(){return Zc()!==null}o(Qc,"serviceWritesFiles");function Zc(){switch(process.platform){case"darwin":return t=>t===ze;case"win32":return t=>t===ze||t===ho||/^progon-agent(-[0-9a-f]{8})?\.task-[0-9a-f]{16}\.xml$/.test(t);default:return null}}o(Zc,"serviceFileMatcher");var Un="progon-agent";function se(t){return{stateDir:t,name:Zt(t)}}o(se,"serviceTargetFor");function Zt(t){let e=Pi(t);if(My(e))return Un;let n=process.platform==="win32"?e.toLowerCase():e;return`${Un}-${Py("sha256").update(n).digest("hex").slice(0,8)}`}o(Zt,"serviceNameFor");function My(t){let e;try{e=Pi(hn(process.platform,process.env,Ly()))}catch(n){if(n instanceof p)return!1;throw n}return process.platform==="win32"?e.toLowerCase()===t.toLowerCase():e===t}o(My,"isStandardStateDir");function en(){let t=Se(Dy($y(import.meta.url))),e=Xc(t,Uy);try{return Ny(e)}catch(n){throw new p(`This installation has no ${e} to register as a service (${n instanceof Error?n.message:String(n)}). Build or reinstall progon-agent.`)}}o(en,"packageCliPath");function ed(t){let e=Pi(t);if(/[\r\n\0]/.test(e))throw new p("The state directory path contains a line break, so it cannot be written into a service registration. Use another --state-dir.");let n=[];for(let r of sa){let i=process.env[r];if(i!==void 0){if(/[\r\n\0]/.test(i))throw new p(`${r} contains a line break, so it cannot be written into the service registration. Fix the variable and run the command again.`);n.push([r,i])}}return{stateDir:e,name:Zt(e),program:[process.execPath,en(),"start","--state-dir",e,"--service"],environment:n}}o(ed,"buildServiceDefinition");function td(t){let e=t.indexOf("--state-dir"),n=e===-1?void 0:t[e+1];return n===void 0||!t.includes("--service")?null:n}o(td,"stateDirOfProgram");var sd="io.progon.agent",Vy=/^io\.progon\.agent(-[0-9a-f]{8})?\.plist$/;function yo(t){return`${sd}${t.slice(Un.length)}`}o(yo,"labelOf");function qy(t){return`${Un}${t.slice(sd.length)}`}o(qy,"nameOfLabel");function Di(){return go(Jy(),"Library","LaunchAgents")}o(Di,"agentsDir");function Mn(t){return go(Di(),`${yo(t)}.plist`)}o(Mn,"plistPath");function rn(){let t=process.getuid?.();if(t===void 0)throw new Error("[launchd-service] process.getuid is unavailable");return`gui/${t}`}o(rn,"domain");function Qe(t){return`${rn()}/${yo(t)}`}o(Qe,"target");function tn(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}o(tn,"xml");function nd(t){let e=tn(go(t.stateDir,ze)),n=t.program.map(i=>` <string>${tn(i)}</string>`).join(`
|
|
149
|
+
`),r=t.environment.map(([i,s])=>` <key>${tn(i)}</key>
|
|
150
|
+
<string>${tn(s)}</string>`).join(`
|
|
151
151
|
`);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
152
152
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
153
153
|
<plist version="1.0">
|
|
154
154
|
<dict>
|
|
155
155
|
<key>Label</key>
|
|
156
|
-
<string>${
|
|
156
|
+
<string>${tn(yo(t.name))}</string>
|
|
157
157
|
<key>ProgramArguments</key>
|
|
158
158
|
<array>
|
|
159
159
|
${n}
|
|
@@ -163,7 +163,7 @@ ${n}
|
|
|
163
163
|
${r}
|
|
164
164
|
</dict>
|
|
165
165
|
<key>WorkingDirectory</key>
|
|
166
|
-
<string>${
|
|
166
|
+
<string>${tn(t.stateDir)}</string>
|
|
167
167
|
<key>RunAtLoad</key>
|
|
168
168
|
<true/>
|
|
169
169
|
<key>KeepAlive</key>
|
|
@@ -183,7 +183,7 @@ ${r}
|
|
|
183
183
|
<string>${e}</string>
|
|
184
184
|
</dict>
|
|
185
185
|
</plist>
|
|
186
|
-
`}o(
|
|
186
|
+
`}o(nd,"renderPlist");function rd(t){return ke("read the LaunchAgent",t,()=>{try{return Fy(t,"utf8")}catch(e){if(e.code==="ENOENT")return null;throw e}})}o(rd,"readFileOrNull");async function nn(t){let e=await X("launchctl",["print",Qe(t)]);if(e.exitCode===null)throw new _(Xe("launchctl",["print",Qe(t)],e));return e.exitCode===0}o(nn,"isLoaded");var od=1e4,Yy=100;async function Li(t){await ie("launchctl",["bootout",Qe(t)],{timeoutMs:Ce+$n});let e=Date.now()+od;for(;await nn(t);){if(Date.now()>e)throw new _(`launchd still has ${Qe(t)} loaded ${od/1e3} s after bootout; run the command again.`);await Ky(Yy)}}o(Li,"bootout");async function id(t){let e=await X("launchctl",["print-disabled",rn()]);if(e.exitCode!==0)return null;let n=yo(t).replace(/\./g,"\\."),r=new RegExp(`^\\s*"${n}" => (\\w+)$`,"m").exec(e.stdout)?.[1];return r!=="disabled"&&r!=="true"}o(id,"isEnabled");var Xy=Ni.object({ProgramArguments:Ni.array(Ni.string())});async function zy(t){let e=await X("plutil",["-convert","json","-o","-",t]);if(e.exitCode!==0)return null;try{let n=Xy.safeParse(JSON.parse(e.stdout));return n.success?n.data.ProgramArguments:null}catch{return null}}o(zy,"readProgram");var ad={description:"a LaunchAgent (launchd) \u2014 starts when you log in",async isCurrent(t){return rd(Mn(t.name))===nd(t)&&await nn(t.name)&&await id(t.name)===!0},async install(t){let e=Mn(t.name);return await nn(t.name)&&await Li(t.name),ke("write the LaunchAgent",e,()=>{Gy(Di(),{recursive:!0});let n=`${e}.tmp-${process.pid}`;Hy(n,nd(t),{mode:384}),jy(n,e)}),await ie("launchctl",["enable",Qe(t.name)]),await ie("launchctl",["bootstrap",rn(),e]),[]},async start(t){await nn(t)?await ie("launchctl",["kickstart",Qe(t)]):(await ie("launchctl",["enable",Qe(t)]),await ie("launchctl",["bootstrap",rn(),Mn(t)]))},async stop(t){await nn(t)&&await Li(t)},async remove(t){let e=Mn(t),n=await nn(t);return n&&await Li(t),ke("delete the LaunchAgent",e,()=>{try{return Wy(e),!0}catch(i){if(i.code!=="ENOENT")throw i;return!1}})||n?"removed":"absent"},async read(t){let e=Mn(t);if(rd(e)===null)return{kind:"absent"};let n=[],r=null,i=await X("launchctl",["print",Qe(t)]);if(i.exitCode===0){let s=/^\s*state = (.+)$/m.exec(i.stdout)?.[1],l=/^\s*pid = (\d+)$/m.exec(i.stdout)?.[1],c=/^\s*last exit code = (.+)$/m.exec(i.stdout)?.[1];r=l!==void 0||c!==void 0&&c!=="0",n.push(`loaded in ${rn()}`+(s===void 0?"":`, ${s}`)+(l===void 0?"":`, pid ${l}`)+(c===void 0?"":`, last exit: ${c}`))}else i.exitCode===null?n.push(`launchd could not be asked: ${i.failure}`):(r=!1,n.push(`not loaded in ${rn()}`));return{kind:"registered",location:e,program:await zy(e),facts:n,active:r,autostart:o(()=>id(t),"autostart")}},async registeredNames(){let t;try{t=By(Di())}catch(e){if(e.code==="ENOENT")return[];throw e}return t.filter(e=>Vy.test(e)).map(e=>qy(e.slice(0,-6)))},logHint(t){return go(t.stateDir,ze)}};import{mkdirSync as Qy,readdirSync as Zy,readFileSync as ew,renameSync as tw,unlinkSync as nw,writeFileSync as rw}from"node:fs";import{homedir as ow,userInfo as ld}from"node:os";import{isAbsolute as iw,join as $i}from"node:path";import{z as cd}from"zod";var sw=/^progon-agent(-[0-9a-f]{8})?\.service$/,Ui="# progon-agent program: ";function Mi(){let t=process.env.XDG_CONFIG_HOME,e=t!==void 0&&iw(t)?t:$i(ow(),".config");return $i(e,"systemd","user")}o(Mi,"unitDir");function Pe(t){return`${t}.service`}o(Pe,"unitName");function Gn(t){return $i(Mi(),Pe(t))}o(Gn,"unitPath");function dd(t,e){let n=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/%/g,"%%");return e&&(n=n.replace(/\$/g,"$$$$")),`"${n}"`}o(dd,"quote");function ud(t){let e=t.program.map(r=>dd(r,!0)).join(" "),n=t.environment.map(([r,i])=>`Environment=${dd(`${r}=${i}`,!1)}
|
|
187
187
|
`).join("");return`${Ui}${JSON.stringify(t.program)}
|
|
188
188
|
[Unit]
|
|
189
189
|
Description=Progon agent (${t.stateDir.replace(/%/g,"%%")})
|
|
@@ -200,13 +200,13 @@ KillMode=mixed
|
|
|
200
200
|
|
|
201
201
|
[Install]
|
|
202
202
|
WantedBy=default.target
|
|
203
|
-
`}o(
|
|
204
|
-
`,1)[0];if(e===void 0||!e.startsWith(Ui))return null;try{let n=
|
|
205
|
-
`).filter(m=>m.includes("=")).map(m=>[m.slice(0,m.indexOf("=")),m.slice(m.indexOf("=")+1)])),d=a.get("ActiveState");d!==void 0&&(i=!["inactive","failed"].includes(d));let u=a.get("UnitFileState");u==="enabled"?s=!0:(u==="disabled"||u==="masked")&&(s=!1),r.push(`${a.get("UnitFileState")??"unknown"} (unit file), ${a.get("ActiveState")??"unknown"}/${a.get("SubState")??"unknown"}, last exit status ${a.get("ExecMainStatus")??"unknown"}`)}else r.push(`systemd could not be asked: ${Xe("systemctl",["--user","show"],l)}`);let c=await X("loginctl",["show-user",
|
|
206
|
-
`)}o(
|
|
203
|
+
`}o(ud,"renderUnit");function wo(t){return ke("read the systemd unit",t,()=>{try{return ew(t,"utf8")}catch(e){if(e.code==="ENOENT")return null;throw e}})}o(wo,"readFileOrNull");var aw=cd.array(cd.string());function lw(t){let e=t.split(`
|
|
204
|
+
`,1)[0];if(e===void 0||!e.startsWith(Ui))return null;try{let n=aw.safeParse(JSON.parse(e.slice(Ui.length)));return n.success?n.data:null}catch{return null}}o(lw,"programOf");async function on(t,e=!1){await ie("systemctl",["--user",...t],e?{timeoutMs:Ce+$n}:{})}o(on,"systemctl");async function cw(t){return(await X("systemctl",["--user","is-enabled",Pe(t)])).exitCode===0}o(cw,"isEnabled");var pd={description:"a systemd user service \u2014 starts at boot (with lingering) or at login",async isCurrent(t){return wo(Gn(t.name))===ud(t)&&await cw(t.name)},async install(t){let e=[],n=Gn(t.name);ke("write the systemd unit",n,()=>{Qy(Mi(),{recursive:!0});let i=`${n}.tmp-${process.pid}`;rw(i,ud(t),{mode:384}),tw(i,n)}),await on(["daemon-reload"]),await on(["enable",Pe(t.name)]);let r=await X("loginctl",["enable-linger"]);return r.exitCode!==0&&e.push(`Lingering could not be turned on (${Xe("loginctl",["enable-linger"],r)}), so the service starts when you log in, not at boot. To start it at boot: sudo loginctl enable-linger ${ld().username}`),e},async start(t){await on(["start",Pe(t)])},async stop(t){wo(Gn(t))!==null&&await on(["stop",Pe(t)],!0)},async remove(t){let e=Gn(t);return wo(e)===null?"absent":(await on(["disable","--now",Pe(t)],!0),ke("delete the systemd unit",e,()=>nw(e)),await on(["daemon-reload"]),await X("systemctl",["--user","reset-failed",Pe(t)]),"removed")},async read(t){let e=Gn(t),n=wo(e);if(n===null)return{kind:"absent"};let r=[],i=null,s=null,l=await X("systemctl",["--user","show",Pe(t),"--property=UnitFileState,ActiveState,SubState,MainPID,ExecMainStatus,Result"]);if(l.exitCode===0){let a=new Map(l.stdout.split(`
|
|
205
|
+
`).filter(m=>m.includes("=")).map(m=>[m.slice(0,m.indexOf("=")),m.slice(m.indexOf("=")+1)])),d=a.get("ActiveState");d!==void 0&&(i=!["inactive","failed"].includes(d));let u=a.get("UnitFileState");u==="enabled"?s=!0:(u==="disabled"||u==="masked")&&(s=!1),r.push(`${a.get("UnitFileState")??"unknown"} (unit file), ${a.get("ActiveState")??"unknown"}/${a.get("SubState")??"unknown"}, last exit status ${a.get("ExecMainStatus")??"unknown"}`)}else r.push(`systemd could not be asked: ${Xe("systemctl",["--user","show"],l)}`);let c=await X("loginctl",["show-user",ld().username,"--property=Linger"]);return c.exitCode===0&&r.push(c.stdout.trim()==="Linger=yes"?"lingering on: starts at boot":"lingering off: starts at login"),{kind:"registered",location:e,program:lw(n),facts:r,active:i,autostart:o(()=>Promise.resolve(s),"autostart")}},async registeredNames(){let t;try{t=Zy(Mi())}catch(e){if(e.code==="ENOENT")return[];throw e}return t.filter(e=>sw.test(e)).map(e=>e.slice(0,-8))},logHint(t){return`journalctl --user -u ${Pe(t.name)}`}};import{randomBytes as dw}from"node:crypto";import{unlinkSync as uw,writeFileSync as pw}from"node:fs";import{join as Fn}from"node:path";import{z as J}from"zod";var mw="^progon-agent(-[0-9a-f]{8})?$",Bi="progon-agent program: ";function fw(t){if(t!==""&&!/[\s"]/.test(t))return t;let e='"',n=0;for(let r of t){if(r==="\\"){n+=1;continue}r==='"'?e+=`${"\\".repeat(n*2+1)}"`:e+=`${"\\".repeat(n)}${r}`,n=0}return`${e}${"\\".repeat(n*2)}"`}o(fw,"quoteWindowsArg");function hw(t){let[e,...n]=t.program;if(e===void 0)throw new Error("[task-scheduler-service] the program has no executable");return["$ErrorActionPreference = 'Stop'",...t.environment.map(([i,s])=>`$env:${i} = ${me(s)}`),`$p = Start-Process -FilePath ${me(e)} -ArgumentList ${me(n.map(fw).join(" "))} -WorkingDirectory ${me(t.stateDir)} -NoNewWindow -Wait -PassThru -RedirectStandardOutput ${me(Fn(t.stateDir,ze))} -RedirectStandardError ${me(Fn(t.stateDir,ho))}`,"exit $p.ExitCode"].join(`
|
|
206
|
+
`)}o(hw,"renderWrapperScript");function md(t){return`-NoProfile -NonInteractive -WindowStyle Hidden -EncodedCommand ${pn(hw(t))}`}o(md,"actionArguments");function fd(t){return`${Bi}${JSON.stringify(t.program)}`}o(fd,"description");function Gi(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}o(Gi,"xml");function gw(){let t=process.env.USERNAME,e=process.env.USERDOMAIN;if(t===void 0||t===""||e===void 0||e==="")throw new p("USERNAME or USERDOMAIN is not set, so the logon task cannot name the user it runs for. Run the command from your own Windows session.");return`${e}\\${t}`}o(gw,"currentUserId");function yw(t){let e=Gi(gw());return`<?xml version="1.0" encoding="UTF-16"?>
|
|
207
207
|
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
208
208
|
<RegistrationInfo>
|
|
209
|
-
<Description>${Gi(
|
|
209
|
+
<Description>${Gi(fd(t))}</Description>
|
|
210
210
|
</RegistrationInfo>
|
|
211
211
|
<Triggers>
|
|
212
212
|
<LogonTrigger>
|
|
@@ -247,40 +247,40 @@ WantedBy=default.target
|
|
|
247
247
|
<Actions Context="Author">
|
|
248
248
|
<Exec>
|
|
249
249
|
<Command>${tt}</Command>
|
|
250
|
-
<Arguments>${Gi(
|
|
250
|
+
<Arguments>${Gi(md(t))}</Arguments>
|
|
251
251
|
</Exec>
|
|
252
252
|
</Actions>
|
|
253
253
|
</Task>
|
|
254
|
-
`}o(
|
|
255
|
-
${t}`)],r=await X(tt,n);if(r.exitCode!==0)throw new _(Xe(tt,["-EncodedCommand","\u2026"],r));let i;try{i=JSON.parse(r.stdout.replace(/^/,""))}catch{throw new _("PowerShell returned invalid JSON for the service command.")}let s=e.safeParse(i);if(!s.success)throw new _(`PowerShell answered in a form this version does not read: ${s.error.message}`);return s.data}o(ji,"powershellJson");var
|
|
254
|
+
`}o(yw,"renderTaskXml");async function ji(t,e){let n=["-NoProfile","-NonInteractive","-EncodedCommand",pn(`[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
|
255
|
+
${t}`)],r=await X(tt,n);if(r.exitCode!==0)throw new _(Xe(tt,["-EncodedCommand","\u2026"],r));let i;try{i=JSON.parse(r.stdout.replace(/^/,""))}catch{throw new _("PowerShell returned invalid JSON for the service command.")}let s=e.safeParse(i);if(!s.success)throw new _(`PowerShell answered in a form this version does not read: ${s.error.message}`);return s.data}o(ji,"powershellJson");var ww=J.union([J.object({registered:J.literal(!1)}),J.object({registered:J.literal(!0),description:J.string().nullable(),arguments:J.string().nullable(),state:J.string(),lastResult:J.number().nullable(),lastRun:J.string().nullable()})]);async function Fi(t){return ji(`$t = Get-ScheduledTask -TaskPath '\\' -TaskName ${me(t)} -ErrorAction SilentlyContinue
|
|
256
256
|
if ($null -eq $t) { '{"registered":false}'; exit 0 }
|
|
257
257
|
$i = $t | Get-ScheduledTaskInfo
|
|
258
|
-
[pscustomobject]@{ registered = $true; description = $t.Description; arguments = $t.Actions[0].Arguments; state = [string]$t.State; lastResult = $i.LastTaskResult; lastRun = [string]$i.LastRunTime } | ConvertTo-Json -Compress`,
|
|
258
|
+
[pscustomobject]@{ registered = $true; description = $t.Description; arguments = $t.Actions[0].Arguments; state = [string]$t.State; lastResult = $i.LastTaskResult; lastRun = [string]$i.LastRunTime } | ConvertTo-Json -Compress`,ww)}o(Fi,"readTask");var Sw=J.array(J.string());function Ew(t){if(t===null||!t.startsWith(Bi))return null;try{let e=Sw.safeParse(JSON.parse(t.slice(Bi.length)));return e.success?e.data:null}catch{return null}}o(Ew,"programOf");var Wi={description:"a Task Scheduler task \u2014 starts when you log in",async isCurrent(t){let e=await Fi(t.name);return e.registered&&e.state!=="Disabled"&&e.description===fd(t)&&e.arguments===md(t)},async install(t){xt(t.stateDir);let e=Fn(t.stateDir,`${t.name}.task-${dw(8).toString("hex")}.xml`);ke("write the task definition",e,()=>pw(e,`\uFEFF${yw(t)}`,{encoding:"utf16le",mode:384,flag:"wx"}));try{await ie("schtasks",["/Create","/TN",t.name,"/XML",e,"/F"])}finally{uw(e)}return[]},async start(t){await ie("schtasks",["/Run","/TN",t])},async stop(t){await ji(`$t = Get-ScheduledTask -TaskPath '\\' -TaskName ${me(t)} -ErrorAction SilentlyContinue
|
|
259
259
|
if ($null -ne $t) { $t | Stop-ScheduledTask -ErrorAction Stop }
|
|
260
|
-
'null'`,K.null())},async remove(t){return(await Fi(t)).registered?(await Wi.stop(t),await ie("schtasks",["/Delete","/TN",t,"/F"]),"removed"):"absent"},async read(t){let e=await Fi(t);if(!e.registered)return{kind:"absent"};let n=[`task state: ${e.state}`+(e.lastResult===null?"":`, last result: ${e.lastResult}`)+(e.lastRun===null||e.lastRun===""?"":`, last run: ${e.lastRun}`)];return{kind:"registered",location:`Task Scheduler \\${t}`,program:vw(e.description),facts:n,active:e.state==="Running"||e.state==="Queued"?!0:e.state==="Disabled"||e.lastResult===0||e.lastResult===267011||e.lastResult===267014?!1:null,autostart:o(()=>Promise.resolve(e.state==="Disabled"?!1:e.state==="Unknown"?null:!0),"autostart")}},async registeredNames(){return ji(`ConvertTo-Json -Compress -InputObject @(Get-ScheduledTask -TaskPath '\\' -ErrorAction SilentlyContinue | Where-Object { $_.TaskName -match '${fw}' } | ForEach-Object { $_.TaskName })`,K.array(K.string()))},logHint(t){return`${Gn(t.stateDir,ze)} and ${Gn(t.stateDir,ho)}`}};function ce(){switch(process.platform){case"darwin":return ld;case"linux":return md;case"win32":return Wi;default:throw new p(`progon-agent has no OS service for platform ${process.platform} (supported: macOS, Linux, Windows). Run 'progon-agent start' under your own supervisor.`)}}o(ce,"platformServiceManager");async function Eo(t){let e=await t.autostart();return e===null?"unknown":e?"on":"off \u2014 registered but disabled in the OS (turn on: 'progon-agent service enable')"}o(Eo,"describeAutostartState");async function vo(t){return ce().read(Qt(t))}o(vo,"readServiceOf");async function bo(){let t=ce(),e=Zt(),n=[],r=[],i=[];for(let s of await t.registeredNames()){let l=await t.read(s);if(l.kind==="absent")continue;let c=l.program,a=c===null?null:nd(c);c===null||a===null?i.push(l.location):c[1]===e?n.push({name:s,stateDir:a}):r.push(s)}return{services:n,foreign:r,unreadable:i}}o(bo,"thisInstallationServices");async function _o(t){let e=ce();if(Zc()&&(await e.read(t.name)).kind!=="absent")try{el(t.stateDir)}catch(n){throw new _(`Could not retain service-file ownership for ${t.stateDir}: ${n instanceof Error?n.message:String(n)}. The registration is kept; fix the cause and retry.`,{cause:n})}return e.remove(t.name)}o(_o,"unregisterService");var Tw={ok:"[ok] ",warn:"[warn]",fail:"[FAIL]",info:"[info]"};function de(t){return t instanceof Error?t.message:String(t)}o(de,"describe");async function gd(){let t=0,e=o((l,c,a)=>{l==="fail"&&(t+=1),h(`${Tw[l]} ${c}: ${a}`)},"report");e("info","progon-agent",`${te()} on Node ${process.version} (${process.execPath})`),xw(e);let n=G().path;Iw(n,e),await Ow(n,e);let r=t,i=Cw(e);t===r?Nw(e):e("info","Start","not checked \u2014 'progon-agent start' refuses the settings above");let s=await Lw(e);return await Dw(s,i,e),await Aw(n,e),h(t===0?"No problems found.":`${t} check(s) failed \u2014 see [FAIL] above.`),t===0?0:1}o(gd,"runDoctorCommand");function xw(t){let e=zt();if(e.kind==="not_global"){t("info","Installation",`not a global npm install (${e.packageRoot}); 'update' cannot replace it and 'uninstall' leaves the package in place`);return}t(e.npmCli===null?"warn":"ok","Installation",`npm global install at ${e.prefix}`+(e.npmCli===null?" \u2014 no npm was found beside this node, so 'progon-agent update' cannot run it":""))}o(xw,"checkInstallation");function Iw(t,e){try{Rw(t)}catch(n){if(P(n)){e("info","State directory",`${t} does not exist yet (created by 'enroll')`);return}e("fail","State directory",`${t}: ${de(n)}`);return}try{bw(t,kw.W_OK)}catch(n){e("fail","State directory",`${t} is not writable by this user: ${de(n)}`);return}try{let n=L(t);n===null?e("warn","Enrollment",`${t} holds no enrollment \u2014 run 'progon-agent enroll'`):e("ok","Enrollment",`agent ${n.agentId} at ${n.serverUrl} (${t})`)}catch(n){if(!(n instanceof p))throw n;e("fail","Enrollment",`${de(n)} 'progon-agent reset' removes it.`)}}o(Iw,"checkStateDir");async function Ow(t,e){try{let n=await $(t);if(n.kind==="none")e("info","Agent","not running");else if(n.kind==="live"){let r=n.status.service?"as the service":"outside the service";e("info","Agent",`running ${r} \u2014 ${j(n.status)}`)}else e("warn","Agent",`a process owns the state directory, but ${n.reason}`)}catch(n){e("warn","Agent",`cannot ask the control channel: ${de(n)}`)}}o(Ow,"checkAgentProcess");async function Aw(t,e){let n;try{n=await vo(t)}catch(a){if(!(a instanceof _)&&!(a instanceof p))throw a;e("warn","Autostart",`the OS service manager could not be asked: ${de(a)}`);return}if(n.kind==="absent"){e("info","Autostart","off \u2014 no OS service is registered ('progon-agent service enable')");return}let r=`${n.location} (${n.facts.join("; ")})`,i=n.program;if(i===null||i.length<2){e("warn","Autostart",`${r}: the command it starts could not be read`);return}let[s,l]=i,c=[s,l].filter(a=>!_w(a));if(c.length>0){e("fail","Autostart",`${r}: it starts ${c.join(" and ")}, which no longer exist(s). Refresh it: progon-agent service enable --state-dir "${t}"`);return}if(s!==process.execPath||l!==Zt()){e("warn","Autostart",`${r}: it starts ${s} ${l}, not this node and installation (${process.execPath} ${Zt()}). Refresh it: progon-agent service enable --state-dir "${t}"`);return}e("ok","Autostart",r)}o(Aw,"checkService");function Cw(t){try{let e=dn(process.env),n=[e.https,e.http].filter(r=>r!==void 0);if(n.length===0)t("ok","Proxy","none configured (HTTPS_PROXY / HTTP_PROXY unset)");else{let r=n.map(s=>`${s.variable}=${mo(s.url)}`).join(", "),i=e.noProxy===void 0?"":`, NO_PROXY=${e.noProxy}`;t("ok","Proxy",`${r}${i}`)}}catch(e){if(!(e instanceof p))throw e;t("fail","Proxy",de(e))}Pw(t);try{let e=hn();return t("ok","Browser settings","PROGON_AGENT_* values are valid"),e}catch(e){if(!(e instanceof p))throw e;return t("fail","Browser settings",de(e)),null}}o(Cw,"checkConfiguration");function Pw(t){let e=[],n=!1;try{let r=Zn(process.env);r!==void 0&&e.push(`${r.variable}=${r.path} (readable)`)}catch(r){if(!(r instanceof p))throw r;t("fail","Certificates",de(r)),n=!0}try{let r=Hs(process.env);r!==void 0&&e.push(`NODE_EXTRA_CA_CERTS=${r} (readable)`)}catch(r){if(!(r instanceof p))throw r;t("fail","Certificates",de(r)),n=!0}n||t("ok","Certificates",e.length===0?"system store only":e.join(", "))}o(Pw,"checkCertificates");function Nw(t){try{let e=Me(),n=yi(e);n!==null&&e.extensionDistOverride===void 0&&ci(n.source==="env_token"?null:n.agentId),n===null&&e.enrollmentCode!==void 0?t("ok","Start",`redeems PROGON_AGENT_ENROLL_CODE at ${e.serverUrl} on its first start`):n===null?t("info","Start",`${e.serverUrl} \u2014 not enrolled yet ('progon-agent enroll')`):t("ok","Start",`connects to ${e.serverUrl} with ${n.source==="env_token"?"PROGON_AGENT_TOKEN":`the enrollment of agent ${n.agentId}`}`)}catch(e){if(!(e instanceof p))throw e;t("fail","Start",`'progon-agent start' refuses: ${de(e)}`)}}o(Nw,"checkStart");async function Lw(t){h("Chromium: checking (downloads it if missing)\u2026");try{return await kt({stdio:"terminal"}),t("ok","Chromium","installed"),!0}catch(e){if(!(e instanceof Q))throw e;return t("fail","Chromium",de(e)),!1}}o(Lw,"checkChromium");async function Dw(t,e,n){if(e!==null&&e.disableBrowserSandbox){n("warn","Browser sandbox","switched off by PROGON_AGENT_DISABLE_BROWSER_SANDBOX");return}if(!t){n("info","Browser sandbox","not checked \u2014 Chromium is not installed");return}try{await Ir(),n("ok","Browser sandbox","Chromium starts with its sandbox")}catch(r){if(!(r instanceof p))throw r;n("fail","Browser sandbox",de(r))}}o(Dw,"checkSandbox");async function yd(){let t=G();return h(`progon-agent ${te()} (this installation)`),h(`State directory: ${t.path} (${t.source==="env"?"PROGON_RUNNER_STATE_DIR / --state-dir":"platform default"})`),h(`Enrollment: ${Mw(t.path)}`),process.env.PROGON_AGENT_TOKEN!==void 0&&process.env.PROGON_AGENT_TOKEN!==""&&h("PROGON_AGENT_TOKEN: set in this environment \u2014 a start from here authenticates with it, not with the enrollment above."),h(`Agent: ${await Uw(t.path)}`),h(`Autostart: ${await $w(t.path)}`),0}o(yd,"runStatusCommand");async function $w(t){try{let e=await vo(t);return e.kind==="absent"?"off (turn on: 'progon-agent service enable')":`${await Eo(e)} \u2014 ${ce().description}; ${e.facts.join("; ")}`}catch(e){if(e instanceof _||e instanceof p)return`unknown \u2014 ${e.message}`;throw e}}o($w,"describeAutostart");async function Uw(t){let e;try{e=await $(t)}catch(n){return`unknown \u2014 ${n instanceof Error?n.message:String(n)}`}return e.kind==="none"?"not running":e.kind==="live"?`running ${e.status.service?"as the service":"outside the service"} \u2014 ${j(e.status)}`:`a process owns this directory, but ${e.reason}`}o(Uw,"describeAgentProcess");function Mw(t){try{let e=L(t);return e===null?"not enrolled (run 'progon-agent enroll')":`agent ${e.agentId} at ${e.serverUrl}`}catch(e){if(e instanceof p)return`the state file cannot be used \u2014 ${e.message}`;throw e}}o(Mw,"describeEnrollment");import{setTimeout as Ww}from"node:timers/promises";import{setTimeout as Gw}from"node:timers/promises";function yt(t){if(t.service.kind==="failed")throw t.service.error}o(yt,"assertManagedServiceStopped");async function Ne(t,e,n="all",r){let i=ce(),{stateDir:s,name:l}=t,c=null,a=[];try{c=await i.read(l)}catch(S){if(!(S instanceof _))throw S;a.push(S)}let d=await $(s),u=d.kind==="live"&&d.status.service?!0:c?.kind==="registered"?c.active:null;c?.kind!=="absent"&&r?.(u);let m=n==="service_only"&&d.kind==="live"&&!d.status.service,g={kind:"not_running"},E=null;if(!m)try{g=await Xc(s,e)}catch(S){if(!(S instanceof p))throw S;E=S}if(c?.kind!=="absent")try{await i.stop(l)}catch(S){if(!(S instanceof _))throw S;a.push(S)}if(!m){let S=Date.now()+Ce;for(;(await $(s)).kind!=="none";){if(a.length>0||c?.kind==="absent"||Date.now()>=S)throw new p((E?.message??`A process still owns ${s}. Stop it where it runs and retry.`)+(a.length===0?"":` OS service: ${a.map(b=>b.message).join("; ")}`));await Gw(250)}d.kind==="live"&&(g={kind:"stopped",status:d.status})}return{owner:g,service:a.length>0?{kind:"failed",error:new _(a.map(S=>S.message).join("; "))}:c?.kind==="absent"?{kind:"absent"}:{kind:"stopped"}}}o(Ne,"stopManagedStateDirOwner");import{createInterface as Fw}from"node:readline/promises";var Bw=new Set(["y","yes","\u0434","\u0434\u0430"]),jw=new Set(["n","no","\u043D","\u043D\u0435\u0442"]);async function ko(t,e){if(process.stdin.isTTY!==!0||process.stdout.isTTY!==!0)return"no_answer";let n=Fw({input:process.stdin,output:process.stdout}),r=new Promise(s=>{n.once("close",()=>s(null))}),i=e==="yes"?"(Y/n)":"(y/N)";try{for(;;){let s=await Promise.race([n.question(`${t} ${i} `).catch(()=>null),r]);if(s===null)return"no_answer";let l=s.trim().toLowerCase();if(l==="")return e;if(Bw.has(l))return"yes";if(jw.has(l))return"no";h("Answer 'y' or 'n'.")}}finally{n.close()}}o(ko,"askYesNo");var wd=2e4,Hw=250;async function Sd(t){let e=G().path;switch(t){case"enable":return await Hi(e),0;case"disable":return await vd(e),0;case"start":return await Ro(se(e)),0;case"stop":return await To(e),0;case"restart":return await To(e),await Ro(se(e)),0;case"status":return await Vw(e),0}}o(Sd,"runServiceCommand");function Ed(t){h(t.service?`Stopping the service (${j(t)}) to apply the new registration\u2026`:`Stopping progon-agent started outside the service (${j(t)}) \u2014 the service takes over\u2026`)}o(Ed,"announceHandOver");function Kw(t){if(L(t)===null)throw new p(`${t} holds no enrollment, so a service there would stop at once. Enroll first: progon-agent enroll --autostart`)}o(Kw,"assertEnrolled");async function Hi(t){Kw(t);let e=ce(),n=td(t),r=await e.isCurrent(n),i=await $(t);if(i.kind==="live"&&i.status.service&&r){h(`The service ${n.name} is enabled and running (${j(i.status)}).`);return}yt(await Ne(n,Ed));let s=r?[]:await e.install(n);r||h(`Registered ${n.name} as ${e.description}.`),Jw(n),await e.start(n.name),await bd(n);for(let l of s)h(l)}o(Hi,"enableService");async function vd(t){let e=se(t),{name:n}=e,r=await $(t);yt(await Ne(e,s=>h(`Stopping the service (${j(s)})\u2026`),"service_only"));let i=await _o(e);h(i==="removed"?`Autostart is off: the service ${n} is removed. The enrollment is kept.`:`Autostart is off: no service is registered for ${t}.`),r.kind==="live"&&!r.status.service&&h(`progon-agent started outside the service is still running (${j(r.status)}).`)}o(vd,"disableService");async function Ro(t){let e=ce(),{stateDir:n,name:r}=t;if((await e.read(r)).kind==="absent"){h("No service is registered for this state directory \u2014 enabling it."),await Hi(n);return}let i=await $(n);if(i.kind==="live"&&i.status.service){h(`The service ${r} is already running (${j(i.status)}).`);return}yt(await Ne(t,Ed)),await e.start(r),await bd(t)}o(Ro,"startService");async function To(t){let e=await Ne(se(t),r=>h(`Stopping progon-agent (${j(r)})\u2026`));yt(e);let n=e.owner;n.kind==="stopped"?h(`Stopped progon-agent (pid ${n.status.pid}).`):e.service.kind==="stopped"?h(`Stopped the OS service for ${t}, including any scheduled restart.`):h(`No progon-agent is running for ${t}.`),e.service.kind==="stopped"&&h("Autostart stays on: it starts again with 'progon-agent service start' or by the OS.")}o(To,"stopService");async function bd(t){let e=Date.now()+wd;for(;Date.now()<e;){let s=await $(t.stateDir);if(s.kind==="live"&&s.status.service){h(`The service ${t.name} is running (${j(s.status)}).`);return}await Ww(Hw)}let n=ce(),r=await n.read(t.name),i=r.kind==="registered"?` The OS: ${r.facts.join("; ")}.`:"";throw new _(`The service ${t.name} was started but did not answer within ${wd/1e3} s.${i} Its log says why: ${n.logHint(t)}`)}o(bd,"waitForService");function Jw(t){if(t.environment.length===0)h("Settings from this environment: none.");else{h("Settings from this environment, written into the registration:");for(let[e,n]of t.environment){let r=/proxy/i.test(e)||e==="PLAYWRIGHT_DOWNLOAD_HOST"||e==="PROGON_SERVER_URL";h(` ${e}=${r?mo(n):n}`)}}process.env.PROGON_AGENT_TOKEN!==void 0&&process.env.PROGON_AGENT_TOKEN!==""&&h("PROGON_AGENT_TOKEN is not copied: the service authenticates with the enrollment.")}o(Jw,"describeEnvironment");async function Vw(t){let e=ce(),n=Qt(t),r=await e.read(n);if(h(`State directory: ${t}`),r.kind==="absent")h(`Autostart: off \u2014 no service ${n} is registered.`);else{h(`Autostart: ${await Eo(r)} \u2014 ${e.description}`),h(`Registration: ${r.location}`);for(let s of r.facts)h(` ${s}`);h(`Log: ${e.logHint({name:n,stateDir:t})}`)}let i=await $(t);i.kind==="none"?h("Process: not running"):i.kind==="live"?h(`Process: ${i.status.service?"the service":"started outside the service"} \u2014 ${j(i.status)}`):h(`Process: a process owns this directory, but ${i.reason}`)}o(Vw,"printServiceStatus");async function _d(t){let e=G(),n=t==="ask"?await qw():t;if(n==="keep")return h(`Autostart was not changed (no terminal to ask, no answer). Turn it on with: progon-agent service enable${Pn(e)}`),0;try{return n==="on"?await Hi(e.path):await vd(e.path),0}catch(r){let i=r instanceof p||r instanceof _;if(h(`This machine is enrolled, but autostart could not be ${n==="on"?"set up":"turned off"}`+(i?":":".")),i&&h(` ${r.message}`),h(`Retry: progon-agent service ${n==="on"?"enable":"disable"}${Pn(e)}`),!i)throw r;return 1}}o(_d,"applyAutostartAfterEnroll");async function qw(){let t=await ko("Start the runner automatically in the background?","yes");return t==="yes"?"on":t==="no"?"off":"keep"}o(qw,"askAutostart");import{readdirSync as Td,rmdirSync as Yw,rmSync as Ki}from"node:fs";import{basename as kd,join as Rd}from"node:path";function Le(t){return t instanceof Error?t.message:String(t)}o(Le,"describe");function xd(t){let e=[],n;try{n=Td(t,{withFileTypes:!0})}catch(a){return P(a)?e:[{path:t,reason:Le(a)}]}let r=new Set([kd(nt(t)),kd(pn(t))]),i=n.some(a=>r.has(a.name)&&!a.isDirectory()),s=n.some(a=>a.name===ft&&a.isFile()),l=Rd(t,Sr),c=null;try{c=vr(t);let a=i||s||c!==null,d=c===null?[]:c.profiles,u=Xw(t,n,e,a,d);(u.length>0||c===null&&a)&&(c={...c??Er,profiles:[...d,...u]},br(t,c))}catch(a){e.push({path:l,reason:Le(a)}),c=null}if(i)try{nr(t)}catch(a){e.push({path:nt(t),reason:Le(a)})}if(c!==null){let a=new ut(t);for(let d of c.profiles){let u=a.userDataDirFor(d);try{Ki(u,{recursive:!0,force:!0})}catch(m){e.push({path:u,reason:Le(m)})}}try{Ji(a.instancesRoot)}catch(d){e.push({path:a.instancesRoot,reason:Le(d)})}}for(let a of n){let d=c!==null&&c.extensionCopy&&al(a.name);if(!(c!==null&&(Za(a.name)||d||Hc(a.name)||c.serviceFiles&&Qc(a.name))))continue;let m=Rd(t,a.name);if(!(a.isDirectory()&&!d))try{Ki(m,{recursive:a.isDirectory(),force:!0})}catch(g){e.push({path:m,reason:Le(g)})}}if(c!==null&&e.length===0)try{Ki(l)}catch(a){e.push({path:l,reason:Le(a)})}return e}o(xd,"removeRunnerFiles");function Xw(t,e,n,r,i){if(!e.some(c=>c.name===sr&&c.isDirectory()))return[];let s=new ut(t),l=[];try{for(let c of Td(s.instancesRoot,{withFileTypes:!0}))if(c.isDirectory()&&!i.includes(c.name))try{s.read(c.name).runId===c.name?l.push(c.name):r&&n.push({path:s.userDataDirFor(c.name),reason:"Instance marker does not identify this profile; ownership is unknown and it was kept"})}catch(a){let d=typeof a=="object"&&a!==null?a.code:void 0;(r||d!==void 0&&!P(a))&&n.push({path:s.userDataDirFor(c.name),reason:`Cannot establish profile ownership; it was kept: ${Le(a)}`})}}catch(c){n.push({path:s.instancesRoot,reason:Le(c)})}return l}o(Xw,"findInstanceProfiles");function Ji(t){try{return Yw(t),"removed"}catch(e){if(P(e))return"absent";let n=e.code;if(n==="ENOTEMPTY"||n==="EEXIST")return"not_empty";throw e}}o(Ji,"removeDirectoryIfEmpty");async function on(t,e){let{stateDir:n}=t,r;try{r=await Ne(t,e)}catch(u){if(u instanceof p)return{kind:"owner_running",stateDir:n,reason:u.message};throw u}let i=r.owner,s=await zw(t),l=r.service.kind==="failed"?{kind:"failed",reason:r.service.error.message+(s.kind==="failed"&&s.reason!==r.service.error.message?`; ${s.reason}`:"")}:s,c=Qw(n),a=xd(n),d=c.kind==="read"?await Zw(c.identity):{kind:"not_attempted"};return{kind:"done",stateDir:n,stop:i,service:l,identity:c,cleanupFailures:a,remote:d}}o(on,"resetStateDir");async function zw(t){try{return await _o(t)==="removed"?{kind:"removed",name:t.name}:{kind:"absent"}}catch(e){if(e instanceof _||e instanceof p)return{kind:"failed",reason:e.message};throw e}}o(zw,"removeServiceRegistration");function Qw(t){try{let e=L(t);return e===null?{kind:"absent"}:{kind:"read",identity:e}}catch(e){if(e instanceof p)return{kind:"unreadable",reason:e.message};throw e}}o(Qw,"readIdentity");async function Zw(t){let e=new Ge({serverUrl:t.serverUrl,agentToken:t.agentToken});try{return await e.revokeSelf(),{kind:"revoked"}}catch(n){if(n instanceof T)return{kind:"already_revoked"};if(n instanceof ee){let r=n.params?.minVersion;return{kind:"not_confirmed",reason:typeof r=="string"?`the server accepts progon-agent ${r} or newer only`:"the server refuses this version of progon-agent"}}if(n instanceof x&&n.status===404)return{kind:"not_confirmed",reason:"the server does not offer self-revocation yet"};if(n instanceof x)return{kind:"not_confirmed",reason:`the server answered HTTP ${n.status}${n.errorCode===null?"":` ${n.errorCode}`}`};if(n instanceof Z)return{kind:"not_confirmed",reason:`the server could not be reached: ${n.message}`};if(n instanceof fe)return{kind:"not_confirmed",reason:`the server's answer was not understood: ${n.message}`};throw n}}o(Zw,"revokeRegistration");function wt(t){h(`Stopping progon-agent (${j(t)})\u2026`)}o(wt,"announceStop");async function Id(){let t=G().path;return await To(t),0}o(Id,"runStopCommand");async function Od(){let t=await on(se(G().path),wt);return Vi(t)?0:1}o(Od,"runResetCommand");function Vi(t){if(t.kind==="owner_running")return h(t.reason),h("The identity and local files were kept."),!1;t.stop.kind==="stopped"&&h(`Stopped progon-agent (pid ${t.stop.status.pid}).`);let e=qi(t.service);e!==null&&h(e);for(let n of Yi(t.identity,t.remote))h(n);if(t.cleanupFailures.length>0||t.service.kind==="failed"){h("Could not remove:"),t.service.kind==="failed"&&h(` the OS service \u2014 ${t.service.reason}`);for(let n of t.cleanupFailures)h(` ${n.path} \u2014 ${n.reason}`);return h("Fix the cause and run 'progon-agent reset' again to finish."),!1}return h(`This machine is disconnected: the credential and browser profiles in ${t.stateDir} are removed.`),process.env.PROGON_AGENT_TOKEN!==void 0&&process.env.PROGON_AGENT_TOKEN!==""&&h("PROGON_AGENT_TOKEN is set in this environment; reset does not change it \u2014 its source does."),!0}o(Vi,"reportResetResult");function qi(t){switch(t.kind){case"removed":return`Autostart is off: the service ${t.name} is removed.`;case"absent":return null;case"failed":return null}}o(qi,"describeServiceRemoval");function Yi(t,e){switch(t.kind){case"absent":return["This directory had no enrollment."];case"unreadable":return[`The state file could not be used (${t.reason}), so the server was not asked to revoke this machine. If it is still listed in Progon \u2192 Settings \u2192 Agents, remove it there.`];case"read":break}let{agentId:n,serverUrl:r}=t.identity;switch(e.kind){case"revoked":return[`Agent ${n} is revoked on ${r}.`];case"already_revoked":return[`Agent ${n} was already revoked on ${r}.`];case"not_confirmed":return[`The agent record ${n} may remain on ${r}: ${e.reason}. Remove it in Progon \u2192 Settings \u2192 Agents.`];case"not_attempted":return[]}}o(Yi,"describeRemote");import{existsSync as eS}from"node:fs";import{homedir as tS}from"node:os";import{resolve as nS}from"node:path";async function Ad(t){let e=[],n=await rS(t,e),r=n.map(s=>s.stateDir);h("progon-agent uninstall removes:");for(let s of r)h(` state directory ${s}`);h(" this installation's Chromium (browsers other Playwright installations use are kept)"),h(" the progon-agent package");for(let s of n){let l=s.stateDir;h(`
|
|
261
|
-
${l}`);let c=await
|
|
262
|
-
`)}h(`The service for ${r} did not start again: ${i instanceof Error?i.message:String(i)}`),h(`Retry: progon-agent service start --state-dir "${r}"`)}}return e}o(
|
|
263
|
-
`),0;switch(
|
|
260
|
+
'null'`,J.null())},async remove(t){return(await Fi(t)).registered?(await Wi.stop(t),await ie("schtasks",["/Delete","/TN",t,"/F"]),"removed"):"absent"},async read(t){let e=await Fi(t);if(!e.registered)return{kind:"absent"};let n=[`task state: ${e.state}`+(e.lastResult===null?"":`, last result: ${e.lastResult}`)+(e.lastRun===null||e.lastRun===""?"":`, last run: ${e.lastRun}`)];return{kind:"registered",location:`Task Scheduler \\${t}`,program:Ew(e.description),facts:n,active:e.state==="Running"||e.state==="Queued"?!0:e.state==="Disabled"||e.lastResult===0||e.lastResult===267011||e.lastResult===267014?!1:null,autostart:o(()=>Promise.resolve(e.state==="Disabled"?!1:e.state==="Unknown"?null:!0),"autostart")}},async registeredNames(){return ji(`ConvertTo-Json -Compress -InputObject @(Get-ScheduledTask -TaskPath '\\' -ErrorAction SilentlyContinue | Where-Object { $_.TaskName -match '${mw}' } | ForEach-Object { $_.TaskName })`,J.array(J.string()))},logHint(t){return`${Fn(t.stateDir,ze)} and ${Fn(t.stateDir,ho)}`}};function ce(){switch(process.platform){case"darwin":return ad;case"linux":return pd;case"win32":return Wi;default:throw new p(`progon-agent has no OS service for platform ${process.platform} (supported: macOS, Linux, Windows). Run 'progon-agent start' under your own supervisor.`)}}o(ce,"platformServiceManager");async function Eo(t){let e=await t.autostart();return e===null?"unknown":e?"on":"off \u2014 registered but disabled in the OS (turn on: 'progon-agent service enable')"}o(Eo,"describeAutostartState");async function vo(t){return ce().read(Zt(t))}o(vo,"readServiceOf");async function bo(){let t=ce(),e=en(),n=[],r=[],i=[];for(let s of await t.registeredNames()){let l=await t.read(s);if(l.kind==="absent")continue;let c=l.program,a=c===null?null:td(c);c===null||a===null?i.push(l.location):c[1]===e?n.push({name:s,stateDir:a}):r.push(s)}return{services:n,foreign:r,unreadable:i}}o(bo,"thisInstallationServices");async function _o(t){let e=ce();if(Qc()&&(await e.read(t.name)).kind!=="absent")try{el(t.stateDir)}catch(n){throw new _(`Could not retain service-file ownership for ${t.stateDir}: ${n instanceof Error?n.message:String(n)}. The registration is kept; fix the cause and retry.`,{cause:n})}return e.remove(t.name)}o(_o,"unregisterService");var Rw={ok:"[ok] ",warn:"[warn]",fail:"[FAIL]",info:"[info]"};function de(t){return t instanceof Error?t.message:String(t)}o(de,"describe");async function hd(){let t=0,e=o((l,c,a)=>{l==="fail"&&(t+=1),h(`${Rw[l]} ${c}: ${a}`)},"report");e("info","progon-agent",`${te()} on Node ${process.version} (${process.execPath})`),Tw(e);let n=G().path;xw(n,e),await Iw(n,e);let r=t,i=Aw(e);t===r?Pw(e):e("info","Start","not checked \u2014 'progon-agent start' refuses the settings above");let s=await Nw(e);return await Lw(s,i,e),await Ow(n,e),h(t===0?"No problems found.":`${t} check(s) failed \u2014 see [FAIL] above.`),t===0?0:1}o(hd,"runDoctorCommand");function Tw(t){let e=Qt();if(e.kind==="not_global"){t("info","Installation",`not a global npm install (${e.packageRoot}); 'update' cannot replace it and 'uninstall' leaves the package in place`);return}t(e.npmCli===null?"warn":"ok","Installation",`npm global install at ${e.prefix}`+(e.npmCli===null?" \u2014 no npm was found beside this node, so 'progon-agent update' cannot run it":""))}o(Tw,"checkInstallation");function xw(t,e){try{kw(t)}catch(n){if(P(n)){e("info","State directory",`${t} does not exist yet (created by 'enroll')`);return}e("fail","State directory",`${t}: ${de(n)}`);return}try{vw(t,_w.W_OK)}catch(n){e("fail","State directory",`${t} is not writable by this user: ${de(n)}`);return}try{let n=L(t);n===null?e("warn","Enrollment",`${t} holds no enrollment \u2014 run 'progon-agent enroll'`):e("ok","Enrollment",`agent ${n.agentId} at ${n.serverUrl} (${t})`)}catch(n){if(!(n instanceof p))throw n;e("fail","Enrollment",`${de(n)} 'progon-agent reset' removes it.`)}}o(xw,"checkStateDir");async function Iw(t,e){try{let n=await $(t);if(n.kind==="none")e("info","Agent","not running");else if(n.kind==="live"){let r=n.status.service?"as the service":"outside the service";e("info","Agent",`running ${r} \u2014 ${j(n.status)}`)}else e("warn","Agent",`a process owns the state directory, but ${n.reason}`)}catch(n){e("warn","Agent",`cannot ask the control channel: ${de(n)}`)}}o(Iw,"checkAgentProcess");async function Ow(t,e){let n;try{n=await vo(t)}catch(a){if(!(a instanceof _)&&!(a instanceof p))throw a;e("warn","Autostart",`the OS service manager could not be asked: ${de(a)}`);return}if(n.kind==="absent"){e("info","Autostart","off \u2014 no OS service is registered ('progon-agent service enable')");return}let r=`${n.location} (${n.facts.join("; ")})`,i=n.program;if(i===null||i.length<2){e("warn","Autostart",`${r}: the command it starts could not be read`);return}let[s,l]=i,c=[s,l].filter(a=>!bw(a));if(c.length>0){e("fail","Autostart",`${r}: it starts ${c.join(" and ")}, which no longer exist(s). Refresh it: progon-agent service enable --state-dir "${t}"`);return}if(s!==process.execPath||l!==en()){e("warn","Autostart",`${r}: it starts ${s} ${l}, not this node and installation (${process.execPath} ${en()}). Refresh it: progon-agent service enable --state-dir "${t}"`);return}e("ok","Autostart",r)}o(Ow,"checkService");function Aw(t){try{let e=un(process.env),n=[e.https,e.http].filter(r=>r!==void 0);if(n.length===0)t("ok","Proxy","none configured (HTTPS_PROXY / HTTP_PROXY unset)");else{let r=n.map(s=>`${s.variable}=${mo(s.url)}`).join(", "),i=e.noProxy===void 0?"":`, NO_PROXY=${e.noProxy}`;t("ok","Proxy",`${r}${i}`)}}catch(e){if(!(e instanceof p))throw e;t("fail","Proxy",de(e))}Cw(t);try{let e=gn();return t("ok","Browser settings","PROGON_AGENT_* values are valid"),e}catch(e){if(!(e instanceof p))throw e;return t("fail","Browser settings",de(e)),null}}o(Aw,"checkConfiguration");function Cw(t){let e=[],n=!1;try{let r=er(process.env);r!==void 0&&e.push(`${r.variable}=${r.path} (readable)`)}catch(r){if(!(r instanceof p))throw r;t("fail","Certificates",de(r)),n=!0}try{let r=Hs(process.env);r!==void 0&&e.push(`NODE_EXTRA_CA_CERTS=${r} (readable)`)}catch(r){if(!(r instanceof p))throw r;t("fail","Certificates",de(r)),n=!0}n||t("ok","Certificates",e.length===0?"system store only":e.join(", "))}o(Cw,"checkCertificates");function Pw(t){try{let e=Me(),n=gi(e);n!==null&&e.extensionDistOverride===void 0&&ci(n.source==="env_token"?null:n.agentId),n===null&&e.enrollmentCode!==void 0?t("ok","Start",`redeems PROGON_AGENT_ENROLL_CODE at ${e.serverUrl} on its first start`):n===null?t("info","Start",`${e.serverUrl} \u2014 not enrolled yet ('progon-agent enroll')`):t("ok","Start",`connects to ${e.serverUrl} with ${n.source==="env_token"?"PROGON_AGENT_TOKEN":`the enrollment of agent ${n.agentId}`}`)}catch(e){if(!(e instanceof p))throw e;t("fail","Start",`'progon-agent start' refuses: ${de(e)}`)}}o(Pw,"checkStart");async function Nw(t){h("Chromium: checking (downloads it if missing)\u2026");try{return await kt({stdio:"terminal"}),t("ok","Chromium","installed"),!0}catch(e){if(!(e instanceof Q))throw e;return t("fail","Chromium",de(e)),!1}}o(Nw,"checkChromium");async function Lw(t,e,n){if(e!==null&&e.disableBrowserSandbox){n("warn","Browser sandbox","switched off by PROGON_AGENT_DISABLE_BROWSER_SANDBOX");return}if(!t){n("info","Browser sandbox","not checked \u2014 Chromium is not installed");return}try{await Or(),n("ok","Browser sandbox","Chromium starts with its sandbox")}catch(r){if(!(r instanceof p))throw r;n("fail","Browser sandbox",de(r))}}o(Lw,"checkSandbox");async function gd(){let t=G();return h(`progon-agent ${te()} (this installation)`),h(`State directory: ${t.path} (${t.source==="env"?"PROGON_RUNNER_STATE_DIR / --state-dir":"platform default"})`),h(`Enrollment: ${Uw(t.path)}`),process.env.PROGON_AGENT_TOKEN!==void 0&&process.env.PROGON_AGENT_TOKEN!==""&&h("PROGON_AGENT_TOKEN: set in this environment \u2014 a start from here authenticates with it, not with the enrollment above."),h(`Agent: ${await $w(t.path)}`),h(`Autostart: ${await Dw(t.path)}`),0}o(gd,"runStatusCommand");async function Dw(t){try{let e=await vo(t);return e.kind==="absent"?"off (turn on: 'progon-agent service enable')":`${await Eo(e)} \u2014 ${ce().description}; ${e.facts.join("; ")}`}catch(e){if(e instanceof _||e instanceof p)return`unknown \u2014 ${e.message}`;throw e}}o(Dw,"describeAutostart");async function $w(t){let e;try{e=await $(t)}catch(n){return`unknown \u2014 ${n instanceof Error?n.message:String(n)}`}return e.kind==="none"?"not running":e.kind==="live"?`running ${e.status.service?"as the service":"outside the service"} \u2014 ${j(e.status)}`:`a process owns this directory, but ${e.reason}`}o($w,"describeAgentProcess");function Uw(t){try{let e=L(t);return e===null?"not enrolled (run 'progon-agent enroll')":`agent ${e.agentId} at ${e.serverUrl}`}catch(e){if(e instanceof p)return`the state file cannot be used \u2014 ${e.message}`;throw e}}o(Uw,"describeEnrollment");import{setTimeout as jw}from"node:timers/promises";import{setTimeout as Mw}from"node:timers/promises";function yt(t){if(t.service.kind==="failed")throw t.service.error}o(yt,"assertManagedServiceStopped");async function Ne(t,e,n="all",r){let i=ce(),{stateDir:s,name:l}=t,c=null,a=[];try{c=await i.read(l)}catch(S){if(!(S instanceof _))throw S;a.push(S)}let d=await $(s),u=d.kind==="live"&&d.status.service?!0:c?.kind==="registered"?c.active:null;c?.kind!=="absent"&&r?.(u);let m=n==="service_only"&&d.kind==="live"&&!d.status.service,g={kind:"not_running"},E=null;if(!m)try{g=await Yc(s,e)}catch(S){if(!(S instanceof p))throw S;E=S}if(c?.kind!=="absent")try{await i.stop(l)}catch(S){if(!(S instanceof _))throw S;a.push(S)}if(!m){let S=Date.now()+Ce;for(;(await $(s)).kind!=="none";){if(a.length>0||c?.kind==="absent"||Date.now()>=S)throw new p((E?.message??`A process still owns ${s}. Stop it where it runs and retry.`)+(a.length===0?"":` OS service: ${a.map(b=>b.message).join("; ")}`));await Mw(250)}d.kind==="live"&&(g={kind:"stopped",status:d.status})}return{owner:g,service:a.length>0?{kind:"failed",error:new _(a.map(S=>S.message).join("; "))}:c?.kind==="absent"?{kind:"absent"}:{kind:"stopped"}}}o(Ne,"stopManagedStateDirOwner");import{createInterface as Gw}from"node:readline/promises";var Fw=new Set(["y","yes","\u0434","\u0434\u0430"]),Bw=new Set(["n","no","\u043D","\u043D\u0435\u0442"]);async function ko(t,e){if(process.stdin.isTTY!==!0||process.stdout.isTTY!==!0)return"no_answer";let n=Gw({input:process.stdin,output:process.stdout}),r=new Promise(s=>{n.once("close",()=>s(null))}),i=e==="yes"?"(Y/n)":"(y/N)";try{for(;;){let s=await Promise.race([n.question(`${t} ${i} `).catch(()=>null),r]);if(s===null)return"no_answer";let l=s.trim().toLowerCase();if(l==="")return e;if(Fw.has(l))return"yes";if(Bw.has(l))return"no";h("Answer 'y' or 'n'.")}}finally{n.close()}}o(ko,"askYesNo");var yd=2e4,Ww=250;async function wd(t){let e=G().path;switch(t){case"enable":return await Hi(e),0;case"disable":return await Ed(e),0;case"start":return await Ro(se(e)),0;case"stop":return await To(e),0;case"restart":return await To(e),await Ro(se(e)),0;case"status":return await Kw(e),0}}o(wd,"runServiceCommand");function Sd(t){h(t.service?`Stopping the service (${j(t)}) to apply the new registration\u2026`:`Stopping progon-agent started outside the service (${j(t)}) \u2014 the service takes over\u2026`)}o(Sd,"announceHandOver");function Hw(t){if(L(t)===null)throw new p(`${t} holds no enrollment, so a service there would stop at once. Enroll first: progon-agent enroll --autostart`)}o(Hw,"assertEnrolled");async function Hi(t){Hw(t);let e=ce(),n=ed(t),r=await e.isCurrent(n),i=await $(t);if(i.kind==="live"&&i.status.service&&r){h(`The service ${n.name} is enabled and running (${j(i.status)}).`);return}yt(await Ne(n,Sd));let s=r?[]:await e.install(n);r||h(`Registered ${n.name} as ${e.description}.`),Jw(n),await e.start(n.name),await vd(n);for(let l of s)h(l)}o(Hi,"enableService");async function Ed(t){let e=se(t),{name:n}=e,r=await $(t);yt(await Ne(e,s=>h(`Stopping the service (${j(s)})\u2026`),"service_only"));let i=await _o(e);h(i==="removed"?`Autostart is off: the service ${n} is removed. The enrollment is kept.`:`Autostart is off: no service is registered for ${t}.`),r.kind==="live"&&!r.status.service&&h(`progon-agent started outside the service is still running (${j(r.status)}).`)}o(Ed,"disableService");async function Ro(t){let e=ce(),{stateDir:n,name:r}=t;if((await e.read(r)).kind==="absent"){h("No service is registered for this state directory \u2014 enabling it."),await Hi(n);return}let i=await $(n);if(i.kind==="live"&&i.status.service){h(`The service ${r} is already running (${j(i.status)}).`);return}yt(await Ne(t,Sd)),await e.start(r),await vd(t)}o(Ro,"startService");async function To(t){let e=await Ne(se(t),r=>h(`Stopping progon-agent (${j(r)})\u2026`));yt(e);let n=e.owner;n.kind==="stopped"?h(`Stopped progon-agent (pid ${n.status.pid}).`):e.service.kind==="stopped"?h(`Stopped the OS service for ${t}, including any scheduled restart.`):h(`No progon-agent is running for ${t}.`),e.service.kind==="stopped"&&h("Autostart stays on: it starts again with 'progon-agent service start' or by the OS.")}o(To,"stopService");async function vd(t){let e=Date.now()+yd;for(;Date.now()<e;){let s=await $(t.stateDir);if(s.kind==="live"&&s.status.service){h(`The service ${t.name} is running (${j(s.status)}).`);return}await jw(Ww)}let n=ce(),r=await n.read(t.name),i=r.kind==="registered"?` The OS: ${r.facts.join("; ")}.`:"";throw new _(`The service ${t.name} was started but did not answer within ${yd/1e3} s.${i} Its log says why: ${n.logHint(t)}`)}o(vd,"waitForService");function Jw(t){if(t.environment.length===0)h("Settings from this environment: none.");else{h("Settings from this environment, written into the registration:");for(let[e,n]of t.environment){let r=/proxy/i.test(e)||e==="PLAYWRIGHT_DOWNLOAD_HOST"||e==="PROGON_SERVER_URL";h(` ${e}=${r?mo(n):n}`)}}process.env.PROGON_AGENT_TOKEN!==void 0&&process.env.PROGON_AGENT_TOKEN!==""&&h("PROGON_AGENT_TOKEN is not copied: the service authenticates with the enrollment.")}o(Jw,"describeEnvironment");async function Kw(t){let e=ce(),n=Zt(t),r=await e.read(n);if(h(`State directory: ${t}`),r.kind==="absent")h(`Autostart: off \u2014 no service ${n} is registered.`);else{h(`Autostart: ${await Eo(r)} \u2014 ${e.description}`),h(`Registration: ${r.location}`);for(let s of r.facts)h(` ${s}`);h(`Log: ${e.logHint({name:n,stateDir:t})}`)}let i=await $(t);i.kind==="none"?h("Process: not running"):i.kind==="live"?h(`Process: ${i.status.service?"the service":"started outside the service"} \u2014 ${j(i.status)}`):h(`Process: a process owns this directory, but ${i.reason}`)}o(Kw,"printServiceStatus");async function bd(t){let e=G(),n=t==="ask"?await Vw():t;if(n==="keep")return h(`Autostart was not changed (no terminal to ask, no answer). Turn it on with: progon-agent service enable${Nn(e)}`),0;try{return n==="on"?await Hi(e.path):await Ed(e.path),0}catch(r){let i=r instanceof p||r instanceof _;if(h(`This machine is enrolled, but autostart could not be ${n==="on"?"set up":"turned off"}`+(i?":":".")),i&&h(` ${r.message}`),h(`Retry: progon-agent service ${n==="on"?"enable":"disable"}${Nn(e)}`),!i)throw r;return 1}}o(bd,"applyAutostartAfterEnroll");async function Vw(){let t=await ko("Start the runner automatically in the background?","yes");return t==="yes"?"on":t==="no"?"off":"keep"}o(Vw,"askAutostart");import{readdirSync as Rd,rmdirSync as qw,rmSync as Ji}from"node:fs";import{basename as _d,join as kd}from"node:path";function Le(t){return t instanceof Error?t.message:String(t)}o(Le,"describe");function Td(t){let e=[],n;try{n=Rd(t,{withFileTypes:!0})}catch(a){return P(a)?e:[{path:t,reason:Le(a)}]}let r=new Set([_d(nt(t)),_d(mn(t))]),i=n.some(a=>r.has(a.name)&&!a.isDirectory()),s=n.some(a=>a.name===ft&&a.isFile()),l=kd(t,Er),c=null;try{c=br(t);let a=i||s||c!==null,d=c===null?[]:c.profiles,u=Yw(t,n,e,a,d);(u.length>0||c===null&&a)&&(c={...c??vr,profiles:[...d,...u]},_r(t,c))}catch(a){e.push({path:l,reason:Le(a)}),c=null}if(i)try{rr(t)}catch(a){e.push({path:nt(t),reason:Le(a)})}if(c!==null){let a=new ut(t);for(let d of c.profiles){let u=a.userDataDirFor(d);try{Ji(u,{recursive:!0,force:!0})}catch(m){e.push({path:u,reason:Le(m)})}}try{Ki(a.instancesRoot)}catch(d){e.push({path:a.instancesRoot,reason:Le(d)})}}for(let a of n){let d=c!==null&&c.extensionCopy&&al(a.name);if(!(c!==null&&(Za(a.name)||d||Wc(a.name)||c.serviceFiles&&zc(a.name))))continue;let m=kd(t,a.name);if(!(a.isDirectory()&&!d))try{Ji(m,{recursive:a.isDirectory(),force:!0})}catch(g){e.push({path:m,reason:Le(g)})}}if(c!==null&&e.length===0)try{Ji(l)}catch(a){e.push({path:l,reason:Le(a)})}return e}o(Td,"removeRunnerFiles");function Yw(t,e,n,r,i){if(!e.some(c=>c.name===ar&&c.isDirectory()))return[];let s=new ut(t),l=[];try{for(let c of Rd(s.instancesRoot,{withFileTypes:!0}))if(c.isDirectory()&&!i.includes(c.name))try{s.read(c.name).runId===c.name?l.push(c.name):r&&n.push({path:s.userDataDirFor(c.name),reason:"Instance marker does not identify this profile; ownership is unknown and it was kept"})}catch(a){let d=typeof a=="object"&&a!==null?a.code:void 0;(r||d!==void 0&&!P(a))&&n.push({path:s.userDataDirFor(c.name),reason:`Cannot establish profile ownership; it was kept: ${Le(a)}`})}}catch(c){n.push({path:s.instancesRoot,reason:Le(c)})}return l}o(Yw,"findInstanceProfiles");function Ki(t){try{return qw(t),"removed"}catch(e){if(P(e))return"absent";let n=e.code;if(n==="ENOTEMPTY"||n==="EEXIST")return"not_empty";throw e}}o(Ki,"removeDirectoryIfEmpty");async function sn(t,e){let{stateDir:n}=t,r;try{r=await Ne(t,e)}catch(u){if(u instanceof p)return{kind:"owner_running",stateDir:n,reason:u.message};throw u}let i=r.owner,s=await Xw(t),l=r.service.kind==="failed"?{kind:"failed",reason:r.service.error.message+(s.kind==="failed"&&s.reason!==r.service.error.message?`; ${s.reason}`:"")}:s,c=zw(n),a=Td(n),d=c.kind==="read"?await Qw(c.identity):{kind:"not_attempted"};return{kind:"done",stateDir:n,stop:i,service:l,identity:c,cleanupFailures:a,remote:d}}o(sn,"resetStateDir");async function Xw(t){try{return await _o(t)==="removed"?{kind:"removed",name:t.name}:{kind:"absent"}}catch(e){if(e instanceof _||e instanceof p)return{kind:"failed",reason:e.message};throw e}}o(Xw,"removeServiceRegistration");function zw(t){try{let e=L(t);return e===null?{kind:"absent"}:{kind:"read",identity:e}}catch(e){if(e instanceof p)return{kind:"unreadable",reason:e.message};throw e}}o(zw,"readIdentity");async function Qw(t){let e=new Ge({serverUrl:t.serverUrl,agentToken:t.agentToken});try{return await e.revokeSelf(),{kind:"revoked"}}catch(n){if(n instanceof T)return{kind:"already_revoked"};if(n instanceof ee){let r=n.params?.minVersion;return{kind:"not_confirmed",reason:typeof r=="string"?`the server accepts progon-agent ${r} or newer only`:"the server refuses this version of progon-agent"}}if(n instanceof x&&n.status===404)return{kind:"not_confirmed",reason:"the server does not offer self-revocation yet"};if(n instanceof x)return{kind:"not_confirmed",reason:`the server answered HTTP ${n.status}${n.errorCode===null?"":` ${n.errorCode}`}`};if(n instanceof Z)return{kind:"not_confirmed",reason:`the server could not be reached: ${n.message}`};if(n instanceof fe)return{kind:"not_confirmed",reason:`the server's answer was not understood: ${n.message}`};throw n}}o(Qw,"revokeRegistration");function wt(t){h(`Stopping progon-agent (${j(t)})\u2026`)}o(wt,"announceStop");async function xd(){let t=G().path;return await To(t),0}o(xd,"runStopCommand");async function Id(){let t=await sn(se(G().path),wt);return Vi(t)?0:1}o(Id,"runResetCommand");function Vi(t){if(t.kind==="owner_running")return h(t.reason),h("The identity and local files were kept."),!1;t.stop.kind==="stopped"&&h(`Stopped progon-agent (pid ${t.stop.status.pid}).`);let e=qi(t.service);e!==null&&h(e);for(let n of Yi(t.identity,t.remote))h(n);if(t.cleanupFailures.length>0||t.service.kind==="failed"){h("Could not remove:"),t.service.kind==="failed"&&h(` the OS service \u2014 ${t.service.reason}`);for(let n of t.cleanupFailures)h(` ${n.path} \u2014 ${n.reason}`);return h("Fix the cause and run 'progon-agent reset' again to finish."),!1}return h(`This machine is disconnected: the credential and browser profiles in ${t.stateDir} are removed.`),process.env.PROGON_AGENT_TOKEN!==void 0&&process.env.PROGON_AGENT_TOKEN!==""&&h("PROGON_AGENT_TOKEN is set in this environment; reset does not change it \u2014 its source does."),!0}o(Vi,"reportResetResult");function qi(t){switch(t.kind){case"removed":return`Autostart is off: the service ${t.name} is removed.`;case"absent":return null;case"failed":return null}}o(qi,"describeServiceRemoval");function Yi(t,e){switch(t.kind){case"absent":return["This directory had no enrollment."];case"unreadable":return[`The state file could not be used (${t.reason}), so the server was not asked to revoke this machine. If it is still listed in Progon \u2192 Settings \u2192 Agents, remove it there.`];case"read":break}let{agentId:n,serverUrl:r}=t.identity;switch(e.kind){case"revoked":return[`Agent ${n} is revoked on ${r}.`];case"already_revoked":return[`Agent ${n} was already revoked on ${r}.`];case"not_confirmed":return[`The agent record ${n} may remain on ${r}: ${e.reason}. Remove it in Progon \u2192 Settings \u2192 Agents.`];case"not_attempted":return[]}}o(Yi,"describeRemote");import{existsSync as Zw}from"node:fs";import{homedir as eS}from"node:os";import{resolve as tS}from"node:path";async function Od(t){let e=[],n=await nS(t,e),r=n.map(s=>s.stateDir);h("progon-agent uninstall removes:");for(let s of r)h(` state directory ${s}`);h(" this installation's Chromium (browsers other Playwright installations use are kept)"),h(" the progon-agent package");for(let s of n){let l=s.stateDir;h(`
|
|
261
|
+
${l}`);let c=await sn(s,wt);if(c.kind==="owner_running"){h(` ${c.reason}`),e.push(`${l} \u2014 could not confirm that its directory owner stopped`);continue}let a=qi(c.service);a!==null&&h(` ${a}`);for(let u of Yi(c.identity,c.remote))h(` ${u}`);c.service.kind==="failed"&&e.push(`the OS service of ${l} \u2014 ${c.service.reason}`);for(let u of c.cleanupFailures)e.push(`${u.path} \u2014 ${u.reason}`);if(c.cleanupFailures.length>0||c.service.kind==="failed")continue;let d=Ki(l);d==="removed"?h(" removed"):d==="absent"?h(" nothing there"):h(" progon-agent files removed; the directory holds other files and is kept")}if(h(""),e.length>0?h("Chromium and the package are kept until the state directories are clean."):(await rS(e),e.length===0?await oS(e):e.push("the progon-agent package \u2014 kept so uninstall can finish Chromium cleanup on retry")),e.length===0)return h("progon-agent is uninstalled."),0;h("Not removed:");for(let s of e)h(` ${s}`);let i=r.map(s=>` --state-dir "${s}"`).join("");return h(`Fix the cause and run again to finish: progon-agent uninstall${i}`),1}o(Od,"runUninstallCommand");async function nS(t,e){let n=[],r=o(s=>{let l=tS(s);n.some(c=>c.stateDir===l)||n.push(se(l))},"add");try{r(hn(process.platform,process.env,eS()))}catch(s){if(!(s instanceof p))throw s;h(`No standard state directory here: ${s.message}`)}let i=process.env.PROGON_RUNNER_STATE_DIR;i!==void 0&&i!==""&&r(i);for(let s of t)r(s);try{let s=await bo();for(let l of s.services){let c=n.findIndex(a=>a.stateDir===l.stateDir);c===-1?n.push(l):n[c]=l}for(let l of s.foreign){let c=n.find(a=>a.name===l);c!==void 0&&(n.splice(n.indexOf(c),1),h(`${c.stateDir} is left alone: its OS service ${l} runs another progon-agent installation. Uninstall that one with its own 'progon-agent uninstall'.`))}for(let l of s.unreadable)e.push(`${l} \u2014 a progon-agent service whose state directory cannot be read; remove it by hand`)}catch(s){if(!(s instanceof _)&&!(s instanceof p))throw s;e.push(`OS services \u2014 they could not be listed: ${s.message}`)}return n}o(nS,"collectTargets");async function rS(t){let e;try{e=Ho().cliPath}catch(r){if(!(r instanceof Q))throw r;t.push(`Chromium \u2014 ${r.message}`);return}if(!Zw(rt.executablePath())){h("This installation's Chromium is not on disk \u2014 nothing to remove.");return}h("Removing this installation's Chromium\u2026");let n=await Dn(e,["uninstall"]);n!==0&&t.push(`Chromium \u2014 Playwright's uninstall exited ${n===null?"by signal":String(n)}`)}o(rS,"removeChromium");async function oS(t){let e=Qt();if(e.kind==="not_global"){h(`The package is not a global npm install (${e.packageRoot}); it is left as it is.`);return}if(e.npmCli===null){t.push(`the package \u2014 no npm beside this node; run: npm uninstall -g ${we}`);return}h(`Removing the package from ${e.prefix}\u2026`);let n=await fo(e.npmCli,["uninstall","--global","--prefix",e.prefix,we]);n!==0&&t.push(`the package \u2014 npm exited ${n===null?"by signal":String(n)}; run: npm uninstall -g ${we}`)}o(oS,"removePackage");async function Ad(t){let e=Qt();if(e.kind==="not_global")throw new p(`This progon-agent is not a global npm install (it runs from ${e.packageRoot}), so there is no installation for 'update' to replace. Update it the way it was installed.`);let n=`${we}@${t===null?"latest":t}`;if(e.npmCli===null)throw new p(`No npm was found beside this node (${process.execPath}), so 'update' cannot run it. Update with the npm that installed progon-agent: npm i -g ${n}`);let r=G(),{terminalStopped:i,servicesStopped:s}=await sS(r.path),l=!1,c;try{c=await iS(e.npmCli,e.prefix,e.packageRoot,n)}finally{Ci(e.packageRoot).kind==="installed"?l=await Cd(s):aS(s),i&&h(`Start the agent again: progon-agent start${r.source==="env"?` --state-dir "${r.path}"`:""}`)}return c===0&&l?0:1}o(Ad,"runUpdateCommand");async function iS(t,e,n,r){let i=te();h(`Installing ${r} into ${e}\u2026`);let s=await fo(t,["install","--global","--prefix",e,r]),l=Ci(n);if(s!==0)return h(`npm did not finish (exit ${s===null?"by signal":String(s)}).`),l.kind==="installed"?h(`Installed now: progon-agent ${l.version} (was ${i}).`):h(`The package is damaged (${l.reason}). Reinstall it: npm i -g ${r}`),1;if(l.kind==="damaged")return h(`npm finished, but the package is damaged (${l.reason}). Reinstall it: npm i -g ${r}`),1;h(l.version===i?`progon-agent ${l.version} is installed (unchanged).`:`Updated progon-agent ${i} \u2192 ${l.version}. The enrollment is kept.`),h("Preparing Chromium for this version\u2026");let c=await Dn(l.cliPath,["install-browser"]);return c!==0&&h(`Chromium could not be prepared (exit ${c===null?"by signal":String(c)}); 'progon-agent start' downloads it again, or run 'progon-agent doctor'.`),c===0?0:1}o(iS,"installUpdate");async function sS(t){let e=await bo();if(e.unreadable.length>0)throw new p(`Update changed nothing: these progon-agent services may run this installation, but their command cannot be read: ${e.unreadable.join(", ")}. Remove them by hand, then retry.`);let n=e.services.find(a=>a.stateDir===t),r=se(t),i=[];n!==void 0?i.push({target:n,scope:"all"}):e.foreign.includes(r.name)?h(`${t} is left alone: its OS service ${r.name} runs another progon-agent installation.`):i.push({target:r,scope:"all"});for(let a of e.services)a!==n&&i.push({target:a,scope:"service_only"});let s=!1,l=!1,c=[];try{for(let{target:a,scope:d}of i){let u=await Ne(a,g=>{!g.service&&d==="all"&&(l=!0),wt(g)},d,g=>{if(g!==!1){if(g===null)throw new _(`The OS did not report the activity of the service for ${a.stateDir}; update cannot choose which services to restore.`);c.push(a)}});yt(u);let m=u.owner;d==="all"&&m.kind==="stopped"&&!m.status.service&&(s=!0)}}catch(a){throw h("Update was aborted before changing the package. Restoring the services already stopped\u2026"),await Cd(c),l&&h(`The terminal runner may have stopped; start it again: progon-agent start --state-dir "${t}"`),a}return{terminalStopped:s,servicesStopped:c}}o(sS,"stopRunningAgents");async function Cd(t){let e=!0;for(let n of t){let r=n.stateDir;try{await Ro(n)}catch(i){if(e=!1,!(i instanceof _)&&!(i instanceof p)){let s=i instanceof Error?i.stack:void 0;process.stderr.write(JSON.stringify({level:"error",module:"update",msg:"Unexpected failure while restarting a service",stateDir:C(r),err:C(i instanceof Error?i.message:String(i)),stack:s===void 0?void 0:C(s)})+`
|
|
262
|
+
`)}h(`The service for ${r} did not start again: ${i instanceof Error?i.message:String(i)}`),h(`Retry: progon-agent service start --state-dir "${r}"`)}}return e}o(Cd,"restartServices");function aS(t){for(let{stateDir:e}of t)h(`The service for ${e} stays stopped until the package is repaired; then: progon-agent service start --state-dir "${e}"`)}o(aS,"reportServicesLeftStopped");async function Pd(t){if(t.command==="version")return process.stdout.write(`${te()}
|
|
263
|
+
`),0;switch(zn(),t.command!=="uninstall"&&t.stateDir!==void 0&&(process.env.PROGON_RUNNER_STATE_DIR=t.stateDir),t.command){case"status":return gd();case"stop":return xd();case"reset":return Id();case"doctor":return hd();case"update":return Ad(t.version);case"uninstall":return Od(t.stateDirs);case"service":return wd(t.verb)}}o(Pd,"runLifecycleCommand");import{randomBytes as cS}from"node:crypto";import{linkSync as dS,symlinkSync as uS}from"node:fs";import{createServer as pS}from"node:net";import{join as Wn,resolve as mS}from"node:path";var Bn=w("state-dir-owner"),lS=4*1024,xo=class{static{o(this,"OwnerState")}#e;#t;#n;#r=new Date().toISOString();#i="starting";#a=o(()=>null,"#readActiveRun");#s;constructor(e,n,r){this.#e=e,this.#t=n,this.#n=r}own(e){let n=!1,r=this.#e,i=o(()=>{n||(n=!0,process.off("exit",i),e(),Bn.info("State directory released",{stateDir:r}))},"release");return process.on("exit",i),Bn.info("State directory owned",{stateDir:r,pid:process.pid}),{stateDir:r,setPhase:o(s=>{this.#i=s},"setPhase"),setActiveRunReader:o(s=>{this.#a=s},"setActiveRunReader"),setStopHandler:o(s=>{this.#s=s},"setStopHandler"),release:i}}serve(e){e.setEncoding("utf8");let n=oo(),r="";e.on("error",i=>{Bn.debug("Control channel connection failed",{err:i.message})}),e.write(`${JSON.stringify({protocol:Pn,challenge:n})}
|
|
264
264
|
`),e.on("data",i=>{r+=i;let s=r.indexOf(`
|
|
265
|
-
`);if(s===-1){r.length>
|
|
266
|
-
`),c==="stop"&&this.#o()})}#o(){
|
|
265
|
+
`);if(s===-1){r.length>lS&&e.destroy();return}let l=uo(r.slice(0,s),jc);if(!l.ok||!lo(so(this.#t,n,l.value.nonce,l.value.type),l.value.proof)){Bn.warn("Refused a control request that did not prove the key of this directory",{stateDir:this.#e}),e.destroy();return}let{type:c,nonce:a}=l.value;c==="stop"&&(this.#i="stopping"),e.end(`${JSON.stringify({proof:ao(this.#t,n,a),status:this.#l()})}
|
|
266
|
+
`),c==="stop"&&this.#o()})}#o(){Bn.info("Stop requested over the control channel",{stateDir:this.#e}),this.#s()}#l(){return{protocol:Pn,pid:process.pid,version:te(),startedAt:this.#r,stateDir:this.#e,phase:this.#i,activeRunId:this.#a(),service:this.#n}}};var Hn=5;async function Ld(t,e){let n=mS(t);xt(n),io(n);let r=xc(n),i=new xo(n,r,e.service),s=pS(g=>i.serve(g)),l=Oi(n);if(l.kind==="pipe"){for(let g=0;g<Hn;g+=1){if(await Nd(s,()=>s.listen(l.name))==="bound")return{kind:"acquired",ownership:i.own(()=>jn(s,n,null))};let S=await $(n);if(S.kind!=="none")return{kind:"held",answer:S}}throw Io(n)}let c=performance.now()+Hn*Ye;await Uc(n,()=>performance.now()+2*Ye<c,async g=>(await $(n,g)).kind==="none");let a=`control-${process.pid}-${cS(4).toString("hex")}.sock`,d=`${a}.pending`;if(await Nd(s,()=>po(n,()=>s.listen(d)))!=="bound")throw new Error(`[state-dir-owner] Cannot bind the control socket ${Wn(n,a)}: the name is already in use.`);let m=!1;try{dS(Wn(n,d),Wn(n,a)),m=!0,qe(Wn(n,d));for(let g=0;g<Hn;g+=1){let E=An(n);if(E!==null){if(performance.now()+Ye>c)throw Io(n);let b=await $(n,E);if(b.kind!=="none")return jn(s,n,a),{kind:"held",answer:b}}if(performance.now()>c)throw Io(n);let S=E===null?co(n):Ii(n,E);try{uS(a,S)}catch(b){if(Dd(b)!=="EEXIST")throw b;continue}if(An(n)!==a){E!==null&&qe(S);continue}return E!==null&&$c(n,a),Mc(n,a),{kind:"acquired",ownership:i.own(()=>jn(s,n,a))}}}catch(g){throw jn(s,n,m?a:d),g}throw jn(s,n,a),Io(n)}o(Ld,"acquireStateDirOwnership");async function Nd(t,e){return new Promise((n,r)=>{let i=o(l=>{t.off("listening",s),Dd(l)==="EADDRINUSE"?n("in_use"):r(l)},"onError"),s=o(()=>{t.off("error",i),n("bound")},"onListening");t.once("error",i),t.once("listening",s),e()})}o(Nd,"listen");function jn(t,e,n){if(n===null){t.close();return}qe(Wn(e,n)),po(e,()=>t.close())}o(jn,"closeOwnSocket");function Io(t){return new Error(`[state-dir-owner] Could not take ownership of ${t} within ${Hn} claim rounds and their ${Hn*Ye/1e3} s answer budget. The control directory kept changing or its socket probes used that budget. Check the processes using this directory and start again.`)}o(Io,"roundsExhausted");function Dd(t){return typeof t=="object"&&t!==null?t.code:void 0}o(Dd,"errnoOf");var Jn=w("daemon");async function Ud(t){ca(),Jn.info("progon-agent starting");let e=G().path,n=await Ld(e,{service:t.service});if(n.kind==="held"){let{answer:i}=n;if(i.kind==="foreign")throw new p(`Cannot take the state directory ${e}: its control channel is held by a process that is not its progon-agent (${i.reason}). On Windows another user's process can hold the channel name; end that process and start again.`);return i.kind==="live"?Jn.info("progon-agent is already running for this state directory \u2014 nothing to start",{stateDir:e,ownerPid:i.status.pid,version:i.status.version,since:i.status.startedAt,phase:i.status.phase}):Jn.info("Another process owns this state directory, but it did not say what it is \u2014 nothing to start",{stateDir:e,reason:i.reason}),0}let r=n.ownership;try{let i=new AbortController,s=Vl(i.signal).catch(u=>{if(i.signal.aborted&&u===i.signal.reason)return null;throw u}),l=da(async u=>{r.setPhase("stopping"),i.abort();let m=await s;m!==null&&await m.shutdown(u)});r.setStopHandler(()=>l("stop_request"));let c=await s.catch(u=>{if(i.signal.aborted)return null;throw u});if(c===null||i.signal.aborted)return null;r.setActiveRunReader(()=>c.activeRunId),r.setPhase("running");let a;try{a=await c.run()}catch(u){throw await c.shutdown("fatal").catch(m=>{throw new AggregateError([u,m],`${$d(u)} \u2014 and the teardown after it failed too, so the browser may still be running: ${$d(m)}`)}),u}let d=Wl[a];return d.level==="error"?Jn.error(d.message):Jn.info(d.message),d.exitCode}finally{r.release()}}o(Ud,"runDaemon");function $d(t){return t instanceof Error?t.message:String(t)}o($d,"describe");import{createHash as _S,randomBytes as kS}from"node:crypto";import{z as W}from"zod";var Md=W.object({requestId:W.uuid(),mode:W.literal("device"),userCode:W.string().min(1),verificationUrl:W.url(),expiresAt:W.iso.datetime({offset:!0}),pollIntervalSec:W.number().int().positive()}),Gd=W.object({status:W.literal("authorization_pending"),expiresAt:W.iso.datetime({offset:!0}),pollIntervalSec:W.number().int().positive()}),fS=W.object({companyName:W.string(),approvedByEmail:W.string(),approvedAt:W.string()}),Fd=W.object({credential:qn,approval:fS});var Bd=w("gateway-enrollment-request"),Oo=class{static{o(this,"GatewayEnrollmentRequestClient")}serverUrl;machine;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.machine=e.machine,this.fetchImpl=e.fetchImpl??Mt}async create(e){let n=await st({operation:"enrollment_request_create",method:"POST",url:q(this.serverUrl,"/enrollment-requests"),agentToken:null,body:{deviceSecretHash:e,protocolVersion:1,...this.machine},signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:ka}),r=V("enrollment_request_create",Md.safeParse(n));return Bd.info("Enrollment request opened",{requestId:r.requestId,mode:r.mode,pollIntervalSec:r.pollIntervalSec,expiresAt:r.expiresAt}),r}async poll(e){let n=await st({operation:"enrollment_request_poll",method:"POST",url:q(this.serverUrl,"/enrollment-requests/poll"),agentToken:null,body:{deviceSecret:e},signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:Ra}),r=typeof n=="object"&&n!==null?n:null;if(r!==null&&"credential"in r){let i=V("enrollment_request_poll",Fd.safeParse(n));return Bd.info("Enrollment request approved",{agentId:i.credential.agentId}),{kind:"enrolled",credential:i.credential,approval:i.approval}}if(r!==null&&"status"in r){let i=V("enrollment_request_poll",Gd.safeParse(n));return{kind:"pending",expiresAt:i.expiresAt,pollIntervalSec:i.pollIntervalSec}}throw new fe("enrollment_request_poll","the 2xx body is neither the authorization_pending answer nor the success envelope CONTRACT-phase-c \xA74.1 M2 defines")}async cancel(e){await st({operation:"enrollment_request_cancel",method:"POST",url:q(this.serverUrl,"/enrollment-requests/cancel"),agentToken:null,body:{deviceSecret:e},signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:Ta})}};async function Xi(t,e){let n=L(t.stateDir);if(n===null||Ue(n.serverUrl,t.serverUrl))return"proceed";h(`This machine is enrolled against ${n.serverUrl} (agent ${n.agentId}), not ${t.serverUrl}. An agent credential is valid only at the server that issued it.`);let r=await ko(`Reset it \u2014 revoke the agent on ${n.serverUrl}, remove its credential and autostart here \u2014 and enroll against ${t.serverUrl}?`,"no");if(r==="yes")return Vi(await sn(se(t.stateDir),wt))?(h(`Enrolling against ${t.serverUrl}\u2026`),"proceed"):(h(`Not enrolled against ${t.serverUrl}: the reset did not finish.`),"stopped");let i=Nn(G());return h(r==="no"?"Nothing was changed.":"Nothing was changed (no terminal to ask, no answer)."),h(` To move this machine to ${t.serverUrl}: progon-agent reset${i}, then ${e.text} again \u2014 or run it in a terminal and answer 'y'.`+(e.withCode?" The enrollment code was not used and stays valid until it expires.":"")),h(` To keep both, enroll the second one under its own state directory: PROGON_RUNNER_STATE_DIR=<dir> ${e.text} (and give 'progon-agent start' the same variable).`),"stopped"}o(Xi,"offerResetForOtherServer");import{spawn as hS}from"node:child_process";var Kn=w("browser-open");function Ao(t){return t!==void 0&&t!==""}o(Ao,"isSet");function gS(t,e){return!(Ao(t.SSH_CONNECTION)||Ao(t.SSH_TTY)||e==="linux"&&!Ao(t.DISPLAY)&&!Ao(t.WAYLAND_DISPLAY))}o(gS,"shouldAttemptBrowserOpen");var yS=/[&|^<>"'` ]/;function wS(t){let e;try{e=new URL(t)}catch{return!1}return e.protocol!=="http:"&&e.protocol!=="https:"||t!==e.href?!1:!yS.test(t)}o(wS,"isSpawnSafeUrl");function SS(t,e){switch(e){case"darwin":return{command:"open",args:[t]};case"linux":return{command:"xdg-open",args:[t]};case"win32":return{command:"cmd",args:["/d","/s","/c","start","",t]};default:return null}}o(SS,"browserOpenCommand");function jd(t,e,n){if(!gS(e,n)){Kn.debug("Not opening a browser: this host has no desktop to open one on",{platform:n});return}if(!wS(t)){Kn.warn('Not opening a browser: the verification URL the server returned is not safe to hand to a spawned process. Follow the "Approve at:" link printed above instead',{platform:n});return}let r=SS(t,n);if(r===null){Kn.debug("Not opening a browser: no opener is defined for this platform",{platform:n});return}try{let i=hS(r.command,[...r.args],{detached:!0,stdio:"ignore"});i.on("error",s=>{Kn.debug("Could not start the browser; the approval URL was printed instead",{platform:n,command:r.command,err:s.message})}),i.unref()}catch(i){Kn.debug("Could not start the browser; the approval URL was printed instead",{platform:n,command:r.command,err:i instanceof Error?i.message:String(i)})}}o(jd,"openVerificationUrl");var ES=30,vS=5;function Wd(t){return{intervalSec:t.pollIntervalSec,deadlineMs:t.timeoutSec===null?t.expiresAtMs:Math.min(t.expiresAtMs,t.nowMs+t.timeoutSec*1e3)}}o(Wd,"initialPollSchedule");function Co(t,e){if(e.kind==="pending")return{state:t,delayMs:t.intervalSec*1e3};if(e.kind==="slow_down"){let r=t.intervalSec+vS,i=e.retryAfterSec!==null&&e.retryAfterSec>r?e.retryAfterSec:r,s=Math.min(i,ES);return{state:{intervalSec:s,deadlineMs:t.deadlineMs},delayMs:s*1e3}}let n=ge(e.attempt,e.rng);return{state:t,delayMs:Math.max(t.intervalSec*1e3,n)}}o(Co,"nextPollDelayMs");function Hd(t,e){return e>=t.deadlineMs}o(Hd,"isDeadlinePassed");function Jd(t,e,n){return Math.max(0,Math.min(e,t.deadlineMs-n))}o(Jd,"clampDelayToDeadline");async function Kd(t,e){try{return await e()}catch(n){let r=bS(n,t);throw r!==null?r:n}}o(Kd,"explainingEnrollRefusals");function bS(t,e){let n=`progon-agent enroll <code> --server ${e}`;if(t instanceof At)return new p(`[progon-agent] ${e} did not accept the enrollment code: it is unknown, expired or already used \u2014 the server does not say which. Nothing was saved on this machine.
|
|
267
267
|
Create a new code in Progon and run: ${n}`,{cause:t});if(t instanceof ot)return new p(`[progon-agent] ${e} does not accept this version of progon-agent (${t.message}). Nothing was saved on this machine.
|
|
268
268
|
Update it with 'progon-agent update', then run: ${n}`,{cause:t});if(t instanceof x&&t.operation==="enroll"&&t.status===429){let r=t.retryAfterMs===null?"Wait, then run the command again.":`Wait ${Math.ceil(t.retryAfterMs/1e3)} s, then run the command again.`;return new p(`[progon-agent] ${e} refused the enrollment: too many attempts from this address. Nothing was saved on this machine.
|
|
269
|
-
${r}`,{cause:t})}return null}o(
|
|
270
|
-
`),zi;if(await Xi(n,{text:`progon-agent enroll --server ${n.serverUrl}`,withCode:!1})==="stopped")return St;let c=RS
|
|
271
|
-
`),process.exit(
|
|
272
|
-
`):process.stdout.write(`${
|
|
273
|
-
`),St;let S;try{S=await e.poll(i)}catch(I){if(I instanceof Nt)return process.stdout.write(`${
|
|
274
|
-
`),St;if(I instanceof Lt)return process.stdout.write(`${
|
|
275
|
-
`),St;if(I instanceof Dt)return
|
|
276
|
-
`),St;if(I instanceof $t)return
|
|
277
|
-
`),St;if(I instanceof Pt){let N=Co(a,{kind:"slow_down",retryAfterSec:I.retryAfterSec});a=N.state,d=N.delayMs,
|
|
278
|
-
`),zi;u=0;let b=Co(a,{kind:"pending"});a=b.state,d=b.delayMs}}finally{process.off("SIGINT",E),process.off("SIGTERM",E)}}o(
|
|
279
|
-
`),
|
|
269
|
+
${r}`,{cause:t})}return null}o(bS,"explainEnrollRefusal");var an=w("device-enrollment"),RS=24,TS=2e3,zi=0,St=1,qd=130,xS="This machine is already enrolled. Start the daemon with: progon-agent start",IS="Enrollment was denied in the browser. Nothing was created on this machine.",OS="Cancelled. Nothing was saved on this machine.",AS="progon-agent: interrupted again \u2014 exiting immediately. The enrollment request was not withdrawn; it expires on its own. Nothing was saved on this machine.";function Vd(t){return`Enrollment request expired. Run: progon-agent enroll --server ${t}`}o(Vd,"expiredLine");function CS(t,e){return`Timed out after ${t}s waiting for approval. The request is still open \u2014 approve at: ${e}`}o(CS,"timedOutLine");function PS(t){return`Enrollment could not be completed: the request was already used and no credential reached this machine. Run: progon-agent enroll --server ${t}`}o(PS,"alreadyCompletedLine");function NS(t){return`Enrollment request is no longer valid. Run: progon-agent enroll --server ${t}`}o(NS,"noLongerValidLine");async function Yd(t){let e=t.env??process.env;t.serverUrl!==void 0&&(process.env.PROGON_SERVER_URL=t.serverUrl);let n=Me(),r=Je(),i=e.PROGON_AGENT_ENROLL_CODE;if(i!==void 0&&i!=="")return Qi({config:n,machine:r,retryCommand:`progon-agent enroll --server ${n.serverUrl}`,fetchImpl:t.fetchImpl,rng:t.rng});let s=L(n.stateDir);if(s!==null&&Ue(s.serverUrl,n.serverUrl))return process.stdout.write(`${xS}
|
|
270
|
+
`),zi;if(await Xi(n,{text:`progon-agent enroll --server ${n.serverUrl}`,withCode:!1})==="stopped")return St;let c=kS(RS).toString("base64url"),a=new Oo(t.fetchImpl===void 0?{serverUrl:n.serverUrl,machine:r}:{serverUrl:n.serverUrl,machine:r,fetchImpl:t.fetchImpl}),d=await a.create(MS(c));return $S(d),t.openBrowser&&jd(d.verificationUrl,e,process.platform),LS({client:a,config:n,created:d,deviceSecret:c,timeoutSec:t.timeoutSec,rng:t.rng})}o(Yd,"runDeviceEnrollment");async function LS(t){let{client:e,config:n,created:r,deviceSecret:i,timeoutSec:s,rng:l}=t,c=Date.parse(r.expiresAt),a=Wd({pollIntervalSec:r.pollIntervalSec,expiresAtMs:c,timeoutSec:s,nowMs:Date.now()}),d=a.intervalSec*1e3,u=0,m={signal:null},g=new AbortController,E=o(S=>{m.signal!==null&&(process.stderr.write(`${AS}
|
|
271
|
+
`),process.exit(qd)),m.signal=S,g.abort()},"onSignal");process.on("SIGINT",E),process.on("SIGTERM",E);try{for(;;){if(await oe(Jd(a,d,Date.now()),g.signal),m.signal!==null)return await DS(e,i,m.signal);if(Hd(a,Date.now()))return s!==null&&a.deadlineMs<c?process.stdout.write(`${CS(s,r.verificationUrl)}
|
|
272
|
+
`):process.stdout.write(`${Vd(n.serverUrl)}
|
|
273
|
+
`),St;let S;try{S=await e.poll(i)}catch(I){if(I instanceof Nt)return process.stdout.write(`${IS}
|
|
274
|
+
`),St;if(I instanceof Lt)return process.stdout.write(`${Vd(n.serverUrl)}
|
|
275
|
+
`),St;if(I instanceof Dt)return an.warn("The enrollment request was already completed on the server; no credential reached this machine and nothing was saved",{requestId:r.requestId,errorCode:I.errorCode,status:I.status}),process.stdout.write(`${PS(n.serverUrl)}
|
|
276
|
+
`),St;if(I instanceof $t)return an.warn("The server no longer recognises this enrollment request",{requestId:r.requestId,errorCode:I.errorCode,status:I.status}),process.stdout.write(`${NS(n.serverUrl)}
|
|
277
|
+
`),St;if(I instanceof Pt){let N=Co(a,{kind:"slow_down",retryAfterSec:I.retryAfterSec});a=N.state,d=N.delayMs,an.warn("The server asked this machine to poll more slowly",{intervalSec:a.intervalSec,retryAfterSec:I.retryAfterSec});continue}if(I instanceof Z||I instanceof x&&I.status>=500){let N=Co(a,{kind:"transport_error",attempt:u,rng:l});u+=1,a=N.state,d=N.delayMs,an.warn("The enrollment poll failed; retrying until the request expires",{attempt:u,delayMs:d,err:I.message});continue}throw I}if(S.kind==="enrolled")return It(n.stateDir,{agentId:S.credential.agentId,agentToken:S.credential.agentToken,protocolVersion:S.credential.protocolVersion,serverUrl:n.serverUrl,tokenRotatedAt:null}),process.stdout.write(`Enrolled into ${S.approval.companyName} (approved by ${S.approval.approvedByEmail}). Start the daemon: progon-agent start
|
|
278
|
+
`),zi;u=0;let b=Co(a,{kind:"pending"});a=b.state,d=b.delayMs}}finally{process.off("SIGINT",E),process.off("SIGTERM",E)}}o(LS,"waitForApproval");async function DS(t,e,n){try{await Ke({operation:"device enrollment cancel",timeoutMs:TS,work:o(()=>t.cancel(e),"work")})}catch(r){an.warn("The enrollment request could not be withdrawn on the server; it expires on its own within its TTL and no agent was created",{signal:n,err:r instanceof Error?r.message:String(r)})}return process.stdout.write(`${OS}
|
|
279
|
+
`),qd}o(DS,"cancelRequest");async function Qi(t){let{config:e,machine:n,fetchImpl:r,rng:i}=t;if(e.initialToken===void 0&&await Xi(e,{text:t.retryCommand,withCode:!0})==="stopped")return St;let s=await Kd(e.serverUrl,()=>Fr({config:e,machine:n,fetchImpl:r,rng:i}));return Ll(s,e),an.info("This machine is enrolled \u2014 start the daemon with: progon-agent start",{agentId:s.agentId,hostname:n.hostname,stateDir:e.stateDir}),zi}o(Qi,"redeemEnrollmentCode");function $S(t){process.stdout.write(`Enrollment requested for this machine.
|
|
280
280
|
Confirmation code: ${t.userCode}
|
|
281
281
|
Approve at: ${t.verificationUrl}
|
|
282
|
-
Waiting for approval (expires in ${
|
|
283
|
-
`)}o(
|
|
282
|
+
Waiting for approval (expires in ${US(t.expiresAt)})...
|
|
283
|
+
`)}o($S,"printRequestOpened");function US(t){let e=Date.parse(t)-Date.now();return`${Math.ceil(e/6e4)}m`}o(US,"describeExpiry");function MS(t){return _S("sha256").update(t,"utf8").digest("hex")}o(MS,"sha256Hex");var Xd=`progon-agent \u2014 the Progon local agent (CONTRACT-la \xA78)
|
|
284
284
|
|
|
285
285
|
Usage:
|
|
286
286
|
progon-agent enroll <code> [--server <url>] Redeem a one-shot enrollment code (\xA75.1) and
|
|
@@ -309,7 +309,7 @@ Usage:
|
|
|
309
309
|
the result, print the report and the link, exit
|
|
310
310
|
with a code for the pipeline. Details:
|
|
311
311
|
'progon-agent ci run --help'.
|
|
312
|
-
${
|
|
312
|
+
${bc}
|
|
313
313
|
|
|
314
314
|
Autostart after 'enroll' (both forms): at the end a terminal is asked 'Start the runner
|
|
315
315
|
automatically in the background? (Y/n)'. --autostart answers yes ('service enable'),
|
|
@@ -378,10 +378,10 @@ Environment (see CONTRACT-la \xA78 for the full list):
|
|
|
378
378
|
PROGON_RUNNER_STATE_DIR optional \u2014 the state directory (enrollment, browser profiles).
|
|
379
379
|
--state-dir sets it for one command. Default: the platform's
|
|
380
380
|
standard per-user directory.
|
|
381
|
-
PROGON_AGENT_HEADFUL optional \u2014 show the browser on this machine's desktop.`;function
|
|
381
|
+
PROGON_AGENT_HEADFUL optional \u2014 show the browser on this machine's desktop.`;function tu(t){let[e,...n]=t;if(e===void 0||e==="--help"||e==="-h"||e==="help")return{kind:"usage",reason:null};if(e==="start")return BS(n);if(_c(e)){let r=kc(e,n);return r.kind==="refusal"?{kind:"usage",reason:r.reason}:{kind:"lifecycle",invocation:r.invocation}}return e==="install-browser"?n.length>0?{kind:"usage",reason:"'install-browser' takes no arguments"}:{kind:"install-browser"}:e==="enroll"?WS(n):e==="ci"?{kind:"ci",args:n}:{kind:"usage",reason:`unknown command '${e}'`}}o(tu,"parseCliArgs");function BS(t){let e,n=!1;for(let r=0;r<t.length;r+=1){let i=t[r];if(i==="--service"&&!n){n=!0;continue}if(i==="--state-dir"&&e===void 0){let s=On(t,r);if("reason"in s)return{kind:"usage",reason:s.reason};e=s.path,r+=1;continue}return{kind:"usage",reason:`unknown or repeated option '${String(i)}' for 'start'`}}return{kind:"start",stateDir:e,service:n}}o(BS,"parseStart");function nu(t,e,n){return t[e]!=="--state-dir"?null:n!==void 0?{reason:"'--state-dir' is given twice"}:On(t,e)}o(nu,"readEnrollStateDir");function ru(t,e){if(t!=="--autostart"&&t!=="--no-autostart")return null;let n=t==="--autostart"?"on":"off";return e!=="ask"?{reason:e===n?`'${t}' is given twice`:"'--autostart' and '--no-autostart' contradict each other \u2014 give one"}:{choice:n}}o(ru,"readAutostartFlag");function jS(t){return t.startsWith("-")&&t.length<32}o(jS,"isOptionInCodeSlot");function WS(t){let[e,...n]=t;if(e===void 0||jS(e))return HS(t);let r,i="ask",s;for(let l=0;l<n.length;l+=1){let c=n[l],a=ru(c,i);if(a!==null){if("reason"in a)return{kind:"usage",reason:a.reason};i=a.choice;continue}let d=nu(n,l,s);if(d!==null){if("reason"in d)return{kind:"usage",reason:d.reason};s=d.path,l+=1;continue}if(c!=="--server"||r!==void 0)return{kind:"usage",reason:`unknown or repeated option '${String(c)}' for 'enroll'`};let u=n[l+1];if(u===void 0)return{kind:"usage",reason:"'--server' needs a URL"};r=u,l+=1}return{kind:"enroll",code:e,serverUrl:r,autostart:i,stateDir:s}}o(WS,"parseEnroll");var zd=1,Qd=3600;function HS(t){let e,n=!0,r=null,i="ask",s;for(let l=0;l<t.length;l+=1){let c=t[l],a=ru(c,i);if(a!==null){if("reason"in a)return{kind:"usage",reason:a.reason};i=a.choice;continue}let d=nu(t,l,s);if(d!==null){if("reason"in d)return{kind:"usage",reason:d.reason};s=d.path,l+=1;continue}if(c==="--no-open"){n=!1;continue}if(c==="--server"){let u=t[l+1];if(u===void 0)return{kind:"usage",reason:"'--server' needs a URL"};e=u,l+=1;continue}if(c==="--timeout"){let u=t[l+1];if(u===void 0)return{kind:"usage",reason:"'--timeout' needs a number of seconds"};if(!/^[0-9]+$/.test(u))return{kind:"usage",reason:`'--timeout' takes a whole number of seconds, got '${u}'`};let m=Number(u);if(m<zd||m>Qd)return{kind:"usage",reason:`'--timeout' must be between ${zd} and ${Qd} seconds, got '${u}'`};r=m,l+=1;continue}return{kind:"usage",reason:`unknown option '${String(c)}' for 'enroll'`}}return{kind:"enroll-device",serverUrl:e,openBrowser:n,timeoutSec:r,autostart:i,stateDir:s}}o(HS,"parseEnrollDevice");function Zi(t){t!==void 0&&(process.env.PROGON_RUNNER_STATE_DIR=t)}o(Zi,"useStateDir");async function JS(t){let e=tu(t);switch(e.kind){case"usage":return e.reason===null?(process.stdout.write(`${Xd}
|
|
382
382
|
`),0):(process.stderr.write(`progon-agent: ${e.reason}
|
|
383
383
|
|
|
384
|
-
${
|
|
385
|
-
`),2);case"enroll":return Zi(e.stateDir),
|
|
384
|
+
${Xd}
|
|
385
|
+
`),2);case"enroll":return Zi(e.stateDir),Zd(await VS(e.code,e.serverUrl),e.autostart);case"enroll-device":return Zi(e.stateDir),Zd(await Yd({serverUrl:e.serverUrl,openBrowser:e.openBrowser,timeoutSec:e.timeoutSec}),e.autostart);case"install-browser":return KS();case"ci":return vc(e.args);case"lifecycle":return Pd(e.invocation);case"start":{Zi(e.stateDir);let n=await Ud({service:e.service});return n!==null&&e.service?vi(n,process.platform):n}}}o(JS,"runAgentCli");async function Zd(t,e){return t!==0?t:bd(e)}o(Zd,"afterEnrollment");async function KS(){return await kt({stdio:"terminal"}),0}o(KS,"installBrowser");async function VS(t,e){process.env.PROGON_AGENT_ENROLL_CODE=t,e!==void 0&&(process.env.PROGON_SERVER_URL=e);let n=Me();return Qi({config:n,machine:Je(),retryCommand:`progon-agent enroll <code> --server ${n.serverUrl}`})}o(VS,"enrollThisMachine");function qS(t,e){let n=C(t instanceof Error?t.message:String(t));if((e.kind==="enroll"||e.kind==="enroll-device"||e.kind==="lifecycle")&&(t instanceof p||t instanceof ee||t instanceof _))return`${n}
|
|
386
386
|
`;let i=t instanceof Error?t.stack:void 0;return JSON.stringify({level:"fatal",module:"cli",msg:"progon-agent failed",err:n,stack:i===void 0?void 0:C(i)})+`
|
|
387
|
-
`}o(
|
|
387
|
+
`}o(qS,"formatCliFailure");function YS(t){JS(t).then(e=>{e!==null&&process.exit(e)}).catch(e=>{let n=tu(t);process.stderr.write(qS(e,n)),process.exit(XS(e,n))})}o(YS,"runAgentCliProcess");function XS(t,e){return e.kind==="start"&&(t instanceof p||t instanceof ee)?e.service?vi(78,process.platform):78:1}o(XS,"failureExitCode");var eu=process.argv[1];eu!==void 0&&import.meta.url===FS(GS(eu)).href&&YS(process.argv.slice(2));export{qS as formatCliFailure,tu as parseCliArgs,JS as runAgentCli,YS as runAgentCliProcess};
|