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