progon-agent 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +167 -0
- package/README.md +340 -0
- package/dist/supervisor/cli.js +87 -0
- package/extension-bundle.json +6 -0
- package/extension-dist/background/background.js +127 -0
- package/extension-dist/content/canvas-interceptor.js +1 -0
- package/extension-dist/content/canvas-mapbox-bridge-main.js +1 -0
- package/extension-dist/content/canvas-mapbox-fiber-discovery.js +1 -0
- package/extension-dist/content/content.css +1 -0
- package/extension-dist/content/content.js +496 -0
- package/extension-dist/content/early-nonce-inject.js +1 -0
- package/extension-dist/content/main-world-nav.js +1 -0
- package/extension-dist/icons/icon128.png +0 -0
- package/extension-dist/icons/icon16.png +0 -0
- package/extension-dist/icons/icon48.png +0 -0
- package/extension-dist/manifest.json +115 -0
- package/extension-dist/offscreen/offscreen.html +10 -0
- package/extension-dist/offscreen/offscreen.js +1 -0
- package/extension-dist/popup/popup.css +1 -0
- package/extension-dist/popup/popup.html +443 -0
- package/extension-dist/popup/popup.js +43 -0
- package/extension-dist/sidepanel/sidepanel.css +1 -0
- package/extension-dist/sidepanel/sidepanel.html +13 -0
- package/extension-dist/sidepanel/sidepanel.js +227 -0
- package/package.json +72 -0
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
var oo=Object.defineProperty;var i=(t,e)=>oo(t,"name",{value:e,configurable:!0});import{realpathSync as hs}from"node:fs";import{pathToFileURL as gs}from"node:url";import{z as Bt}from"zod";var io=/^[a-z_]{1,32}@\d{1,3}$/,Jt=Bt.array(Bt.string().regex(io)).min(1).max(32),Vt=["playback@1"],Ht="make_auto@1",Kt="atlas_crawl@1";import{z as g}from"zod";var Q=/^pgat_[0-9A-Za-z]{43}$/;var be="agent:command",Oe="agent:command-ack",yt="agent:active-job";import{z as l}from"zod";import{z as w}from"zod";var so=w.object({scenarioId:w.uuid(),scenarioName:w.string().min(1)}).strict(),Wt=8192,lo=w.string().min(1).refine(t=>new TextEncoder().encode(t).length<=Wt,`instructions must be at most ${String(Wt)} UTF-8 bytes`),Yt=w.object({scenarios:w.array(so).min(1).max(1e3),projectId:w.uuid(),projectDomain:w.string().min(1),applicationId:w.uuid().nullable(),environmentId:w.uuid().nullable(),entryUrl:w.url({protocol:/^https?$/}),instructions:lo.nullable(),headful:w.boolean()}).strict(),Xt=w.object({projectId:w.uuid(),projectDomain:w.string().min(1),entryUrl:w.url({protocol:/^https?$/}),standMode:w.enum(["main","dangerous"]),accountLabel:w.string().min(1),role:w.string().min(1),locale:w.string().min(1),viewportWidth:w.number().int().min(1),viewportHeight:w.number().int().min(1)}).strict();import{z as ke}from"zod";var co=["queued","launching","in_progress","completed","failed","cancelled"],Ns=ke.enum(co);var uo=["queued","launching","in_progress"],zt=ke.enum(uo);var Zt=["claim_timeout","launch_timeout","launch_error","browser_gone","agent_lost","max_duration","killed"],Cs=ke.enum(Zt),mo=["launch_error","browser_gone","max_duration"],Qt=ke.enum(mo);var po=[...Zt,"stalled","capability_mismatch","subject_rejected"],Ds=ke.enum(po);var ho=l.enum(["darwin","linux","win32"]),go=l.enum(["x64","arm64"]),en=l.enum(["official","debug"]),js=l.object({enrollmentCode:l.string().min(32),hostname:l.string().min(1).max(255),platform:ho,arch:go,agentVersion:l.string().min(1).max(30),protocolVersion:l.number().int().min(1)}).strict(),Pe=l.object({agentId:l.uuid(),agentToken:l.string().regex(Q),pollWaitSec:l.number().int().min(1).max(25),protocolVersion:l.literal(1)}).strict(),qs=l.object({waitSec:l.coerce.number().int().min(0).max(25).optional()}).strict(),tn=l.object({agent:l.object({revoked:l.boolean()}).strict(),run:l.union([l.null(),l.object({runId:l.uuid(),phase:zt}).strict()])}).strict(),wt=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(),Et=l.object({v:l.literal(1),kind:l.literal("make_auto"),runId:l.uuid(),issuedAt:l.iso.datetime(),...Yt.shape}).strict(),_t=l.object({v:l.literal(1),kind:l.literal("atlas_crawl"),runId:l.uuid(),issuedAt:l.iso.datetime(),...Xt.shape}).strict(),Bs=l.discriminatedUnion("kind",[wt,Et,_t]),fo={playback:!0,make_auto:!0,atlas_crawl:!0},Js=Object.keys(fo),Vs=l.object({agentJobId:l.uuid(),updatedAt:l.iso.datetime()}).strict(),yo=l.enum(["invalid_envelope","dispatch_failed"]),nn=l.discriminatedUnion("outcome",[l.object({runId:l.uuid(),outcome:l.literal("dispatched")}).strict(),l.object({runId:l.uuid(),outcome:l.literal("rejected"),reason:yo}).strict()]),rn=l.object({cancelRequested:l.boolean(),killRequested:l.boolean()}).strict(),wo=2147483646,Eo=l.object({stepId:l.uuid(),stepIndex:l.number().int().min(0).max(wo),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(),Hs=l.object({events:l.array(Eo).min(1).max(50)}).strict(),Ks=l.object({updated:l.number().int().min(0),control:rn}).strict(),Ws=l.object({phase:l.enum(["running","paused"])}).strict(),Ys=l.object({control:rn}).strict(),Xs=l.object({reason:Qt,message:l.string().max(500).optional()}).strict(),on=l.object({status:l.enum(["failed","already_terminal"])}).strict();var nl=g.union([g.object({}).strict(),g.object({capabilities:Jt}).strict()]);function bt(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(bt,"checkClaimRunIdAgreement");function _o(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(_o,"checkPlaybackClaimProjectAgreement");var bo=g.object({runId:g.uuid(),scenarioId:g.uuid(),projectId:g.uuid(),applicationId:g.uuid().nullable(),projectDomain:g.string().min(1),entryUrl:g.url({protocol:/^https?$/}),environmentId:g.uuid().nullable(),runPurpose:en,headful:g.boolean(),maxRunDurationSec:g.number().int().min(60).max(3600),extensionSession:g.object({accessToken:g.string().min(1),refreshToken:g.string().min(1)}).strict(),command:wt}).strict().check(bt).check(_o),sn=g.object({accessToken:g.string().min(1),refreshToken:g.string().min(1)}).strict(),ko=g.object({kind:g.literal("make_auto"),runId:g.uuid(),entryUrl:g.url({protocol:/^https?$/}),headful:g.boolean(),maxRunDurationSec:g.number().int().min(60).max(604800),extensionSession:sn,command:Et}).strict().check(bt),vo=g.object({kind:g.literal("atlas_crawl"),runId:g.uuid(),entryUrl:g.url({protocol:/^https?$/}),headful:g.boolean(),maxRunDurationSec:g.number().int().min(60).max(604800),extensionSession:sn,command:_t}).strict().check(bt),ln=g.union([bo,ko,vo]);import{spawn as No}from"node:child_process";import{existsSync as Co}from"node:fs";import{createRequire as Do}from"node:module";import{dirname as un,join as Lo}from"node:path";import xo from"pino";var So=new Set(["token","agenttoken","accesstoken","refreshtoken","pgrttoken","jobtoken","authorization","secret","password","resolvedvariables","cookie","set-cookie","x-api-key","proxy-authorization","api-key"]),Ro=/\b(?:pgat_|rr_|pgrt_)[A-Za-z0-9_-]+/g,To=/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,Ao=["token","secret","password","authorization","api_key","api-key","apikey"],Io=new RegExp(`([?&](?:${Ao.join("|")})=)([^&\\s]+)`,"gi"),Ne="[REDACTED]";function dn(t){let e=t.replace(To,Ne);return e=e.replace(Ro,Ne),e=e.replace(Io,`$1${Ne}`),e}i(dn,"redactValueString");function K(t){if(Array.isArray(t))return t.map(K);if(t!==null&&typeof t=="object"){let e=t,n={};for(let r of Object.keys(e))So.has(r.toLowerCase())?n[r]=Ne:n[r]=K(e[r]);return n}return typeof t=="string"?dn(t):t}i(K,"redactSecrets");function L(t){return dn(t)}i(L,"redactSensitiveText");function Oo(){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(Oo,"resolveLogLevel");function Po(){if(process.env.NODE_ENV!=="production")return{target:"pino-pretty",options:{translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname"}}}i(Po,"buildTransport");var cn=xo({name:"qa-runner",level:Oo(),transport:Po(),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 kt(t){return{debug(e,n){n!==void 0?t.debug(K(n),e):t.debug(e)},info(e,n){n!==void 0?t.info(K(n),e):t.info(e)},warn(e,n){n!==void 0?t.warn(K(n),e):t.warn(e)},error(e,n){n!==void 0?t.error(K(n),e):t.error(e)},child(e){return kt(t.child(e))}}}i(kt,"adaptPino");function u(t){return kt(cn.child({module:t}))}i(u,"createLogger");var fl=kt(cn);var vt=u("browser-provision"),Go=60*6e4,F=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}},mn=[" - 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 Mo(){let t=Do(import.meta.url),e;try{e=t.resolve("playwright-core/package.json")}catch(r){throw new F(`[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=Lo(un(e),"cli.js");if(!Co(n))throw new F(`[browser-provision] 'playwright-core' resolved to ${un(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(Mo,"resolveInstallCommand");async function Ce(t){let e=t.commandOverride===void 0?Mo():t.commandOverride,n=t.deadlineMs===void 0?Go:t.deadlineMs,r=t.stdio==="pipe"?[...e.args,"--no-progress"]:[...e.args],o=`${e.execPath} ${e.cliPath} ${r.join(" ")}`,a=Date.now();vt.info("Provisioning Chromium",{cliPath:e.cliPath,args:r,deadlineMs:n});let s=No(e.execPath,[e.cliPath,...r],{env:process.env,stdio:t.stdio==="inherit"?"inherit":["ignore","pipe","pipe"]});if(t.stdio==="pipe"){let{stdout:h,stderr:p}=s;if(h===null||p===null)throw new F(`[browser-provision] The installer was spawned without the stdout/stderr pipes this module requested (${o}).`);pn(h,"stdout"),pn(p,"stderr")}let d=!1,c=setTimeout(()=>{d=!0,s.kill("SIGKILL")},n),m=new Map,f=i(()=>{for(let[h,p]of m)process.off(h,p);m.clear()},"removeSignalHandlers");for(let h of["SIGTERM","SIGINT"]){let p=i(()=>{s.kill("SIGKILL"),f(),process.stderr.write(JSON.stringify({level:"warn",module:"browser-provision",msg:"Chromium provisioning aborted by signal: the installer was killed, and the next start downloads again",signal:h,installerPid:s.pid})+`
|
|
4
|
+
`),process.kill(process.pid,h)},"handler");m.set(h,p),process.on(h,p)}try{await new Promise((h,p)=>{s.once("error",S=>{p(new F(`[browser-provision] Could not start the Playwright installer (${o}): ${S.message}`,{cause:S}))}),s.once("close",(S,v)=>{if(d){p(new F(`[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
|
+
${mn}`,{exitCode:S,timedOut:!0}));return}if(S===0){h();return}let xe=S===null?`was terminated by signal ${String(v)}`:`exited with code ${S}`;p(new F(`[browser-provision] Chromium could not be installed: the Playwright installer ${xe} (${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
|
+
${mn}`,{exitCode:S}))})})}finally{clearTimeout(c),f()}vt.info("Chromium is provisioned",{durationMs:Date.now()-a})}i(Ce,"provisionBrowser");function pn(t,e){let n="";t.setEncoding("utf8"),t.on("data",r=>{n+=r;let o=n.lastIndexOf(`
|
|
7
|
+
`);if(o===-1)return;let a=n.slice(0,o);n=n.slice(o+1);for(let s of a.split(`
|
|
8
|
+
`))hn(s,e)}),t.on("end",()=>{let r=n;n="",hn(r,e)})}i(pn,"forwardLinesToLogger");function hn(t,e){let n=t.replace(/\r/g,"").trim();n!==""&&vt.info("Chromium provisioning output",{stream:e,line:n})}i(hn,"logLine");import{homedir as Yo}from"node:os";import{isAbsolute as _n,join as De}from"node:path";import{Agent as $o,EnvHttpProxyAgent as Uo}from"undici";var gn=u("gateway-proxy"),Fo=["http_proxy","HTTP_PROXY"],jo=["https_proxy","HTTPS_PROXY"],qo=["no_proxy","NO_PROXY"];function Bo(t){return t.http!==void 0||t.https!==void 0}i(Bo,"gatewayIsProxied");var Jo=/^[A-Za-z][A-Za-z0-9+.-]*:\/\//,Vo=/:\d+$/,Ho=/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)?[^/?#]*@/;function Ko(t){let e=Ho.exec(t);if(e===null)return t;let n=e[1];return`${n===void 0?"":n}***@${t.slice(e[0].length)}`}i(Ko,"withoutProxyCredentials");function te(t,e,n){return new Error(`[config] ${t} does not name a proxy this agent can use: ${n}. Got: ${JSON.stringify(Ko(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(te,"refuseProxyValue");function fn(t,e){for(let n of e){let r=t[n];if(r!==void 0)return r===""?void 0:{variable:n,raw:r}}}i(fn,"readProxyVariable");function Wo(t){for(let e of qo){let n=t[e];if(n!==void 0)return n}}i(Wo,"readNoProxy");function yn(t,e){if(Jo.test(e)){let s;try{s=new URL(e)}catch{throw te(t,e,"it carries a scheme but is not a URL that parses")}if(s.protocol!=="http:"&&s.protocol!=="https:")throw te(t,e,`its scheme is ${JSON.stringify(s.protocol)}, not http: or https:`);if(s.hostname==="")throw te(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(!Vo.test(r))throw te(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 te(t,e,'it is neither a URL nor a "host:port" pair')}if(a.hostname==="")throw te(t,e,"it names no host");return{variable:t,url:o,schemeCompleted:!0}}i(yn,"parseProxyValue");function St(t){let e=fn(t,Fo),n=fn(t,jo);return{http:e===void 0?void 0:yn(e.variable,e.raw),https:n===void 0?void 0:yn(n.variable,n.raw),noProxy:Wo(t)}}i(St,"resolveGatewayProxyConfig");function wn(t,e){if(!Bo(t))return new $o(e);gn.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 n=[];for(let r of[t.http,t.https])r!==void 0&&r.schemeCompleted&&n.push(r.variable);return n.length>0&&gn.info('A proxy variable carries no scheme and is read as an HTTP proxy (curl convention: "host:port" means "http://host:port")',{variables:n}),new Uo({...e,httpProxy:t.http?.url,httpsProxy:t.https?.url,noProxy:t.noProxy})}i(wn,"createProxyAwareDispatcher");function En(t){St(t)}i(En,"validateGatewayProxyEnv");var Xo=new Set(["localhost","127.0.0.1","::1","[::1]"]);function Rt(t){let e;try{e=new URL(t)}catch{throw new Error("[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:"&&Xo.has(e.hostname)))throw new Error(`[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 Error(`[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 Error("[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 Error(`[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(Rt,"validateServerUrl");function Tt(t){if(!Q.test(t))throw new Error("[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(Tt,"validateRunnerToken");function bn(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 Error(`[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(bn,"validateRunnerMachineId");function kn(t){if(t!==1)throw new Error(`[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(kn,"validateProtocolVersion");function zo(t){let e=process.env[t];if(e===void 0||e==="")throw new Error(`[config] Required environment variable ${t} is not set. See docs/working/local-agent-v1/CONTRACT-la.md \xA78 for the full env key list.`);return e}i(zo,"getRequired");function Le(t){let e=process.env[t];return e!==void 0&&e!==""?e:void 0}i(Le,"getOptional");function Zo(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 Error(`[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(Zo,"getOptionalBool");var Ge="progon-agent";function Qo(t,e,n){if(n==="")throw new Error("[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 De(n,"Library","Application Support",Ge);case"linux":{let r=e.XDG_STATE_HOME;if(r===void 0||r==="")return De(n,".local","state",Ge);if(!_n(r))throw new Error(`[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 De(r,Ge)}case"win32":{let r=e.APPDATA;if(r===void 0||r==="")throw new Error("[config] %APPDATA% is not set, so the default Windows state directory cannot be resolved. Set PROGON_RUNNER_STATE_DIR explicitly.");return De(r,Ge)}default:throw new Error(`[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(Qo,"resolveDefaultStateDir");function ne(){let t=zo("PROGON_SERVER_URL");Rt(t),En(process.env);let e=process.env.PROGON_AGENT_TOKEN;if(e==="")throw new Error("[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 n=e;n!==void 0&&Tt(n);let r=Le("PROGON_AGENT_EXTENSION_DIST");if(r!==void 0&&!_n(r))throw new Error(`[config] PROGON_AGENT_EXTENSION_DIST must be an absolute path, got: ${JSON.stringify(r)}. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`);let o=Le("PROGON_AGENT_ENROLL_CODE");if(o!==void 0&&o.length<32)throw new Error(`[config] PROGON_AGENT_ENROLL_CODE is shorter than the ${32} characters an enrollment code has (got ${o.length}). Copy the whole code from the agent's enrollment dialog. See docs/working/local-agent-v1/CONTRACT-la.md \xA75.1.`);return{serverUrl:t,initialToken:n,stateDir:Le("PROGON_RUNNER_STATE_DIR")??Qo(process.platform,process.env,Yo()),extensionDistOverride:r,headfulOverride:Zo("PROGON_AGENT_HEADFUL",!1),enrollmentCode:o,nodeEnv:Le("NODE_ENV")??"production"}}i(ne,"loadConfig");function ve(t,e,n){process.stderr.write(JSON.stringify({level:t,module:"process-guards",msg:e,...n})+`
|
|
9
|
+
`)}i(ve,"writeLine");function Sn(t){let e=t instanceof Error?t.message:String(t),n=t instanceof Error?t.stack:void 0;return{err:L(e),stack:n!==void 0?L(n):void 0}}i(Sn,"describeError");function vn(t,e,n){ve("fatal",`Unhandled ${t} \u2014 terminating the daemon`,{event:t,...Sn(e),...n})}i(vn,"writeFatalLine");function Rn(){process.on("uncaughtException",(t,e)=>{vn("uncaughtException",t,{origin:e}),process.exit(1)}),process.on("unhandledRejection",t=>{vn("unhandledRejection",t,{}),process.exit(1)})}i(Rn,"installProcessGuards");function Tn(t){let e=!1,n=i(r=>{if(e){ve("info","Shutdown already in progress \u2014 signal ignored",{signal:r});return}e=!0,ve("info","Signal received \u2014 shutting down",{signal:r}),(async()=>{try{await t(r)}catch(o){ve("fatal","Shutdown hook failed \u2014 the daemon may leave resources behind",{signal:r,...Sn(o)}),process.exit(1)}ve("info","Shutdown complete",{signal:r}),process.exit(0)})()},"handle");process.on("SIGTERM",n),process.on("SIGINT",n)}i(Tn,"installShutdownHandlers");import{chmodSync as oi,cpSync as ii,mkdirSync as ai,readdirSync as si,renameSync as li,rmSync as It,statSync as xn,writeFileSync as di}from"node:fs";import{dirname as ci,join as re}from"node:path";import{fileURLToPath as ui}from"node:url";import{statSync as ei}from"node:fs";import{dirname as ti,join as ni}from"node:path";var An="package.json";function In(t){let e=t;for(;;){if(ri(e))return e;let n=ti(e);if(n===e)throw new Error(`[package-root] No ${An} 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(In,"findPackageRoot");function ri(t){try{return ei(ni(t,An)),!0}catch(e){if(typeof e=="object"&&e!==null){let n=e.code;if(n==="ENOENT"||n==="ENOTDIR")return!1}throw e}}i(ri,"holdsPackageManifest");var Me=u("extension-dist"),mi="extension-dist",Nn="extension-dist",Cn=`${Nn}.tmp-`,xt="agent-manifest.json",On="manifest.json";function pi(){return In(ci(ui(import.meta.url)))}i(pi,"packageRoot");function hi(){return gi(re(pi(),mi))}i(hi,"resolveBundledExtensionSource");function gi(t){let e;try{e=xn(t)}catch(r){throw Pn(r)?new Error(At(t,"the directory does not exist"),{cause:r}):r}if(!e.isDirectory())throw new Error(At(t,"that path is not a directory"));let n=re(t,On);try{xn(n)}catch(r){throw Pn(r)?new Error(At(t,`it holds no ${On}`),{cause:r}):r}return t}i(gi,"assertBundledExtensionSource");function Pn(t){if(typeof t!="object"||t===null)return!1;let e=t.code;return e==="ENOENT"||e==="ENOTDIR"}i(Pn,"isAbsentPathError");function At(t,e){return`[extension-dist] No extension dist is bundled in this package (${t}): ${e}.
|
|
10
|
+
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.
|
|
11
|
+
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(At,"bundledMissingMessage");function fi(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??hi(),o=re(e,Nn),a=re(e,`${Cn}${process.pid}`);return ai(e,{recursive:!0,mode:448}),wi(e),It(a,{recursive:!0,force:!0}),ii(r,a,{recursive:!0}),oi(a,448),yi(a,n),It(o,{recursive:!0,force:!0}),li(a,o),Me.info("Agent-mode extension dist prepared",{extensionDist:o,sourceDir:r,agentId:n,protocolVersion:1}),o}i(fi,"prepareAgentExtensionDist");function yi(t,e){let n={agentMode:!0,agentId:e,protocolVersion:1};di(re(t,xt),JSON.stringify(n,null,2)+`
|
|
12
|
+
`,"utf8")}i(yi,"writeAgentManifest");function wi(t){let e;try{e=si(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(Cn))continue;let r=re(t,n.name);try{It(r,{recursive:!0,force:!0}),Me.warn("Removed a leftover extension-dist staging directory",{leftover:r})}catch(o){Me.error("Failed to remove a leftover extension-dist staging directory",{leftover:r,err:o instanceof Error?o.message:String(o)})}}}i(wi,"removeLeftoverStagingDirs");function Dn(t){if(t.overridePath!==void 0)return Me.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).
|
|
13
|
+
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 fi({stateDir:t.stateDir,agentId:t.agentId})}i(Dn,"resolveExtensionDist");import{fetch as bi}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}},G=class extends k{static{i(this,"GatewayTransportError")}constructor(e,n,r){super(e,`[gateway] ${e} failed before a response was received: ${n}`,r)}},_=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}},oe=class extends _{static{i(this,"GatewayUnauthorizedError")}},b=class extends _{static{i(this,"TokenSupersededError")}},y=class extends k{static{i(this,"TerminalSignalError")}signal;constructor(e,n,r){super(e,`[gateway] agent revoked (${n}) during ${e}: ${r}`),this.signal=n}},$e=class extends _{static{i(this,"EnrollmentCodeRejectedError")}},Se=class extends _{static{i(this,"ProtocolVersionMismatchError")}},ie=class extends _{static{i(this,"RunNotClaimableError")}},W=class extends _{static{i(this,"RunNotFoundError")}},M=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 Ln=u("gateway-http");async function Y(t){let e={accept:"application/json"};t.agentToken!==null&&(e.authorization=`Bearer ${t.agentToken}`),t.body!==null&&(e["content-type"]="application/json"),Ln.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 G(t.operation,Gn(o),o)}let r;try{r=await n.text()}catch(o){throw new G(t.operation,Gn(o),o)}if(!n.ok){let o=Ei(n.status,r);throw Ln.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 M(t.operation,`the ${n.status} response body is not valid JSON`,o)}}i(Y,"executeGatewayRequest");function P(t,e){if(e.success)return e.data;throw new M(t,_i(e.error),e.error)}i(P,"parseGatewayBody");function Ei(t,e){let n;try{n=JSON.parse(e)}catch{return{status:t,errorCode:null,params:null,message:Ot}}if(typeof n!="object"||n===null||Array.isArray(n))return{status:t,errorCode:null,params:null,message:Ot};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"?L(s):Ot}}i(Ei,"readErrorEnvelope");var Ot="the response body carried no Progon error envelope";function Gn(t){return L(t instanceof Error?t.message:String(t))}i(Gn,"describeCause");function _i(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(_i,"summarizeSchemaViolation");var ae=class extends _{static{i(this,"EnrollmentSlowDownError")}retryAfterSec;constructor(e,n,r,o,a,s){super(e,n,r,o,a),this.retryAfterSec=s}},se=class extends _{static{i(this,"EnrollmentAccessDeniedError")}},le=class extends _{static{i(this,"EnrollmentRequestExpiredError")}},de=class extends _{static{i(this,"EnrollmentAlreadyCompletedError")}},ce=class extends _{static{i(this,"EnrollmentRequestInvalidError")}};function Mn(t){return t.status===401&&t.errorCode==="agent_enroll.invalid_code"?x($e,"enroll",t):t.status===409&&t.errorCode==="agent_enroll.protocol_version"?x(Se,"enroll",t):C("enroll",t)}i(Mn,"mapEnrollError");function $n(t){return t.status===409&&t.errorCode==="agent_enroll.protocol_version"?x(Se,"enrollment_request_create",t):C("enrollment_request_create",t)}i($n,"mapEnrollmentRequestCreateError");function Un(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 ae("enrollment_request_poll",t.status,t.errorCode,t.params,t.message,n)}return t.status===403&&t.errorCode==="agent_enroll.access_denied"?x(se,"enrollment_request_poll",t):t.status===410&&t.errorCode==="agent_enroll.expired"?x(le,"enrollment_request_poll",t):t.status===410&&t.errorCode==="agent_enroll.already_completed"?x(de,"enrollment_request_poll",t):t.status===401&&t.errorCode==="agent_enroll.invalid_request"?x(ce,"enrollment_request_poll",t):C("enrollment_request_poll",t)}i(Un,"mapEnrollmentRequestPollError");function Fn(t){return C("enrollment_request_cancel",t)}i(Fn,"mapEnrollmentRequestCancelError");function jn(t){return ue("poll_desired_state",t,()=>C("poll_desired_state",t))}i(jn,"mapPollDesiredStateError");function qn(t){return ue("claim",t,()=>t.status===409&&t.errorCode==="run.not_claimable"?x(ie,"claim",t):t.status===404?x(W,"claim",t):C("claim",t))}i(qn,"mapClaimError");function Bn(t){return ue("fail",t,()=>t.status===404?x(W,"fail",t):C("fail",t))}i(Bn,"mapFailError");function Jn(t){return ue("token_status",t,()=>C("token_status",t))}i(Jn,"mapTokenStatusError");function Vn(t){return ue("token_rotate",t,()=>C("token_rotate",t))}i(Vn,"mapTokenRotateError");function Hn(t){return ue("declare_capabilities",t,()=>C("declare_capabilities",t))}i(Hn,"mapDeclareCapabilitiesError");function ue(t,e,n){return e.status===403&&e.errorCode==="agents.revoked"?new y(t,"http_403_agents_revoked",e.message):e.status===401&&e.errorCode==="agents.token_superseded"?x(b,t,e):e.status===401?x(oe,t,e):n()}i(ue,"bearerRoute");function x(t,e,n){return new t(e,n.status,n.errorCode,n.params,n.message)}i(x,"named");function C(t,e){return x(_,t,e)}i(C,"generic");var Ue=[...Vt,Ht,Kt];import{z as X}from"zod";var Kn=X.object({rotationDue:X.boolean(),tokenRotatedAt:X.string().nullable(),anchorAt:X.string(),intervalDays:X.number().int()}),Wn=X.object({agentToken:X.string().regex(Q)});var Fe=u("gateway-client"),ki="/api/agent-gateway";function N(t,e){return new URL(`${t.replace(/\/+$/,"")}${ki}${e}`)}i(N,"buildGatewayUrl");var Yn=3e5,vi=1e4,Si={headersTimeout:Yn,bodyTimeout:Yn,connect:{timeout:vi}},Pt,Be=i((t,e)=>{if(Pt===void 0){let n=wn(St(process.env),Si);Pt=i((r,o)=>bi(r,{...o,dispatcher:n}),"defaultGatewayFetch")}return Pt(t,e)},"pinnedGatewayFetch"),je=class{static{i(this,"GatewayEnrollmentClient")}serverUrl;machine;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.machine=e.machine,this.fetchImpl=e.fetchImpl??Be}async enroll(e){let n={...this.machine,enrollmentCode:e,protocolVersion:1},r=await Y({operation:"enroll",method:"POST",url:N(this.serverUrl,"/enroll"),agentToken:null,body:n,signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:Mn}),o=P("enroll",Pe.safeParse(r));return Fe.info("Agent enrolled",{agentId:o.agentId,pollWaitSec:o.pollWaitSec,protocolVersion:o.protocolVersion}),o}},qe=class{static{i(this,"GatewayClient")}serverUrl;agentToken;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.agentToken=e.agentToken,this.fetchImpl=e.fetchImpl??Be}async authenticatedRequest(e){return Y({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=N(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:jn}),o=P("poll_desired_state",tn.safeParse(r));if(o.agent.revoked)throw new y("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:N(this.serverUrl,`/runs/${encodeURIComponent(e)}/claim`),body:{capabilities:Ue},signal:void 0,mapHttpError:qn});return P("claim",ln.safeParse(n))}async failRun(e,n){let r=await this.authenticatedRequest({operation:"fail",method:"POST",url:N(this.serverUrl,`/runs/${encodeURIComponent(e)}/fail`),body:n,signal:void 0,mapHttpError:Bn}),o=P("fail",on.safeParse(r));return Fe.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:N(this.serverUrl,"/token"),body:null,signal:e?.signal,mapHttpError:Jn});return P("token_status",Kn.safeParse(n))}async rotateToken(e){let n=await this.authenticatedRequest({operation:"token_rotate",method:"POST",url:N(this.serverUrl,"/token/rotate"),body:null,signal:e?.signal,mapHttpError:Vn});return P("token_rotate",Wn.safeParse(n))}async declareCapabilities(e){await this.authenticatedRequest({operation:"declare_capabilities",method:"POST",url:N(this.serverUrl,"/capabilities"),body:{capabilities:Ue},signal:e?.signal,mapHttpError:Hn}),Fe.info("Capabilities declared",{capabilities:Ue})}useAgentToken(e){this.agentToken=e,Fe.info("Adopted a rotated agent token for all subsequent gateway requests")}};var Ri=u("debug-env-guard"),Ti=["pw:protocol","pw:api"];function Ai(t){return t.replace(/[\\^$.|?+()[\]{}]/g,"\\$&")}i(Ai,"escapeRegExp");function Xn(t){if(t.startsWith("-"))return!1;let e=`^${t.split("*").map(Ai).join(".*?")}$`,n=new RegExp(e);return Ti.some(r=>n.test(r))}i(Xn,"enablesPlaywright");function Ii(){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=>Xn(o));if(n.length===0)return[];let r=e.filter(o=>!Xn(o));return r.length===0?delete process.env.DEBUG:process.env.DEBUG=r.join(","),Ri.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(Ii,"sanitizePlaywrightDebugEnv");Ii();import{statSync as Zn}from"node:fs";import{isAbsolute as Oi,join as Pi}from"node:path";import{createRequire as xi}from"node:module";var $=xi(import.meta.url)("playwright-core"),Je=$.chromium,Pd=$.firefox,Nd=$.webkit,Cd=$.selectors,Dd=$.devices,Ld=$.errors,Gd=$.request,Md=$._electron,$d=$._android;var Ve="chromium";var zn="instances",He="instance.json";async function Qn(t){return Je.launchPersistentContext(t.userDataDir,{headless:!t.headful,channel:Ve,args:[`--disable-extensions-except=${t.extensionDist}`,`--load-extension=${t.extensionDist}`,"--no-first-run","--no-default-browser-check"]})}i(Qn,"launchExtensionContext");function Ni(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(Ni,"requireBrowser");function er(t){return Ni(t).version()}i(er,"readChromeVersion");async function tr(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(tr,"raceClose");function nr(t){if(!Oi(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=Zn(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=Pi(t,"manifest.json");try{Zn(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(nr,"assertUsableExtensionDist");var Ci=u("worker-evaluate"),Nt=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 j(t){let e=t.evaluate(),n=!1;e.catch(a=>{n&&Ci.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 Nt(t.operation,t.timeoutMs))},t.timeoutMs)});try{return await Promise.race([e,o])}finally{r!==void 0&&clearTimeout(r)}}i(j,"evaluateWithDeadline");var rr="accessToken",or="refreshToken";async function ar(t,e){await j({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())),[rr,or,e.accessToken,e.refreshToken]),"evaluate")});let n=await j({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})})),[rr,or]),"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(ar,"seedRunSession");function ir(t){return JSON.stringify(Object.keys(t).sort().map(e=>[e,t[e]]))}i(ir,"canonicalise");async function sr(t,e){await j({operation:`write the command envelope to chrome.storage.local['${be}']`,timeoutMs:1e4,evaluate:i(()=>t.evaluate(([a,s])=>new Promise(d=>chrome.storage.local.set({[a]:s},()=>d())),[be,e]),"evaluate")});let n=await j({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)})),be),"evaluate")});if(typeof n!="object"||n===null)throw new Error(`command envelope read-back returned ${JSON.stringify(n)} \u2014 chrome.storage.local['${be}'] does not hold the envelope`);let r=ir({...e}),o=ir(n);if(r!==o)throw new Error(`command envelope read-back mismatch: wrote ${r}, read ${o}`)}i(sr,"seedCommandEnvelope");async function Li(t,e,n){let r=await j({operation:`read chrome.storage.local['${Oe}']`,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)})),Oe),"evaluate")});if(r===null)return{kind:"absent"};let o=nn.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(Li,"pollCommandAck");async function lr(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['${Oe}'] 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 Li(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(lr,"waitForCommandAck");import We from"node:os";import{createRequire as Gi}from"node:module";var dr=Gi(import.meta.url);function Mi(){let t=dr.resolve("playwright-core/package.json"),e=dr(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(Mi,"readPlaywrightCoreVersion");function cr(t){return{node:process.version,platform:`${We.platform()} ${We.release()} ${We.arch()}`,cpus:We.cpus().length,playwrightCore:Mi(),chromiumExecutable:Je.executablePath(),channel:Ve,extensionDist:t}}i(cr,"buildEnvFingerprint");import{mkdirSync as fr,readdirSync as Zi,readFileSync as Qi,renameSync as ea,rmSync as Dt,writeFileSync as ta}from"node:fs";import{join as Re}from"node:path";var q=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}},B=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}},Ye=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 Ui}from"node:child_process";import{promisify as Fi}from"node:util";import{setTimeout as hr}from"node:timers/promises";var Xe=Fi(Ui),ze={timeout:5e3};function gr(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(gr,"asExecFailure");function ji(t){let e=[];for(let n of t.split(`
|
|
14
|
+
`)){let r=n.trim();if(r==="")continue;let o=Number(r);!Number.isInteger(o)||o===process.pid||e.push(o)}return e}i(ji,"parsePidLines");var Ct="--user-data-dir=",qi=new Set([" "," ",'"',"'"]),Bi=new Set([" "," ",'"',"'"]);function Ji(t){return t.replace(/[\\^$.|?*+()[\]{}]/g,"\\$&")}i(Ji,"escapeEre");function Vi(t){return`(^|[[:space:]'"])${Ji(`${Ct}${t}`)}([[:space:]'"]|$)`}i(Vi,"buildAnchorPattern");function Hi(t,e){let n=t.toLowerCase(),r=`${Ct}${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||qi.has(a),c=s===void 0||Bi.has(s);if(d&&c)return!0}return!1}i(Hi,"matchesAnchor");async function Ki(t){try{let{stdout:e}=await Xe("pgrep",["-f",Vi(t)],ze);return ji(e)}catch(e){let n=gr(e);if(n!==null&&n.code===1&&n.stdout.trim()==="")return[];throw e}}i(Ki,"discoverPosix");async function ur(t){let n=`Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Where-Object { $_.ProcessId -ne $PID -and $_.CommandLine -and $_.CommandLine.Contains('${`${Ct}${t}`.replace(/'/g,"''")}') } | ForEach-Object { "$($_.ProcessId)\`t$($_.CommandLine)" }`,{stdout:r}=await Xe("powershell.exe",["-NoProfile","-NonInteractive","-Command",n],ze),o=[];for(let a of r.split(`
|
|
15
|
+
`)){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||Hi(c,t)&&o.push(d)}return o}i(ur,"discoverWin32");async function mr(){let{stdout:t}=await Xe("ps",["-A","-o","pid=,ppid=,pgid="],ze),e=[];for(let n of t.split(`
|
|
16
|
+
`)){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(mr,"readProcessTable");function Wi(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 f of m)r.has(f)||(r.add(f),o.push(f))}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(Wi,"expandTree");function Yi(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(Yi,"sigkill");async function Ze(t){return process.platform==="win32"?zi(t):Xi(t)}i(Ze,"killProcessTree");async function Xi(t){let e=await Ki(t);if(e.length===0)return{platform:process.platform,userDataDir:t,discoveredPids:[],signalledPids:[],survivorPids:[]};let n=await mr(),{members:r,groups:o}=Wi(n,e),a=[];for(let c of r)Yi(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 hr(500);let s=await mr(),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(Xi,"killProcessTreePosix");async function zi(t){let e=await ur(t),n=[];for(let o of e)try{await Xe("taskkill.exe",["/T","/F","/PID",String(o)],ze),n.push(o)}catch(a){let s=gr(a);if(s===null||s.code!==128)throw a}await hr(500);let r=await ur(t);return{platform:"win32",userDataDir:t,discoveredPids:e,signalledPids:n,survivorPids:r}}i(zi,"killProcessTreeWin32");var z=u("instance-registry");function Qe(t){return typeof t=="string"&&t!==""}i(Qe,"isNonEmptyString");function na(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(!Qe(n.runId))throw new Error(`[instance-registry] ${e} has a missing or empty runId.`);if(!Qe(n.userDataDir))throw new Error(`[instance-registry] ${e} has a missing or empty userDataDir.`);if(!Qe(n.startedAt)||!Qe(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(na,"parseInstanceRecord");function ra(t,e){let n=`${t}.tmp`;ta(n,JSON.stringify(e,null,2),{encoding:"utf8",mode:384}),ea(n,t)}i(ra,"writeMarkerAtomically");var et=class{static{i(this,"InstanceRegistry")}#e;constructor(e){this.#e=Re(e,zn)}get instancesRoot(){return this.#e}userDataDirFor(e){return Re(this.#e,e)}reserve(e,n){fr(this.#e,{recursive:!0,mode:448});let r=this.userDataDirFor(e);try{fr(r,{recursive:!1,mode:448})}catch(a){throw typeof a=="object"&&a!==null&&a.code==="EEXIST"?new B(e,r,a):a}let o=new Date().toISOString();try{ra(Re(r,He),{v:1,runId:e,agentPid:process.pid,userDataDir:r,startedAt:o,deadlineAt:n})}catch(a){try{Dt(r,{recursive:!0,force:!0})}catch(s){z.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 z.info("Instance reserved",{runId:e,userDataDir:r,deadlineAt:n}),{runId:e,userDataDir:r,startedAt:o,deadlineAt:n}}read(e){return this.#n(Re(this.userDataDirFor(e),He))}release(e){let n=this.userDataDirFor(e);Dt(n,{recursive:!0,force:!0}),z.info("Instance released",{runId:e,userDataDir:n})}listRunIds(){let e;try{e=Zi(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?z.warn("Startup sweep found leftover browser instances",{instancesRoot:this.#e,count:n.length,outcomes:n}):z.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=Re(n,He),o=null,a;try{o=this.#n(r),a="valid"}catch(d){a=(typeof d=="object"&&d!==null?d.code:null)==="ENOENT"?"missing":"unreadable",z.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 Ze(n);return z.warn("Leftover browser instance swept",{runId:e,userDataDir:n,marker:a,kill:s}),Dt(n,{recursive:!0,force:!0}),{runId:e,userDataDir:n,marker:a,record:o,kill:s,removed:!0}}#n(e){let n=Qi(e,"utf8");return na(JSON.parse(n),e)}};async function yr(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 j({operation:`read chrome.storage.session['tabStates'] and ['${yt}']`,timeoutMs:1e4,evaluate:i(()=>r.evaluate(async a=>{let s=await new Promise(h=>chrome.storage.session.get(["tabStates",a],h)),d=s.tabStates,c=typeof d!="object"||d===null?[]:Object.entries(d).map(([h,p])=>{let S=typeof p=="object"&&p!==null?p.playback:null;if(typeof S!="object"||S===null)return{tabId:h,playback:null};let v=S;return{tabId:h,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}}}),m=s[a],f=typeof m!="object"||m===null?null:(()=>{let h=m;return{agentJobId:typeof h.agentJobId=="string"?h.agentJobId:null,updatedAt:typeof h.updatedAt=="string"?h.updatedAt:null}})();return{tabs:c,agentJob:f}},yt),"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(yr,"probePlaybackSession");async function _r(t,e){let r=t.serviceWorkers()[0];return r!==void 0?r:t.waitForEvent("serviceworker",{timeout:e})}i(_r,"waitForServiceWorker");async function br(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(br,"readRuntimeId");async function kr(t){let e=Date.now(),n=await _r(t,5e3);try{let r=await br(n,1e4);return{worker:n,extensionId:r,serviceWorkerUrl:n.url(),attempts:1,readyAfterMs:Date.now()-e}}catch(r){let o=await t.newPage();try{let a=await _r(t,5e3),s=await br(a,1e4);return{worker:a,extensionId:s,serviceWorkerUrl:a.url(),attempts:2,readyAfterMs:Date.now()-e}}catch(a){let s=r instanceof Error?r.message:String(r),d=a instanceof Error?a.message:String(a);throw new Error(`extension readiness probe failed on both exp5 lanes. Direct attempt: ${s}. Page-open retry: ${d}.`,{cause:a})}finally{await o.close()}}}i(kr,"probeExtensionReadiness");var E=u("playwright-execution-runtime"),Gt=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}},tt=class{static{i(this,"PlaywrightExecutionRuntime")}#e;#t;#n;#r;#a;#o=null;#i=null;#s=!1;#c=null;#l=null;constructor(e){nr(e.extensionDist),this.#e=e.extensionDist,this.#t=e.headfulOverride,this.#n=e.onInstanceLost,this.#r=new et(e.stateDir),this.#a=cr(e.extensionDist),E.info("Execution runtime constructed",{stateDir:e.stateDir,instancesRoot:this.#r.instancesRoot,headfulOverride:e.headfulOverride,envFingerprint:this.#a})}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.#r.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"}:yr(e.context)}async startRun(e){let n=this.#o;if(n!==null)throw new Ye(e.runId,n.runId);let r=Date.now(),o=new Date(r+e.maxRunDurationSec*1e3).toISOString(),a=await J(e.runId,"instance_reserve",()=>this.#r.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.#u(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.#a});let c=null;try{let m=await J(e.runId,"browser_launch",()=>Qn({userDataDir:a.userDataDir,extensionDist:this.#e,headful:d}));c=m,s.context=m,this.#d(s);let f=await J(e.runId,"browser_version",()=>er(m)),h=await J(e.runId,"readiness_probe",()=>kr(m));await this.#m(e,h.worker),await J(e.runId,"entry_navigation",()=>aa(m,e)),await this.#h(e,m);let p={runId:e.runId,context:c,userDataDir:a.userDataDir,headful:d,extensionId:h.extensionId,chromeVersion:f,startedAt:a.startedAt,deadlineAt:o};this.#d(s),this.#p(p),this.#o=p,this.#i===s&&(this.#i=null),E.info("Run launched",{runId:e.runId,chromeVersion:f,extensionId:h.extensionId,readinessAttempts:h.attempts,readyAfterMs:h.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.#c;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.#g(e):(this.#o=null,this.#f({runId:e,context:a.context,userDataDir:a.userDataDir,timeoutMs:n,trigger:"dispose"}))}#u(e){return e.headful||this.#t}async#m(e,n){let r=await J(e.runId,"token_seed",()=>ar(n,e.extensionSession));E.info("Run session seeded into the browser profile",{runId:e.runId,accessTokenLength:r.accessTokenLength,refreshTokenLength:r.refreshTokenLength}),await J(e.runId,"command_seed",()=>sr(n,e.command)),E.info("Command envelope seeded",{runId:e.runId,command:e.command})}async#h(e,n){let r=await J(e.runId,"command_ack",()=>lr(n,e.runId,15e3));if(r.outcome==="rejected")throw new q(e.runId,"command_ack",`the extension refused the command envelope: ${r.reason}`);E.info("Command envelope dispatched by the extension",{runId:e.runId})}#d(e){if(e.disposeRequested)throw new Gt(e.runId)}#p(e){let n=i(o=>{if(this.#s||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.#c={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.#c?.promise===a&&(this.#c=null)});let s={runId:e.runId,at:new Date().toISOString(),source:o};E.error("Browser instance disappeared without a dispose",{...s}),this.#n(s)},"report");e.context.on("close",()=>n("context_closed"));let r=e.context.browser();r!==null&&r.on("disconnected",()=>n("browser_disconnected"))}#g(e){let n=this.#l;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.#r.release(e);let o={...n.result,instanceReleased:!0,durationMs:Date.now()-r};return this.#l={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.#s=!0;let r="closed",o=null,a=null;try{if(e.context!==null){let p=await tr(e.context,e.timeoutMs);p.settled==="closed"?r="closed":p.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: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 Ze(e.userDataDir)}catch(p){a=p,E.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,m=!1;if(d)try{this.#r.release(e.runId),m=!0}catch(p){c=p,E.error("Failed to remove the instance directory after teardown",{runId:e.runId,userDataDir:e.userDataDir,err:p instanceof Error?p.message:String(p)})}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 f={runId:e.runId,outcome:r,kill:o,instanceReleased:m,durationMs:Date.now()-n};this.#l={runId:e.runId,result:f,killConfirmed:d};let h={runId:f.runId,disposeOutcome:f.outcome,trigger:e.trigger,contextPresent:e.context!==null,kill:f.kill,killFailed:a!==null,instanceReleased:f.instanceReleased,durationMs:f.durationMs};if(a!==null||c!==null?E.error("Instance disposed with a failed cleanup step",h):E.info("Instance disposed",h),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 f}finally{this.#s=!1}}};async function J(t,e,n){try{return await n()}catch(r){throw r instanceof q||r instanceof B?r:new q(t,e,r instanceof Error?r.message:String(r),r)}}i(J,"stage");async function aa(t,e){let n=t.pages()[0];await(n===void 0?await t.newPage():n).goto(e.entryUrl,{waitUntil:"load"})}i(aa,"navigateToEntry");import{setTimeout as ka}from"node:timers/promises";function me(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(me,"computeBackoffDelayMs");function pe(t){let e=sa(t.error);return e!==null?{retry:!1,reason:e}:{retry:!0,delayMs:me(t.attempt,t.rng)}}i(pe,"decideGatewayRetry");function sa(t){if(t instanceof y)return"terminal_signal";if(t instanceof M)return"contract_breach";if(t instanceof b)return"semantic_refusal";if(t.operation==="claim"||t.operation==="token_rotate")return"one_shot_operation";if(t instanceof G||t instanceof oe)return null;if(t instanceof _)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(sa,"classifyFailure");import{unlinkSync as _a}from"node:fs";import{readFileSync as la,writeFileSync as da,renameSync as ca,mkdirSync as ua,existsSync as ma,chmodSync as pa,fchmodSync as ha,openSync as vr,fsyncSync as Sr,closeSync as Rr,unlinkSync as ga}from"node:fs";import{join as Tr}from"node:path";var nt=u("state-file");function rt(t){return Tr(t,"runner-state.json")}i(rt,"stateFilePath");function Mt(t){return Tr(t,"runner-state.json.tmp")}i(Mt,"stateTmpPath");function Ar(t){let e=rt(t);if(!ma(e))return nt.debug("No state file found \u2014 first start",{filePath:e}),null;let n;try{n=la(e,"utf-8")}catch(a){throw new Error(`[state-file] Failed to read state file at ${e}: ${String(a)}. If the file is corrupted, remove it and re-register with PROGON_RUNNER_TOKEN set.`)}let r;try{r=JSON.parse(n)}catch(a){throw new Error(`[state-file] State file at ${e} contains invalid JSON: ${String(a)}. Remove the file and re-register with PROGON_RUNNER_TOKEN set.`)}let o=wa(r,e);return nt.info("State file loaded",{agentId:o.agentId,protocolVersion:o.protocolVersion}),o}i(Ar,"readState");function Ir(t,e){ua(t,{recursive:!0,mode:448}),pa(t,448);let n=rt(t),r=Mt(t),o=JSON.stringify(e,null,2);try{let a=vr(r,"w",384);try{ha(a,384),da(a,o,{encoding:"utf-8"}),Sr(a)}finally{Rr(a)}ca(r,n),ya(t)}catch(a){throw fa(r),new Error(`[state-file] Failed to write state file at ${n}: ${String(a)}. Check permissions on stateDir ${t}.`)}nt.info("State file written",{agentId:e.agentId,filePath:n})}i(Ir,"writeState");function fa(t){try{ga(t)}catch(e){if(e.code==="ENOENT")return;nt.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(fa,"removeStateTmp");function ya(t){let e=vr(t,"r");try{Sr(e)}finally{Rr(e)}}i(ya,"fsyncDirectory");function wa(t,e){if(typeof t!="object"||t===null||Array.isArray(t)){let d=t===null?"null":Array.isArray(t)?"array":typeof t;throw new Error(`[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 Error(`[state-file] State file ${e} is missing or has invalid 'agentId' (expected non-empty string).`);bn(r);let o=n.agentToken;if(typeof o!="string"||o==="")throw new Error(`[state-file] State file ${e} is missing or has invalid 'agentToken' (expected non-empty string).`);Tt(o);let a=n.protocolVersion;if(typeof a!="number"||!Number.isInteger(a))throw new Error(`[state-file] State file ${e} is missing or has invalid 'protocolVersion' (expected integer).`);kn(a);let s=n.serverUrl;if(typeof s!="string"||s==="")throw new Error(`[state-file] State file ${e} is missing or has invalid 'serverUrl' (expected non-empty string).`);try{Rt(s)}catch(d){throw new Error(`[state-file] State file ${e} has an invalid 'serverUrl': ${String(d)}`)}return{agentId:r,agentToken:o,protocolVersion:a,serverUrl:s,tokenRotatedAt:Ea(n,e)}}i(wa,"validateState");function Ea(t,e){let n=t.tokenRotatedAt;if(n==null)return null;if(typeof n!="string"||n==="")throw new Error(`[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(Ea,"readTokenRotatedAt");var xr=u("token-store");function Z(t){return Ar(t)}i(Z,"loadAgentIdentity");function he(t,e){Ir(t,e)}i(he,"saveAgentIdentity");function Pr(t){let e=rt(t),n=Mt(t),r=Or(n,"temporary state file"),o=Or(e,"identity");if(!o&&!r){xr.info("Agent identity wipe: no state file to remove",{filePath:e,tmpPath:n});return}xr.warn("Agent identity wiped \u2014 this agent was revoked and must be re-enrolled",{filePath:e,tmpPath:n,removedState:o,removedTmp:r})}i(Pr,"wipeAgentIdentity");function Or(t,e){try{return _a(t),!0}catch(n){if(ba(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(Or,"removeCredentialFile");function ba(t){return t.code==="ENOENT"}i(ba,"isFileNotFound");var V=u("supervisor-identity");async function ge(t){let{config:e}=t;if(e.initialToken!==void 0)return va(e,e.initialToken);let n=Z(e.stateDir);if(n!==null)return Aa(n.serverUrl,e.serverUrl),V.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 Ra(t,e.enrollmentCode);throw new Error(`[progon-agent] This machine has no agent identity, so the daemon cannot start.
|
|
17
|
+
There is no state file in ${e.stateDir} and neither PROGON_AGENT_TOKEN nor PROGON_AGENT_ENROLL_CODE is set.
|
|
18
|
+
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(ge,"resolveAgentIdentity");function va(t,e){return t.enrollmentCode!==void 0&&V.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)"),V.info("Agent identity taken from PROGON_AGENT_TOKEN",{stateFile:Sa(t.stateDir)}),{agentToken:e,agentId:null,pollWaitSec:void 0,source:"env_token"}}i(va,"identityFromEnvToken");function Sa(t){try{return Z(t)===null?"absent":"present"}catch(e){return V.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(Sa,"describeStateFile");async function Ra(t,e){let{config:n,machine:r}=t;V.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 je(t.fetchImpl===void 0?{serverUrl:n.serverUrl,machine:r}:{serverUrl:n.serverUrl,machine:r,fetchImpl:t.fetchImpl}),a=await Ta(o,e,t.rng);return he(n.stateDir,{agentId:a.agentId,agentToken:a.agentToken,protocolVersion:a.protocolVersion,serverUrl:n.serverUrl,tokenRotatedAt:null}),V.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(Ra,"enrollThisMachine");var Nr=900*1e3;async function Ta(t,e,n){let r=Date.now()+Nr;for(let o=0;;o+=1)try{return await t.enroll(e)}catch(a){if(!(a instanceof k))throw a;let s=pe({attempt:o,error:a,rng:n});if(!s.retry)throw V.warn("Enrollment refused definitively \u2014 not retrying",{attempt:o,reason:s.reason,err:a.message}),a;if(Date.now()+s.delayMs>=r)throw new Error(`[progon-agent] Enrollment kept failing for the ${Nr/6e4} minutes an enrollment code stays valid (CONTRACT-la \xA75.1), so this code can no longer be redeemed. Last failure: ${a.message}
|
|
19
|
+
Mint a fresh code in Progon (Settings \u2192 Agents) once the server is reachable, then run 'progon-agent enroll <code>' again.`,{cause:a});V.warn("Enrollment attempt failed \u2014 backing off and retrying",{attempt:o,retryInMs:s.delayMs,err:a.message}),await ka(s.delayMs)}}i(Ta,"enrollWithRetry");function Aa(t,e){if(new URL(t).href!==new URL(e).href)throw new Error(`[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.
|
|
20
|
+
Either point PROGON_SERVER_URL back at the enrolled server, or enroll this machine against the new one (remove the state file and start once with PROGON_AGENT_ENROLL_CODE=<code>).`)}i(Aa,"assertServerMatchesEnrollment");import{createRequire as Ia}from"node:module";import{hostname as xa}from"node:os";var Cr=["darwin","linux","win32"],Dr=["x64","arm64"];function Oa(t){return Cr.includes(t)}i(Oa,"isSupportedPlatform");function Pa(t){return Dr.includes(t)}i(Pa,"isSupportedArch");function Na(){let e=Ia(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(Na,"readAgentVersion");function fe(){let t=process.platform;if(!Oa(t))throw new Error(`[supervisor] Unsupported platform ${JSON.stringify(t)}. The local agent runs on ${Cr.join(", ")} (CONTRACT-la \xA75.1, \xA710.3).`);let e=process.arch;if(!Pa(e))throw new Error(`[supervisor] Unsupported CPU architecture ${JSON.stringify(e)}. The local agent runs on ${Dr.join(", ")} (CONTRACT-la \xA75.1).`);let n=xa();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:Na()}}i(fe,"describeAgentMachine");var Lr=i(()=>{},"noop"),ot=class{static{i(this,"ActionQueue")}#e=Promise.resolve();run(e){let n=this.#e.then(e,e);return this.#e=n.then(Lr,Lr),n}};var Gr=u("supervisor-deadline"),Te=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 it(t){let e=t.work(),n=!1;e.then(()=>{n&&Gr.warn("Abandoned work settled successfully after its deadline had passed",{operation:t.operation,timeoutMs:t.timeoutMs})},a=>{n&&Gr.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 Te(t.operation,t.timeoutMs))},t.timeoutMs)});try{return await Promise.race([e,o])}finally{r!==void 0&&clearTimeout(r)}}i(it,"withDeadline");function at(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(at,"sleep");var H=u("fail-reporter"),st=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){H.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&&H.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,H.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&&(H.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});H.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 y)throw n;if(n instanceof b)throw H.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 k))throw n;let r=pe({attempt:e.attempt,error:n});if(!r.retry){H.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},H.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 lt=120,Mr=lt*1e3,$t=3e4,ye=3,Ut=45*1e3,Ft="agent shutdown";var U=u("launch-run");async function $r(t){let e=await Da(t);return e.kind!=="claimed"?e:Ga(t,e.payload)}i($r,"claimAndLaunch");async function Da(t){try{let e=await t.client.claimRun(t.runId);return U.info("Run claimed",La(e)),{kind:"claimed",payload:e}}catch(e){if(e instanceof y)throw e;if(e instanceof b)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 ie||e instanceof W)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(Da,"claimRun");function La(t){return"kind"in t?t.kind==="make_auto"?{kind:t.kind,runId:t.runId,projectId:t.command.projectId,scenarios:t.command.scenarios.length,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(La,"describeClaim");async function Ga(t,e){try{await it({operation:`startRun(${e.runId})`,timeoutMs:Mr,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",...Ma(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(Ga,"launchClaimedRun");function Ma(t,e){return e instanceof q?(U.error("Launch failed",{runId:t,stage:e.stage,failReason:e.failReason,err:e.message}),{reason:e.failReason,message:`launch failed at stage ${e.stage}`}):e instanceof Te?(U.error("Launch exceeded the agent-side launch deadline \u2014 disposing and failing",{runId:t,launchTimeoutSec:lt,err:e.message}),{reason:"launch_error",message:`launch did not complete within ${lt}s`}):e instanceof B?(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(Ma,"describeLaunchFailure");var we=u("run-monitor");function $a(t,e){let n=Date.now();return e.ok?e.tabs.some(o=>o.playback!==null&&o.playback.runId===t)?{healthy:!0}:Ua(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 (${Fa(e.tabs)}; ${ja(e.agentJob,n)})`}:{healthy:!1,reason:e.reason,detail:e.detail}}i($a,"judgeProbe");function Ua(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<=Ut}i(Ua,"isJobPulseStanding");function Fa(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(Fa,"describeTabs");function ja(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(Ut)}ms)`}i(ja,"describeJobMarker");var dt=class{static{i(this,"RunMonitor")}#e;#t;#n=null;#r=null;#a=0;#o=!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());we.info("Monitoring launched run",{runId:this.#e.runId,deadlineAt:this.#e.deadlineAt,deadlineInMs:e,probeIntervalMs:$t,probeStrikeLimit:ye}),this.#n=setInterval(()=>{this.#i()},$t),this.#n.unref(),this.#r=setTimeout(()=>{this.#o||(this.stop(),we.error("Run reached its server-authored deadline",{runId:this.#e.runId,deadlineAt:this.#e.deadlineAt}),this.#e.onDeadline())},e),this.#r.unref()}stop(){this.#o=!0,this.#n!==null&&(clearInterval(this.#n),this.#n=null),this.#r!==null&&(clearTimeout(this.#r),this.#r=null)}async#i(){if(this.#o)return;let e=$a(this.#e.runId,await this.#s());if(this.#o)return;if(e.healthy){this.#a>0&&we.info("Liveness probe recovered",{runId:this.#e.runId,clearedStrikes:this.#a}),this.#a=0;return}this.#a+=1;let n=`${e.reason}: ${e.detail}`;we.warn("Liveness probe failed",{runId:this.#e.runId,strike:this.#a,strikeLimit:ye,reason:e.reason,detail:e.detail}),!(this.#a<ye)&&(this.stop(),we.error("Liveness probe failed the strike limit \u2014 the browser is gone",{runId:this.#e.runId,strikes:ye,detail:n}),this.#e.onBrowserGone(`${ye} consecutive liveness probes failed (${n})`))}async#s(){try{return await this.#e.probe()}catch(e){let n=e instanceof Error?e.message:String(e);return we.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 D=u("instance-reconciler");function qa(t){let e=i(()=>{},"markSettled"),n=new Promise(r=>{e=r});return{runId:t,cancelledBy:null,settled:n,markSettled:e}}i(qa,"createPendingLaunch");var ct=class{static{i(this,"InstanceReconciler")}#e;#t;#n;#r;#a=new Set;#o=null;#i=null;#s=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)),D.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.#i;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.#s===n.runId){D.info("Not re-claiming a run this agent has already attempted (one-shot CAS)",{runId:n.runId});return}this.#s=n.runId,this.#c(n.runId);return}await this.#p(n.runId,n.phase)}}async cancelLaunchAndSettle(e){let n=this.#i;return n===null?null:(D.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){D.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);D.info("Instance disposed",{runId:e,trigger:n,disposeOutcome:r.outcome,instanceReleased:r.instanceReleased,kill:r.kill,durationMs:r.durationMs})}catch(r){D.error("Dispose finished with a failed cleanup step",{runId:e,trigger:n,err:r instanceof Error?r.message:String(r)})}}stopMonitor(){this.#o?.stop(),this.#o=null}#c(e){let n=qa(e);this.#i=n,this.#l(n)}async#l(e){try{let n=await this.#u(e.runId);await this.#r(()=>this.#m(e,n))}finally{e.markSettled()}}async#u(e){try{return{kind:"outcome",outcome:await $r({client:this.#e,runtime:this.#t,runId:e})}}catch(n){return{kind:"thrown",error:n}}}async#m(e,n){if(this.#i===e&&(this.#i=null),n.kind==="thrown")throw n.error;let r=n.outcome;switch(r.kind){case"launched":if(e.cancelledBy!==null){D.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){D.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){D.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.#o=new dt({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.#o.start()}async#p(e,n){let r=this.#a.has(e),o=r?"browser_gone":"launch_error";D.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 Ur={revoked:"agent_revoked",reenroll_required:"agent_superseded",credential_unusable:"agent_superseded",fatal:"shutdown",stopped:"shutdown"};var A=u("token-rotation"),Fr=1440*60*1e3,ut=class{static{i(this,"TokenRotationCoordinator")}#e;#t;#n;#r=null;#a=!1;#o=!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.#i(e);this.#r=r;try{return await r}finally{this.#r=null}}get canDiagnoseFromTheWire(){return this.#n!=="env_token"}async diagnoseSuperseded(e){if(this.#n==="env_token")return A.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 b)return"reenroll_required";if(n instanceof y)throw n;if(n instanceof k)return A.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#i(e){if(this.#n==="env_token")return this.#a||(this.#a=!0,A.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.#o)return{kind:"superseded_in_grace"};let n=this.#p();if(n.kind!=="identity")return this.#g(n);let r=n.identity,o=await this.#s(e);return o.kind!=="status"?o.outcome:o.value.rotationDue?await this.#l(r,o.value.tokenRotatedAt,e):this.#c(r,o.value.tokenRotatedAt)}async#s(e){try{return{kind:"status",value:e===void 0?await this.#e.getTokenRotationStatus():await this.#e.getTokenRotationStatus({signal:e})}}catch(n){if(n instanceof b)return A.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 y)throw n;if(n instanceof k)return A.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}}#c(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.#o=!0,A.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 y)throw s;if(s instanceof b)return await this.#u(r);if(s instanceof k)return A.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"),A.info("Agent token rotated"),{kind:"rotated"})}async#u(e){return await this.diagnoseSuperseded(e)==="reenroll_required"?{kind:"reenroll_required"}:(this.#o=!0,A.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.#s(void 0);return n.kind!=="status"?n.outcome:n.value.tokenRotatedAt===e?(A.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.#o=!0,A.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.#s(void 0);return e.kind==="status"?{kind:"observed",tokenRotatedAt:e.value.tokenRotatedAt}:e.outcome.kind==="reenroll_required"?{kind:"reenroll_required"}:(A.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 he(this.#t,e),!0}catch(r){return A.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=Z(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"?(A.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"}):(A.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"),jt=i(()=>Promise.resolve(),"noVerdictOwed"),mt=class{static{i(this,"RunSupervisor")}#e;#t;#n;#r=new ot;#a;#o;#i=null;#s=0;#c=!1;#l=new AbortController;#u=null;#m=!1;#h=!1;#d;#p=null;#g=null;constructor(e){this.#e=e.client,this.#a=e.stateDir,this.#o=e.pollWaitSec,this.#d=e.tokenRotation,this.#t=new st(e.client),this.#l.signal.addEventListener("abort",()=>this.#P(),{once:!0});let n=e.createRuntime(r=>{this.#T(()=>this.#n.handleInstanceLost(r))});this.#n=new ct({client:e.client,runtime:n,reporter:this.#t,detach:i(r=>this.#T(r),"detach")})}async run(){await this.#r.run(()=>this.#n.sweepAtStartup());let e=await this.#x();if(e!==null)return e;for(this.#v(),await this.#f();!this.#c;){let n=this.#u;if(n!==null)return await this.#E(n),"revoked";if(this.#m)return await this.#_(),"reenroll_required";if(this.#h)return await this.#R(),"credential_unusable";try{await this.#r.run(()=>this.#t.retryPending());let r=await this.#N();this.#s=0,await this.#r.run(()=>this.#n.reconcile(r))}catch(r){if(r instanceof y)return await this.#E(r),"revoked";if(r instanceof b&&await this.#S(r))return await this.#_(),"reenroll_required";if(this.#c)break;if(this.#u!==null||this.#m||this.#h)continue;let o=await this.#D(r);if(o!==null)return o==="credential_unusable"?await this.#R():await this.#C(),o}}return"stopped"}async#f(){try{await this.#e.declareCapabilities({signal:this.#l.signal})}catch(e){if(e instanceof y||e instanceof b||!(e instanceof k))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.#I(e);return this.#g=r,r}async#I(e){I.info("Shutting down",{cause:e}),await this.#y(e==="fatal"?"fatal":"stopped",n=>this.#k(n))}async#y(e,n){this.#c=!0,this.#i?.abort(),this.#l.abort();let r=Ur[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#k(e){let{activeRunId:n,launchingRunId:r}=e;if(n!==null){await this.#b(()=>this.#t.report({runId:n,reason:"browser_gone",message:Ft}));return}if(r!==null){await this.#b(()=>this.#t.report({runId:r,reason:"browser_gone",message:Ft}));return}await this.#b(()=>this.#t.retryPending())}async#x(){try{if((await this.#d.runCycle(this.#l.signal)).kind!=="reenroll_required")return null}catch(e){if(e instanceof y)return await this.#E(e),"revoked";throw e}return await this.#_(),"reenroll_required"}#v(){if(this.#c||this.#l.signal.aborted)return;let e=setTimeout(()=>{this.#p=null,this.#O().finally(()=>{this.#v()})},Fr);e.unref(),this.#p=e}async#O(){try{if((await this.#d.runCycle(this.#l.signal)).kind!=="reenroll_required")return;this.#m=!0,this.#i?.abort()}catch(e){await this.#A(e)}}#P(){this.#p!==null&&(clearTimeout(this.#p),this.#p=null)}async#S(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 y)return this.#u=n,!1;throw n}}async#N(){let e=new AbortController;this.#i=e;try{return await this.#e.pollDesiredState({waitSec:this.#o,signal:e.signal})}finally{this.#i=null}}async#w(){await this.#d.settle(),Pr(this.#a)}async#E(e){I.error("This agent has been revoked \u2014 disposing, wiping the credential and stopping",{signal:e.signal}),await this.#y("revoked",jt),await this.#w()}async#R(){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",jt)}async#C(){await this.#y("fatal",e=>this.#k(e))}async#_(){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",jt),await this.#w()}async#D(e){if(!(e instanceof k))throw e;let n=this.#L(e);return n.kind==="exit"?n.exit:(this.#s+=1,await at(n.delayMs,this.#l.signal),null)}#L(e){if(e instanceof b){if(!this.#d.canDiagnoseFromTheWire)return{kind:"exit",exit:"credential_unusable"};let r=me(this.#s);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.#s,retryInMs:r}),{kind:"retry",delayMs:r}}let n=pe({attempt:this.#s,error:e});return n.retry?(I.warn("Desired-state poll failed \u2014 backing off",{attempt:this.#s,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"})}#T(e){return this.#r.run(e).catch(n=>this.#A(n))}async#A(e){if(e instanceof y){this.#u=e,this.#i?.abort();return}if(e instanceof b){try{await this.#S(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.#u!==null)&&this.#i?.abort();return}I.error("A background supervisor action failed",{err:e instanceof Error?e.message:String(e)})}async#b(e){try{await e()}catch(n){if(n instanceof b){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 y){await this.#w(),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 jr=u("supervisor-boot");async function qr(){let t=ne();jr.info("Config loaded",{serverUrlOrigin:new URL(t.serverUrl).origin,stateDir:t.stateDir,headfulOverride:t.headfulOverride});let e=fe(),n=await ge({config:t,machine:e});jr.info("Agent identity resolved",{source:n.source,agentId:n.agentId,hostname:e.hostname,platform:e.platform,arch:e.arch,agentVersion:e.agentVersion});let r=Dn({overridePath:t.extensionDistOverride,stateDir:t.stateDir,agentId:n.agentId});await Ce({stdio:"pipe"});let o=new qe({serverUrl:t.serverUrl,agentToken:n.agentToken}),a=new ut({client:o,stateDir:t.stateDir,identitySource:n.source});return new mt({client:o,stateDir:t.stateDir,pollWaitSec:n.pollWaitSec,tokenRotation:a,createRuntime:i(s=>new tt({stateDir:t.stateDir,extensionDist:r,headfulOverride:t.headfulOverride,onInstanceLost:s}),"createRuntime")})}i(qr,"bootRunSupervisor");import{createHash as za,randomBytes as Za}from"node:crypto";import{z as T}from"zod";var Br=T.object({requestId:T.uuid(),mode:T.literal("device"),userCode:T.string().min(1),verificationUrl:T.url(),expiresAt:T.iso.datetime({offset:!0}),pollIntervalSec:T.number().int().positive()}),Jr=T.object({status:T.literal("authorization_pending"),expiresAt:T.iso.datetime({offset:!0}),pollIntervalSec:T.number().int().positive()}),Ba=T.object({companyName:T.string(),approvedByEmail:T.string(),approvedAt:T.string()}),Vr=T.object({credential:Pe,approval:Ba});var Hr=u("gateway-enrollment-request"),pt=class{static{i(this,"GatewayEnrollmentRequestClient")}serverUrl;machine;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.machine=e.machine,this.fetchImpl=e.fetchImpl??Be}async create(e){let n=await Y({operation:"enrollment_request_create",method:"POST",url:N(this.serverUrl,"/enrollment-requests"),agentToken:null,body:{deviceSecretHash:e,protocolVersion:1,...this.machine},signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:$n}),r=P("enrollment_request_create",Br.safeParse(n));return Hr.info("Enrollment request opened",{requestId:r.requestId,mode:r.mode,pollIntervalSec:r.pollIntervalSec,expiresAt:r.expiresAt}),r}async poll(e){let n=await Y({operation:"enrollment_request_poll",method:"POST",url:N(this.serverUrl,"/enrollment-requests/poll"),agentToken:null,body:{deviceSecret:e},signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:Un}),r=typeof n=="object"&&n!==null?n:null;if(r!==null&&"credential"in r){let o=P("enrollment_request_poll",Vr.safeParse(n));return Hr.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",Jr.safeParse(n));return{kind:"pending",expiresAt:o.expiresAt,pollIntervalSec:o.pollIntervalSec}}throw new M("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 Y({operation:"enrollment_request_cancel",method:"POST",url:N(this.serverUrl,"/enrollment-requests/cancel"),agentToken:null,body:{deviceSecret:e},signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:Fn})}};import{spawn as Ja}from"node:child_process";var Ae=u("browser-open");function ht(t){return t!==void 0&&t!==""}i(ht,"isSet");function Va(t,e){return!(ht(t.SSH_CONNECTION)||ht(t.SSH_TTY)||e==="linux"&&!ht(t.DISPLAY)&&!ht(t.WAYLAND_DISPLAY))}i(Va,"shouldAttemptBrowserOpen");var Ha=/[&|^<>"'` ]/;function Ka(t){let e;try{e=new URL(t)}catch{return!1}return e.protocol!=="http:"&&e.protocol!=="https:"||t!==e.href?!1:!Ha.test(t)}i(Ka,"isSpawnSafeUrl");function Wa(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(Wa,"browserOpenCommand");function Kr(t,e,n){if(!Va(e,n)){Ae.debug("Not opening a browser: this host has no desktop to open one on",{platform:n});return}if(!Ka(t)){Ae.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=Wa(t,n);if(r===null){Ae.debug("Not opening a browser: no opener is defined for this platform",{platform:n});return}try{let o=Ja(r.command,[...r.args],{detached:!0,stdio:"ignore"});o.on("error",a=>{Ae.debug("Could not start the browser; the approval URL was printed instead",{platform:n,command:r.command,err:a.message})}),o.unref()}catch(o){Ae.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(Kr,"openVerificationUrl");var Ya=30,Xa=5;function Wr(t){return{intervalSec:t.pollIntervalSec,deadlineMs:t.timeoutSec===null?t.expiresAtMs:Math.min(t.expiresAtMs,t.nowMs+t.timeoutSec*1e3)}}i(Wr,"initialPollSchedule");function gt(t,e){if(e.kind==="pending")return{state:t,delayMs:t.intervalSec*1e3};if(e.kind==="slow_down"){let r=t.intervalSec+Xa,o=e.retryAfterSec!==null&&e.retryAfterSec>r?e.retryAfterSec:r,a=Math.min(o,Ya);return{state:{intervalSec:a,deadlineMs:t.deadlineMs},delayMs:a*1e3}}let n=me(e.attempt,e.rng);return{state:t,delayMs:Math.max(t.intervalSec*1e3,n)}}i(gt,"nextPollDelayMs");function Yr(t,e){return e>=t.deadlineMs}i(Yr,"isDeadlinePassed");function Xr(t,e,n){return Math.max(0,Math.min(e,t.deadlineMs-n))}i(Xr,"clampDelayToDeadline");var Ee=u("device-enrollment"),Qa=24,es=2e3,qt=0,Ie=1,Zr=130,ts="This machine is already enrolled. Start the daemon with: progon-agent start",ns="Enrollment was denied in the browser. Nothing was created on this machine.",rs="Cancelled. Nothing was saved on this machine.",os="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 zr(t){return`Enrollment request expired. Run: progon-agent enroll --server ${t}`}i(zr,"expiredLine");function is(t,e){return`Timed out after ${t}s waiting for approval. The request is still open \u2014 approve at: ${e}`}i(is,"timedOutLine");function as(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(as,"alreadyCompletedLine");function ss(t){return`Enrollment request is no longer valid. Run: progon-agent enroll --server ${t}`}i(ss,"noLongerValidLine");async function Qr(t){let e=t.env??process.env;t.serverUrl!==void 0&&(process.env.PROGON_SERVER_URL=t.serverUrl);let n=ne(),r=fe(),o=e.PROGON_AGENT_ENROLL_CODE;if(o!==void 0&&o!=="")return cs(n,r,t.fetchImpl,t.rng);if(Z(n.stateDir)!==null)return process.stdout.write(`${ts}
|
|
21
|
+
`),qt;let a=Za(Qa).toString("base64url"),s=new pt(t.fetchImpl===void 0?{serverUrl:n.serverUrl,machine:r}:{serverUrl:n.serverUrl,machine:r,fetchImpl:t.fetchImpl}),d=await s.create(ps(a));return us(d),t.openBrowser&&Kr(d.verificationUrl,e,process.platform),ls({client:s,config:n,created:d,deviceSecret:a,timeoutSec:t.timeoutSec,rng:t.rng})}i(Qr,"runDeviceEnrollment");async function ls(t){let{client:e,config:n,created:r,deviceSecret:o,timeoutSec:a,rng:s}=t,d=Date.parse(r.expiresAt),c=Wr({pollIntervalSec:r.pollIntervalSec,expiresAtMs:d,timeoutSec:a,nowMs:Date.now()}),m=c.intervalSec*1e3,f=0,h={signal:null},p=new AbortController,S=i(v=>{h.signal!==null&&(process.stderr.write(`${os}
|
|
22
|
+
`),process.exit(Zr)),h.signal=v,p.abort()},"onSignal");process.on("SIGINT",S),process.on("SIGTERM",S);try{for(;;){if(await at(Xr(c,m,Date.now()),p.signal),h.signal!==null)return await ds(e,o,h.signal);if(Yr(c,Date.now()))return a!==null&&c.deadlineMs<d?process.stdout.write(`${is(a,r.verificationUrl)}
|
|
23
|
+
`):process.stdout.write(`${zr(n.serverUrl)}
|
|
24
|
+
`),Ie;let v;try{v=await e.poll(o)}catch(R){if(R instanceof se)return process.stdout.write(`${ns}
|
|
25
|
+
`),Ie;if(R instanceof le)return process.stdout.write(`${zr(n.serverUrl)}
|
|
26
|
+
`),Ie;if(R instanceof de)return Ee.warn("The enrollment request was already completed on the server; no credential reached this machine and nothing was saved",{requestId:r.requestId,errorCode:R.errorCode,status:R.status}),process.stdout.write(`${as(n.serverUrl)}
|
|
27
|
+
`),Ie;if(R instanceof ce)return Ee.warn("The server no longer recognises this enrollment request",{requestId:r.requestId,errorCode:R.errorCode,status:R.status}),process.stdout.write(`${ss(n.serverUrl)}
|
|
28
|
+
`),Ie;if(R instanceof ae){let _e=gt(c,{kind:"slow_down",retryAfterSec:R.retryAfterSec});c=_e.state,m=_e.delayMs,Ee.warn("The server asked this machine to poll more slowly",{intervalSec:c.intervalSec,retryAfterSec:R.retryAfterSec});continue}if(R instanceof G||R instanceof _&&R.status>=500){let _e=gt(c,{kind:"transport_error",attempt:f,rng:s});f+=1,c=_e.state,m=_e.delayMs,Ee.warn("The enrollment poll failed; retrying until the request expires",{attempt:f,delayMs:m,err:R.message});continue}throw R}if(v.kind==="enrolled")return he(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
|
|
29
|
+
`),qt;f=0;let xe=gt(c,{kind:"pending"});c=xe.state,m=xe.delayMs}}finally{process.off("SIGINT",S),process.off("SIGTERM",S)}}i(ls,"waitForApproval");async function ds(t,e,n){try{await it({operation:"device enrollment cancel",timeoutMs:es,work:i(()=>t.cancel(e),"work")})}catch(r){Ee.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(`${rs}
|
|
30
|
+
`),Zr}i(ds,"cancelRequest");async function cs(t,e,n,r){let o=await ge({config:t,machine:e,fetchImpl:n,rng:r});if(o.source!=="enrollment")throw new Error(`[progon-agent] The enrollment code was not redeemed: this machine already has a credential (source: ${o.source}), which takes precedence.
|
|
31
|
+
To enroll it as a NEW agent, unset PROGON_AGENT_TOKEN and remove the state file in ${t.stateDir}, then run 'progon-agent enroll' again.
|
|
32
|
+
The code itself was not spent and stays valid until it expires.`);return Ee.info("This machine is enrolled \u2014 start the daemon with: progon-agent start",{agentId:o.agentId,hostname:e.hostname,stateDir:t.stateDir}),qt}i(cs,"redeemLegacyEnrollmentCode");function us(t){process.stdout.write(`Enrollment requested for this machine.
|
|
33
|
+
Confirmation code: ${t.userCode}
|
|
34
|
+
Approve at: ${t.verificationUrl}
|
|
35
|
+
Waiting for approval (expires in ${ms(t.expiresAt)})...
|
|
36
|
+
`)}i(us,"printRequestOpened");function ms(t){let e=Date.parse(t)-Date.now();return`${Math.ceil(e/6e4)}m`}i(ms,"describeExpiry");function ps(t){return za("sha256").update(t,"utf8").digest("hex")}i(ps,"sha256Hex");var ft=u("cli"),eo=`progon-agent \u2014 the Progon local agent (CONTRACT-la \xA78)
|
|
37
|
+
|
|
38
|
+
Usage:
|
|
39
|
+
progon-agent enroll <code> [--server <url>] Redeem a one-shot enrollment code (\xA75.1) and
|
|
40
|
+
persist this machine's agent credential.
|
|
41
|
+
progon-agent enroll [--server <url>] Enroll WITHOUT a code: open a request, and a
|
|
42
|
+
[--no-open] [--timeout s] person approves this machine in their browser
|
|
43
|
+
under their own Progon session. The command
|
|
44
|
+
prints a confirmation code and an approval
|
|
45
|
+
URL, waits, then persists the credential.
|
|
46
|
+
progon-agent start Run the daemon: reconcile the desired state
|
|
47
|
+
and execute the runs this agent is given.
|
|
48
|
+
progon-agent install-browser Download this agent's Chromium ahead of time
|
|
49
|
+
(\xA715 A31). Optional: 'start' provisions it
|
|
50
|
+
automatically, and re-running is a fast
|
|
51
|
+
offline no-op once it is installed.
|
|
52
|
+
|
|
53
|
+
Options for 'enroll' without a code:
|
|
54
|
+
--no-open do not try to open a browser. Implied on SSH sessions and on
|
|
55
|
+
headless Linux; the approval URL is always printed either way.
|
|
56
|
+
--timeout <seconds> stop waiting after this many seconds (1-3600). Omitted: wait
|
|
57
|
+
until the request expires on the server (10 minutes).
|
|
58
|
+
|
|
59
|
+
Which credential 'enroll' uses, highest precedence first:
|
|
60
|
+
1. the positional <code> -> the one-shot code path (\xA75.1).
|
|
61
|
+
2. PROGON_AGENT_ENROLL_CODE -> the same path, with the code from the environment.
|
|
62
|
+
3. neither -> browser approval (the device flow above).
|
|
63
|
+
|
|
64
|
+
Exit codes: 0 enrolled, or already enrolled; 1 the enrollment did not happen \u2014 denied,
|
|
65
|
+
expired, --timeout exhausted, already completed from another machine, no longer valid, or the
|
|
66
|
+
network still failing when the deadline passed; 2 the command line was wrong; 130 interrupted
|
|
67
|
+
with Ctrl-C \u2014 the first Ctrl-C withdraws the pending request before exiting, a second one
|
|
68
|
+
exits at once and leaves the request to expire on its own.
|
|
69
|
+
|
|
70
|
+
Environment (see CONTRACT-la \xA78 for the full list):
|
|
71
|
+
PROGON_SERVER_URL required \u2014 base URL of the Progon backend.
|
|
72
|
+
PROGON_AGENT_EXTENSION_DIST optional \u2014 absolute path of an already agent-mode qa-extension
|
|
73
|
+
dist, overriding the one bundled in this package (dev/E2E).
|
|
74
|
+
Required by 'start' ONLY on the PROGON_AGENT_TOKEN path: that
|
|
75
|
+
credential carries no agentId, and agent-manifest.json \u2014 the
|
|
76
|
+
file that takes the extension out of its inert state \u2014 must
|
|
77
|
+
name one (\xA71 D-C, \xA715 A30.1).
|
|
78
|
+
PROGON_AGENT_TOKEN optional \u2014 an existing credential, takes precedence over the
|
|
79
|
+
state file and over enrollment.
|
|
80
|
+
PROGON_AGENT_HEADFUL optional \u2014 show the browser on this machine's desktop.`;function fs(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"?ws(n):{kind:"usage",reason:`unknown command '${e}'`}}i(fs,"parseCliArgs");function ys(t){return t.startsWith("-")&&t.length<32}i(ys,"isOptionInCodeSlot");function ws(t){let[e,...n]=t;if(e===void 0||ys(e))return Es(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(ws,"parseEnroll");var to=1,no=3600;function Es(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<to||d>no)return{kind:"usage",reason:`'--timeout' must be between ${to} and ${no} 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(Es,"parseEnrollDevice");async function _s(t){let e=fs(t);switch(e.kind){case"usage":return e.reason===null?(process.stdout.write(`${eo}
|
|
81
|
+
`),0):(process.stderr.write(`progon-agent: ${e.reason}
|
|
82
|
+
|
|
83
|
+
${eo}
|
|
84
|
+
`),2);case"enroll":return ks(e.code,e.serverUrl);case"enroll-device":return Qr({serverUrl:e.serverUrl,openBrowser:e.openBrowser,timeoutSec:e.timeoutSec});case"install-browser":return bs();case"start":return vs()}}i(_s,"runAgentCli");async function bs(){return await Ce({stdio:"inherit"}),0}i(bs,"installBrowser");async function ks(t,e){process.env.PROGON_AGENT_ENROLL_CODE=t,e!==void 0&&(process.env.PROGON_SERVER_URL=e);let n=ne(),r=fe(),o=await ge({config:n,machine:r});if(o.source!=="enrollment")throw new Error(`[progon-agent] The enrollment code was not redeemed: this machine already has a credential (source: ${o.source}), which takes precedence.
|
|
85
|
+
To enroll it as a NEW agent, unset PROGON_AGENT_TOKEN and remove the state file in ${n.stateDir}, then run 'progon-agent enroll <code>' again.
|
|
86
|
+
The code itself was not spent and stays valid until it expires.`);return ft.info("This machine is enrolled \u2014 start the daemon with: progon-agent start",{agentId:o.agentId,hostname:r.hostname,stateDir:n.stateDir}),0}i(ks,"enrollThisMachine");async function vs(){Rn(),ft.info("progon-agent starting");let t=await qr();return Tn(async n=>{await t.shutdown(n)}),await t.run()==="revoked"?(ft.error("progon-agent stopped: this agent was revoked and its credential has been wiped. Create a new enrollment code in Progon (Settings \u2192 Agents) and run 'progon-agent enroll <code>' to enroll this machine again."),1):(ft.info("progon-agent stopped"),0)}i(vs,"startDaemon");var ro=process.argv[1];ro!==void 0&&import.meta.url===gs(hs(ro)).href&&_s(process.argv.slice(2)).then(t=>{process.exit(t)}).catch(t=>{let e=L(t instanceof Error?t.message:String(t)),n=t instanceof Error?t.stack:void 0;process.stderr.write(JSON.stringify({level:"fatal",module:"cli",msg:"progon-agent failed",err:e,stack:n===void 0?void 0:L(n)})+`
|
|
87
|
+
`),process.exit(1)});export{fs as parseCliArgs,_s as runAgentCli};
|