progon-agent 1.1.2 → 1.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -99,11 +99,14 @@ The enrollment dialog in Progon (**Settings → Agents**) hands you the complete
99
99
  machine, install included:
100
100
 
101
101
  ```bash
102
- npm i -g progon-agent && progon-agent enroll <code> --server "https://your-progon-host" && progon-agent start
102
+ npm i -g progon-agent && progon-agent enroll <code> && progon-agent start
103
103
  ```
104
104
 
105
- `--server` is remembered: enrollment persists it next to the credential, so the third command —
106
- and every later `progon-agent start` — needs no environment variable of its own.
105
+ No address is needed: this package was built for one deployment and carries its address
106
+ (`extension-bundle.json`), so `enroll` knows where to go. The dialog may hand you the longer form
107
+ with `--server "https://your-progon-host"` — that still works and still wins over the built-in
108
+ address; it is simply no longer required. Either way the server is persisted next to the
109
+ credential, so every later `progon-agent start` needs nothing of its own.
107
110
 
108
111
  On Windows, run this in PowerShell 7 or cmd — Windows PowerShell 5.1 does not support `&&`;
109
112
  there, run the commands one at a time.
@@ -138,11 +141,12 @@ Enrollment binds this machine to one agent record in your Progon company and giv
138
141
  3. On the agent machine, run:
139
142
 
140
143
  ```bash
141
- progon-agent enroll <code> --server "https://your-progon-host"
144
+ progon-agent enroll <code>
142
145
  ```
143
146
 
144
- `--server` is how `PROGON_SERVER_URL` gets set for this command; omit it only if that variable is
145
- already exported. (On a machine that is already enrolled the server is read from the state file
147
+ `--server "https://your-progon-host"` may be added and takes precedence over everything else; it is
148
+ needed only when this build carries no deployment of its own (a source checkout) or when you mean a
149
+ different one. (On a machine that is already enrolled the server is read from the state file
146
150
  instead — but so is the credential, and the command then refuses the code rather than spending it,
147
151
  because a credential already exists.) The command redeems the code, persists the credential — the
148
152
  server URL with it — and exits: it does not start the daemon, does not download Chromium and does
@@ -249,8 +253,13 @@ Precedence, highest first:
249
253
  1. **`--server <url>`** on the `enroll` command — it sets `PROGON_SERVER_URL` for that one process.
250
254
  2. **`PROGON_SERVER_URL`** in the environment.
251
255
  3. **The enrolled deployment** — the `serverUrl` this machine's state file records. This is why
252
- `progon-agent start` needs no environment after `enroll`: the URL was persisted together with
253
- the credential it belongs to.
256
+ `progon-agent start` needs nothing after `enroll`: the URL was persisted together with the
257
+ credential it belongs to.
258
+ 4. **The deployment this package was built for** — `appUrl` in `extension-bundle.json` inside the
259
+ installed package, the same address the bundled extension is compiled against (see the top of
260
+ this file). This is why a clean machine needs no address at all. A **source checkout has no such
261
+ file** — nothing writes it outside the publish pipeline — so there you must pass `--server` or
262
+ export `PROGON_SERVER_URL`.
254
263
 
255
264
  Two rules complete it:
256
265
 
@@ -261,9 +270,9 @@ Two rules complete it:
261
270
  for recovering from a state file that cannot be read — so on that path the state file is not
262
271
  consulted for the server either, and `PROGON_SERVER_URL` is required.
263
272
 
264
- On a machine that is not enrolled and has no `PROGON_SERVER_URL`, every command that needs a server
265
- says so and names both remedies. `progon-agent install-browser` is the exception that needs neither:
266
- it reads no configuration at all.
273
+ If none of the four names a deployment — a source checkout, not enrolled, nothing exported — every
274
+ command that needs a server says so and names each place it looked. `progon-agent install-browser`
275
+ is the exception that needs none of them: it reads no configuration at all.
267
276
 
268
277
  ### Enrolling one machine into two deployments
269
278
 
@@ -288,8 +297,10 @@ progon-agent start
288
297
  ```
289
298
 
290
299
  Requires an enrolled machine, and nothing else: the server comes from the state file the
291
- enrollment wrote, so no environment variable is needed (set `PROGON_SERVER_URL` and it must match
292
- that enrollment). The daemon boots (config → identity →
300
+ enrollment wrote — and on a machine that has not enrolled, from the deployment this package was
301
+ built for, which is why the error you get there names the missing enrollment rather than a missing
302
+ variable. (Set `PROGON_SERVER_URL` and it must match the enrollment.) The daemon boots
303
+ (config → identity →
293
304
  extension dist → Chromium → gateway), then reconciles the backend's desired state and executes the
294
305
  runs it is given, until you stop it.
295
306
 
@@ -332,18 +343,18 @@ A `401` is _not_ revocation: it backs off and retries, and never wipes anything.
332
343
 
333
344
  ### Runtime
334
345
 
335
- | Variable | Required | Meaning |
336
- | ----------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
337
- | `PROGON_SERVER_URL` | until enrolled | Base URL of the Progon backend. `https://` only, except loopback hosts. Scheme + host + optional path prefix — **no** embedded credentials, **no** query string, **no** fragment (the agent-gateway routes are appended to it). Once this machine is enrolled the URL comes from the state file, and setting this variable to a different deployment makes `start` refuse; it stays **required** alongside `PROGON_AGENT_TOKEN`. See [Which server the daemon uses](#which-server-the-daemon-uses). |
338
- | `PROGON_AGENT_TOKEN` | no | An existing `pgat_` credential. Takes precedence over the state file — this is the rotation mechanism. Must match the `pgat_` wire format; set-but-empty is rejected. |
339
- | `PROGON_AGENT_ENROLL_CODE` | no | One-shot enrollment code, the env form of `progon-agent enroll <code>`. Must be at least 32 characters. |
340
- | `PROGON_RUNNER_STATE_DIR` | no | Overrides the platform state directory. **Required** on platforms other than darwin/linux/win32, and when the user has no home directory. |
341
- | `PROGON_AGENT_EXTENSION_DIST` | no | Absolute path of an already agent-mode qa-extension dist, replacing the bundled one (dev/E2E). Relative paths are rejected. |
342
- | `PROGON_AGENT_HEADFUL` | no | `true`/`false`/`1`/`0`. Shows the browser window on this machine's desktop. Default `false`. It can only turn headful **on** — the server still decides per run. Any other value is rejected. |
343
- | `PROGON_AGENT_ALLOW_INSECURE_HTTPS` | no | `true`/`false`/`1`/`0`. The run browser opens a stand whose certificate it cannot verify — a self-signed internal stand. Default `false`. Any other value is rejected. See [Self-signed stands](#self-signed-stands). |
344
- | `PROGON_AGENT_EXTRA_CA_CERTS` | no | Absolute path to a readable PEM bundle whose authority the **agent's own** connections to the backend trust, on top of the public roots. Refused at startup if the path is relative or the file cannot be read. Does not reach the browser. |
345
- | `PROGON_LOG_LEVEL` | no | pino log level. Default: `info` when `NODE_ENV=production`, `debug` otherwise. |
346
- | `NODE_ENV` | no | Default `production`. Anything else additionally switches logging to human-readable `pino-pretty` output. |
346
+ | Variable | Required | Meaning |
347
+ | ----------------------------------- | -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
348
+ | `PROGON_SERVER_URL` | no (source checkouts: yes) | Base URL of the Progon backend. `https://` only, except loopback hosts. Scheme + host + optional path prefix — **no** embedded credentials, **no** query string, **no** fragment (the agent-gateway routes are appended to it). An installed package does not need it: the URL comes from this machine's enrollment, else from the deployment the package was built for. Setting it to a deployment other than the enrollment makes `start` refuse. Required only on a build that carries no bundled deployment. See [Which server the daemon uses](#which-server-the-daemon-uses). |
349
+ | `PROGON_AGENT_TOKEN` | no | An existing `pgat_` credential. Takes precedence over the state file — this is the rotation mechanism. Must match the `pgat_` wire format; set-but-empty is rejected. |
350
+ | `PROGON_AGENT_ENROLL_CODE` | no | One-shot enrollment code, the env form of `progon-agent enroll <code>`. Must be at least 32 characters. |
351
+ | `PROGON_RUNNER_STATE_DIR` | no | Overrides the platform state directory. **Required** on platforms other than darwin/linux/win32, and when the user has no home directory. |
352
+ | `PROGON_AGENT_EXTENSION_DIST` | no | Absolute path of an already agent-mode qa-extension dist, replacing the bundled one (dev/E2E). Relative paths are rejected. |
353
+ | `PROGON_AGENT_HEADFUL` | no | `true`/`false`/`1`/`0`. Shows the browser window on this machine's desktop. Default `false`. It can only turn headful **on** — the server still decides per run. Any other value is rejected. |
354
+ | `PROGON_AGENT_ALLOW_INSECURE_HTTPS` | no | `true`/`false`/`1`/`0`. The run browser opens a stand whose certificate it cannot verify — a self-signed internal stand. Default `false`. Any other value is rejected. See [Self-signed stands](#self-signed-stands). |
355
+ | `PROGON_AGENT_EXTRA_CA_CERTS` | no | Absolute path to a readable PEM bundle whose authority the **agent's own** connections to the backend trust, on top of the public roots. Refused at startup if the path is relative or the file cannot be read. Does not reach the browser. |
356
+ | `PROGON_LOG_LEVEL` | no | pino log level. Default: `info` when `NODE_ENV=production`, `debug` otherwise. |
357
+ | `NODE_ENV` | no | Default `production`. Anything else additionally switches logging to human-readable `pino-pretty` output. |
347
358
 
348
359
  ### Inherited by the Chromium installer and launch
349
360
 
@@ -407,14 +418,18 @@ is set to something the enrollment does not match. Point it back, unset it — a
407
418
  reads the server from its own state file — or remove the state file and enroll against the new
408
419
  deployment.
409
420
 
410
- **`start` fails saying this machine is not enrolled and `PROGON_SERVER_URL` is not set.** Nothing
411
- on this machine names a deployment: there is no state file in the state directory and no
412
- environment variable. Enroll it —
413
- `progon-agent enroll --server "https://your-progon-host"`. If you enrolled with
414
- `PROGON_RUNNER_STATE_DIR` set, `start` needs the same variable — that is where the credential and
415
- its server are. Exporting `PROGON_SERVER_URL` alone does not fix this for `start`: it names a
416
- server but no agent, so the next step refuses for want of an identity — it is enough only
417
- alongside `PROGON_AGENT_TOKEN`.
421
+ **`start` fails saying the agent does not know which deployment to talk to.** None of the places
422
+ it looks names one: no `PROGON_SERVER_URL`, no state file in the state directory, and no
423
+ `extension-bundle.json` — the last of which means you are running a source checkout, since every
424
+ published package has one. Pass `--server "https://your-progon-host"` to `enroll`, or export
425
+ `PROGON_SERVER_URL`. If you enrolled with `PROGON_RUNNER_STATE_DIR` set, `start` needs the same
426
+ variable — that is where the credential and its server are. Exporting `PROGON_SERVER_URL` alone
427
+ does not make `start` work: it names a server but no agent, so the next step refuses for want of an
428
+ identity — it is enough only alongside `PROGON_AGENT_TOKEN`.
429
+
430
+ **`start` on an installed package says this machine has no agent identity.** The server was found
431
+ (the deployment this package was built for), but the machine has never enrolled. Run
432
+ `progon-agent enroll` — no address needed.
418
433
 
419
434
  **The daemon exits 1 mid-run reporting a revocation.** The agent was revoked server-side and its
420
435
  local credential has been wiped. Mint a new code and re-enroll — see
@@ -1,56 +1,59 @@
1
1
  #!/usr/bin/env node
2
- var So=Object.defineProperty;var o=(t,e)=>So(t,"name",{value:e,configurable:!0});import{realpathSync as Ds}from"node:fs";import{pathToFileURL as Ls}from"node:url";import{z as zt}from"zod";var Ro=/^[a-z_]{1,32}@\d{1,3}$/,Zt=zt.array(zt.string().regex(Ro)).min(1).max(32),Qt=["playback@1"],en="make_auto@1",tn="atlas_crawl@1";import{z as g}from"zod";var Q=/^pgat_[0-9A-Za-z]{43}$/;var Se="agent:command",Ce="agent:command-ack",bt="agent:active-job";import{z as c}from"zod";import{z as w}from"zod";var ko=w.object({scenarioId:w.uuid(),scenarioName:w.string().min(1)}).strict(),nn=8192,To=w.string().min(1).refine(t=>new TextEncoder().encode(t).length<=nn,`instructions must be at most ${String(nn)} UTF-8 bytes`),rn=w.object({scenarios:w.array(ko).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:To.nullable(),headful:w.boolean()}).strict(),on=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 Re}from"zod";var Ao=["queued","launching","in_progress","completed","failed","cancelled"],Zs=Re.enum(Ao);var Io=["queued","launching","in_progress"],an=Re.enum(Io);var sn=["claim_timeout","launch_timeout","launch_error","browser_gone","agent_lost","max_duration","killed"],Qs=Re.enum(sn),xo=["launch_error","browser_gone","max_duration"],ln=Re.enum(xo);var Oo=[...sn,"stalled","capability_mismatch","subject_rejected"],el=Re.enum(Oo);var Po=c.enum(["darwin","linux","win32"]),No=c.enum(["x64","arm64"]),dn=c.enum(["official","debug"]),sl=c.object({enrollmentCode:c.string().min(32),hostname:c.string().min(1).max(255),platform:Po,arch:No,agentVersion:c.string().min(1).max(30),protocolVersion:c.number().int().min(1)}).strict(),De=c.object({agentId:c.uuid(),agentToken:c.string().regex(Q),pollWaitSec:c.number().int().min(1).max(25),protocolVersion:c.literal(1)}).strict(),ll=c.object({waitSec:c.coerce.number().int().min(0).max(25).optional()}).strict(),cn=c.object({agent:c.object({revoked:c.boolean()}).strict(),run:c.union([c.null(),c.object({runId:c.uuid(),phase:an}).strict()])}).strict(),kt=c.object({v:c.literal(1),kind:c.literal("playback"),runId:c.uuid(),scenarioId:c.uuid(),projectId:c.uuid(),projectDomain:c.string().min(1),applicationId:c.uuid().nullable(),environmentId:c.uuid().nullable(),executionMode:c.literal("auto"),issuedAt:c.iso.datetime()}).strict(),Tt=c.object({v:c.literal(1),kind:c.literal("make_auto"),runId:c.uuid(),issuedAt:c.iso.datetime(),...rn.shape}).strict(),At=c.object({v:c.literal(1),kind:c.literal("atlas_crawl"),runId:c.uuid(),issuedAt:c.iso.datetime(),...on.shape}).strict(),dl=c.discriminatedUnion("kind",[kt,Tt,At]),Co={playback:!0,make_auto:!0,atlas_crawl:!0},cl=Object.keys(Co),ul=c.object({agentJobId:c.uuid(),updatedAt:c.iso.datetime()}).strict(),Do=c.enum(["invalid_envelope","dispatch_failed"]),un=c.discriminatedUnion("outcome",[c.object({runId:c.uuid(),outcome:c.literal("dispatched")}).strict(),c.object({runId:c.uuid(),outcome:c.literal("rejected"),reason:Do}).strict()]),mn=c.object({cancelRequested:c.boolean(),killRequested:c.boolean()}).strict(),Lo=2147483646,Go=c.object({stepId:c.uuid(),stepIndex:c.number().int().min(0).max(Lo),status:c.enum(["passed","failed","skipped"]),failureCode:c.string().max(64).regex(/^[a-z0-9_]+$/).nullable(),notes:c.string().max(4e3).nullable(),startedAt:c.iso.datetime().nullable(),completedAt:c.iso.datetime().nullable()}).strict(),ml=c.object({events:c.array(Go).min(1).max(50)}).strict(),pl=c.object({updated:c.number().int().min(0),control:mn}).strict(),hl=c.object({phase:c.enum(["running","paused"])}).strict(),gl=c.object({control:mn}).strict(),fl=c.object({reason:ln,message:c.string().max(500).optional()}).strict(),pn=c.object({status:c.enum(["failed","already_terminal"])}).strict();var Sl=g.union([g.object({}).strict(),g.object({capabilities:Zt}).strict()]);function It(t){let{value:e}=t;e.command.runId!==e.runId&&t.issues.push({code:"custom",input:e.command.runId,path:["command","runId"],message:"command.runId must be the claimed runId \u2014 the agent and the extension must monitor the same unit of work"})}o(It,"checkClaimRunIdAgreement");function Mo(t){let{value:e}=t;e.command.projectId!==e.projectId&&t.issues.push({code:"custom",input:e.command.projectId,path:["command","projectId"],message:"command.projectId must be the claimed projectId"})}o(Mo,"checkPlaybackClaimProjectAgreement");var Uo=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:dn,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:kt}).strict().check(It).check(Mo),gn=g.object({accessToken:g.string().min(1),refreshToken:g.string().min(1)}).strict(),$o=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:gn,command:Tt}).strict().check(It),Fo=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:gn,command:At}).strict().check(It),fn=g.union([Uo,$o,Fo]);import{spawn as Yo}from"node:child_process";import{existsSync as Xo}from"node:fs";import{createRequire as zo}from"node:module";import{dirname as En,join as Zo}from"node:path";import Jo from"pino";var jo=new Set(["token","agenttoken","accesstoken","refreshtoken","pgrttoken","jobtoken","authorization","secret","password","resolvedvariables","cookie","set-cookie","x-api-key","proxy-authorization","api-key"]),qo=/\b(?:pgat_|rr_|pgrt_)[A-Za-z0-9_-]+/g,Bo=/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,Ho=["token","secret","password","authorization","api_key","api-key","apikey"],Vo=new RegExp(`([?&](?:${Ho.join("|")})=)([^&\\s]+)`,"gi"),Le="[REDACTED]";function yn(t){let e=t.replace(Bo,Le);return e=e.replace(qo,Le),e=e.replace(Vo,`$1${Le}`),e}o(yn,"redactValueString");function W(t){if(Array.isArray(t))return t.map(W);if(t!==null&&typeof t=="object"){let e=t,n={};for(let r of Object.keys(e))jo.has(r.toLowerCase())?n[r]=Le:n[r]=W(e[r]);return n}return typeof t=="string"?yn(t):t}o(W,"redactSecrets");function L(t){return yn(t)}o(L,"redactSensitiveText");function Ko(){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"}o(Ko,"resolveLogLevel");function Wo(){if(process.env.NODE_ENV!=="production")return{target:"pino-pretty",options:{translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname"}}}o(Wo,"buildTransport");var wn=Jo({name:"qa-runner",level:Ko(),transport:Wo(),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 xt(t){return{debug(e,n){n!==void 0?t.debug(W(n),e):t.debug(e)},info(e,n){n!==void 0?t.info(W(n),e):t.info(e)},warn(e,n){n!==void 0?t.warn(W(n),e):t.warn(e)},error(e,n){n!==void 0?t.error(W(n),e):t.error(e)},child(e){return xt(t.child(e))}}}o(xt,"adaptPino");function u(t){return xt(wn.child({module:t}))}o(u,"createLogger");var Gl=xt(wn);var Ot=u("browser-provision"),Qo=60*6e4,j=class extends Error{static{o(this,"BrowserProvisionError")}exitCode;timedOut;constructor(e,n={}){super(e,{cause:n.cause}),this.name="BrowserProvisionError",this.exitCode=n.exitCode===void 0?null:n.exitCode,this.timedOut=n.timedOut===void 0?!1:n.timedOut}},vn=[" - 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 ei(){let t=zo(import.meta.url),e;try{e=t.resolve("playwright-core/package.json")}catch(r){throw new j(`[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=Zo(En(e),"cli.js");if(!Xo(n))throw new j(`[browser-provision] 'playwright-core' resolved to ${En(e)} but its CLI is not at ${n}. That installation is incomplete or has been altered \u2014 reinstall it ('npm ci'). This agent installs Chromium through that CLI and through no other path (CONTRACT-la \xA715 A31.1).`);return{execPath:process.execPath,cliPath:n,args:["install","chromium","--no-shell"]}}o(ei,"resolveInstallCommand");async function Ge(t){let e=t.commandOverride===void 0?ei():t.commandOverride,n=t.deadlineMs===void 0?Qo:t.deadlineMs,r=t.stdio==="pipe"?[...e.args,"--no-progress"]:[...e.args],i=`${e.execPath} ${e.cliPath} ${r.join(" ")}`,a=Date.now();Ot.info("Provisioning Chromium",{cliPath:e.cliPath,args:r,deadlineMs:n});let s=Yo(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 j(`[browser-provision] The installer was spawned without the stdout/stderr pipes this module requested (${i}).`);_n(h,"stdout"),_n(p,"stderr")}let l=!1,d=setTimeout(()=>{l=!0,s.kill("SIGKILL")},n),m=new Map,f=o(()=>{for(let[h,p]of m)process.off(h,p);m.clear()},"removeSignalHandlers");for(let h of["SIGTERM","SIGINT"]){let p=o(()=>{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",b=>{p(new j(`[browser-provision] Could not start the Playwright installer (${i}): ${b.message}`,{cause:b}))}),s.once("close",(b,R)=>{if(l){p(new j(`[browser-provision] Chromium installation did not finish within ${n}ms and was killed (${i}). A stalled installer is a known Playwright failure mode (microsoft/playwright#40998) and usually means the download connection went silent rather than failing.
5
- ${vn}`,{exitCode:b,timedOut:!0}));return}if(b===0){h();return}let Ne=b===null?`was terminated by signal ${String(R)}`:`exited with code ${b}`;p(new j(`[browser-provision] Chromium could not be installed: the Playwright installer ${Ne} (${i}). The agent cannot run scenarios without a browser and does not retry \u2014 a failed download is an environment condition, not a transient one.
6
- ${vn}`,{exitCode:b}))})})}finally{clearTimeout(d),f()}Ot.info("Chromium is provisioned",{durationMs:Date.now()-a})}o(Ge,"provisionBrowser");function _n(t,e){let n="";t.setEncoding("utf8"),t.on("data",r=>{n+=r;let i=n.lastIndexOf(`
7
- `);if(i===-1)return;let a=n.slice(0,i);n=n.slice(i+1);for(let s of a.split(`
8
- `))Sn(s,e)}),t.on("end",()=>{let r=n;n="",Sn(r,e)})}o(_n,"forwardLinesToLogger");function Sn(t,e){let n=t.replace(/\r/g,"").trim();n!==""&&Ot.info("Chromium provisioning output",{stream:e,line:n})}o(Sn,"logLine");import{homedir as Pi}from"node:os";import{isAbsolute as Hn,join as qe}from"node:path";var ti=new Set(["localhost","127.0.0.1","::1","[::1]"]);function be(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:"&&ti.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.`)}o(be,"validateServerUrl");function ke(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.")}o(ke,"validateRunnerToken");function Pt(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.`)}o(Pt,"validateRunnerMachineId");function Nt(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.`)}o(Nt,"validateProtocolVersion");import{Agent as ni,EnvHttpProxyAgent as ri}from"undici";var Rn=u("gateway-proxy"),oi=["http_proxy","HTTP_PROXY"],ii=["https_proxy","HTTPS_PROXY"],ai=["no_proxy","NO_PROXY"];function si(t){return t.http!==void 0||t.https!==void 0}o(si,"gatewayIsProxied");var li=/^[A-Za-z][A-Za-z0-9+.-]*:\/\//,di=/:\d+$/,ci=/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)?[^/?#]*@/;function ui(t){let e=ci.exec(t);if(e===null)return t;let n=e[1];return`${n===void 0?"":n}***@${t.slice(e[0].length)}`}o(ui,"withoutProxyCredentials");function te(t,e,n){return new Error(`[config] ${t} does not name a proxy this agent can use: ${n}. Got: ${JSON.stringify(ui(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.`)}o(te,"refuseProxyValue");function bn(t,e){for(let n of e){let r=t[n];if(r!==void 0)return r===""?void 0:{variable:n,raw:r}}}o(bn,"readProxyVariable");function mi(t){for(let e of ai){let n=t[e];if(n!==void 0)return n}}o(mi,"readNoProxy");function kn(t,e){if(li.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(!di.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 i=`http://${e}`,a;try{a=new URL(i)}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:i,schemeCompleted:!0}}o(kn,"parseProxyValue");function Ct(t){let e=bn(t,oi),n=bn(t,ii);return{http:e===void 0?void 0:kn(e.variable,e.raw),https:n===void 0?void 0:kn(n.variable,n.raw),noProxy:mi(t)}}o(Ct,"resolveGatewayProxyConfig");function Tn(t,e,n){if(!si(t))return new ni(e);Rn.info("Gateway traffic follows the proxy configured in this environment",{httpProxy:t.http!==void 0,httpsProxy:t.https!==void 0,noProxy:t.noProxy!==void 0});let r=[];for(let a of[t.http,t.https])a!==void 0&&a.schemeCompleted&&r.push(a.variable);r.length>0&&Rn.info('A proxy variable carries no scheme and is read as an HTTP proxy (curl convention: "host:port" means "http://host:port")',{variables:r});let i={...e,...n===void 0?{}:{requestTls:{ca:n},proxyTls:{ca:n}},httpProxy:t.http?.url,httpsProxy:t.https?.url,noProxy:t.noProxy};return new ri(i)}o(Tn,"createProxyAwareDispatcher");function An(t){Ct(t)}o(An,"validateGatewayProxyEnv");import{readFileSync as pi,statSync as hi}from"node:fs";import{isAbsolute as gi}from"node:path";import{rootCertificates as In}from"node:tls";var fi=u("gateway-tls-trust"),Ue="PROGON_AGENT_EXTRA_CA_CERTS";function Me(t,e,n){let r=`[config] ${Ue} does not name a certificate bundle this agent can use: ${e}. Got: ${JSON.stringify(t)}. Accepted: an ABSOLUTE path to a readable PEM file holding the corporate root certificate (one or more "-----BEGIN CERTIFICATE-----" blocks). It extends the trust of the agent's OWN connections to the Progon backend; it does not reach the browser, which trusts what the operating system trusts. Unset ${Ue} to trust only the public roots.`;return n===void 0?new Error(r):new Error(r,{cause:n})}o(Me,"refuseExtraCaValue");function xn(t){let e=t[Ue];if(e===void 0||e==="")return;if(!gi(e))throw Me(e,"it is not an absolute path, and a relative one would be resolved against the working directory the daemon happens to have been started in");let n;try{n=hi(e)}catch(i){throw Me(e,"it cannot be read",i)}if(!n.isFile())throw Me(e,"it is not a file");let r;try{r=pi(e,"utf8")}catch(i){throw Me(e,"its contents could not be read",i)}return{variable:Ue,path:e,pem:r}}o(xn,"resolveExtraCaTrust");function On(t){let e=xn(t);if(e!==void 0)return fi.info("Trusting an extra certificate authority for the agent's own connections",{variable:e.variable,path:e.path,publicRootCount:In.length}),[...In,e.pem]}o(On,"readTrustedCaBundle");function Pn(t){xn(t)}o(Pn,"validateExtraCaTrustEnv");import{unlinkSync as xi}from"node:fs";import{readFileSync as yi,writeFileSync as wi,renameSync as Ei,mkdirSync as vi,existsSync as _i,chmodSync as Si,fchmodSync as Ri,openSync as Nn,fsyncSync as Cn,closeSync as Dn,unlinkSync as bi}from"node:fs";import{join as Ln}from"node:path";var $e=u("state-file");function Fe(t){return Ln(t,"runner-state.json")}o(Fe,"stateFilePath");function Dt(t){return Ln(t,"runner-state.json.tmp")}o(Dt,"stateTmpPath");function Gn(t){let e=Fe(t);if(!_i(e))return $e.debug("No state file found \u2014 first start",{filePath:e}),null;let n;try{n=yi(e,"utf-8")}catch(a){throw new Error(`[state-file] Failed to read state file at ${e}: ${String(a)}. Check that this user owns the file and its directory. If it is beyond repair, remove it and enroll the machine again: progon-agent enroll --server <url>.`)}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 enroll the machine again: progon-agent enroll --server <url>.`)}let i=Ai(r,e);return $e.info("State file loaded",{agentId:i.agentId,protocolVersion:i.protocolVersion}),i}o(Gn,"readState");function Mn(t,e){vi(t,{recursive:!0,mode:448}),Si(t,448);let n=Fe(t),r=Dt(t),i=JSON.stringify(e,null,2);try{let a=Nn(r,"w",384);try{Ri(a,384),wi(a,i,{encoding:"utf-8"}),Cn(a)}finally{Dn(a)}Ei(r,n),Ti(t)}catch(a){throw ki(r),new Error(`[state-file] Failed to write state file at ${n}: ${String(a)}. Check permissions on stateDir ${t}.`)}$e.info("State file written",{agentId:e.agentId,filePath:n})}o(Mn,"writeState");function ki(t){try{bi(t)}catch(e){if(e.code==="ENOENT")return;$e.error("Failed to remove the temporary state file \u2014 it may still hold the agent credential",{tmpPath:t,err:e instanceof Error?e.message:String(e)})}}o(ki,"removeStateTmp");function Ti(t){let e=Nn(t,"r");try{Cn(e)}finally{Dn(e)}}o(Ti,"fsyncDirectory");function Ai(t,e){if(typeof t!="object"||t===null||Array.isArray(t)){let l=t===null?"null":Array.isArray(t)?"array":typeof t;throw new Error(`[state-file] State file ${e} must contain a JSON object, got: ${l}`)}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).`);Pt(r);let i=n.agentToken;if(typeof i!="string"||i==="")throw new Error(`[state-file] State file ${e} is missing or has invalid 'agentToken' (expected non-empty string).`);ke(i);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).`);Nt(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{be(s)}catch(l){throw new Error(`[state-file] State file ${e} has an invalid 'serverUrl': ${String(l)}`)}return{agentId:r,agentToken:i,protocolVersion:a,serverUrl:s,tokenRotatedAt:Ii(n,e)}}o(Ai,"validateState");function Ii(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}o(Ii,"readTokenRotatedAt");var Un=u("token-store");function G(t){return Gn(t)}o(G,"loadAgentIdentity");function ne(t,e){Mn(t,e)}o(ne,"saveAgentIdentity");function Fn(t){let e=Fe(t),n=Dt(t),r=$n(n,"temporary state file"),i=$n(e,"identity");if(!i&&!r){Un.info("Agent identity wipe: no state file to remove",{filePath:e,tmpPath:n});return}Un.warn("Agent identity wiped \u2014 this agent was revoked and must be re-enrolled",{filePath:e,tmpPath:n,removedState:i,removedTmp:r})}o(Fn,"wipeAgentIdentity");function $n(t,e){try{return xi(t),!0}catch(n){if(Oi(n))return!1;throw new Error(`[token-store] Failed to wipe the agent ${e} at ${t}: ${String(n)}. The agent has been revoked (CONTRACT-la \xA715 A15.1) and its credential must not remain on disk \u2014 remove the file manually.`)}}o($n,"removeCredentialFile");function Oi(t){return t.code==="ENOENT"}o(Oi,"isFileNotFound");function je(t,e){return jn(t)===jn(e)}o(je,"isSameDeployment");function jn(t){let e=new URL(t);return`${e.origin}${e.pathname.replace(/\/+$/,"")}`}o(jn,"normalizeDeployment");function qn(t){let{envUrl:e,envTokenPresent:n,stateDir:r}=t;if(e!==void 0)return be(e),{url:e,source:"env"};if(n)throw new Error(`[config] PROGON_SERVER_URL is not set, and PROGON_AGENT_TOKEN names no deployment \u2014 a pgat_ token is only meaningful at the backend that minted it, and this daemon will not guess which one that is.
2
+ var To=Object.defineProperty;var i=(t,e)=>To(t,"name",{value:e,configurable:!0});import{realpathSync as Vs}from"node:fs";import{pathToFileURL as Hs}from"node:url";import{z as tn}from"zod";var Ao=/^[a-z_]{1,32}@\d{1,3}$/,nn=tn.array(tn.string().regex(Ao)).min(1).max(32),rn=["playback@1"],on="make_auto@1",an="atlas_crawl@1";import{z as f}from"zod";var ne=/^pgat_[0-9A-Za-z]{43}$/;var ke="agent:command",Le="agent:command-ack",At="agent:active-job";import{z as c}from"zod";import{z as E}from"zod";var Io=E.object({scenarioId:E.uuid(),scenarioName:E.string().min(1)}).strict(),sn=8192,Oo=E.string().min(1).refine(t=>new TextEncoder().encode(t).length<=sn,`instructions must be at most ${String(sn)} UTF-8 bytes`),ln=E.object({scenarios:E.array(Io).min(1).max(1e3),projectId:E.uuid(),projectDomain:E.string().min(1),applicationId:E.uuid().nullable(),environmentId:E.uuid().nullable(),entryUrl:E.url({protocol:/^https?$/}),instructions:Oo.nullable(),headful:E.boolean()}).strict(),dn=E.object({projectId:E.uuid(),projectDomain:E.string().min(1),entryUrl:E.url({protocol:/^https?$/}),standMode:E.enum(["main","dangerous"]),accountLabel:E.string().min(1),role:E.string().min(1),locale:E.string().min(1),viewportWidth:E.number().int().min(1),viewportHeight:E.number().int().min(1)}).strict();import{z as Te}from"zod";var Po=["queued","launching","in_progress","completed","failed","cancelled"],ll=Te.enum(Po);var No=["queued","launching","in_progress"],cn=Te.enum(No);var un=["claim_timeout","launch_timeout","launch_error","browser_gone","agent_lost","max_duration","killed"],dl=Te.enum(un),Co=["launch_error","browser_gone","max_duration"],pn=Te.enum(Co);var Do=[...un,"stalled","capability_mismatch","subject_rejected"],cl=Te.enum(Do);var Lo=c.enum(["darwin","linux","win32"]),Go=c.enum(["x64","arm64"]),mn=c.enum(["official","debug"]),yl=c.object({enrollmentCode:c.string().min(32),hostname:c.string().min(1).max(255),platform:Lo,arch:Go,agentVersion:c.string().min(1).max(30),protocolVersion:c.number().int().min(1)}).strict(),Ge=c.object({agentId:c.uuid(),agentToken:c.string().regex(ne),pollWaitSec:c.number().int().min(1).max(25),protocolVersion:c.literal(1)}).strict(),wl=c.object({waitSec:c.coerce.number().int().min(0).max(25).optional()}).strict(),hn=c.object({agent:c.object({revoked:c.boolean()}).strict(),run:c.union([c.null(),c.object({runId:c.uuid(),phase:cn}).strict()])}).strict(),xt=c.object({v:c.literal(1),kind:c.literal("playback"),runId:c.uuid(),scenarioId:c.uuid(),projectId:c.uuid(),projectDomain:c.string().min(1),applicationId:c.uuid().nullable(),environmentId:c.uuid().nullable(),executionMode:c.literal("auto"),issuedAt:c.iso.datetime()}).strict(),It=c.object({v:c.literal(1),kind:c.literal("make_auto"),runId:c.uuid(),issuedAt:c.iso.datetime(),...ln.shape}).strict(),Ot=c.object({v:c.literal(1),kind:c.literal("atlas_crawl"),runId:c.uuid(),issuedAt:c.iso.datetime(),...dn.shape}).strict(),El=c.discriminatedUnion("kind",[xt,It,Ot]),Mo={playback:!0,make_auto:!0,atlas_crawl:!0},vl=Object.keys(Mo),bl=c.object({agentJobId:c.uuid(),updatedAt:c.iso.datetime()}).strict(),Uo=c.enum(["invalid_envelope","dispatch_failed"]),gn=c.discriminatedUnion("outcome",[c.object({runId:c.uuid(),outcome:c.literal("dispatched")}).strict(),c.object({runId:c.uuid(),outcome:c.literal("rejected"),reason:Uo}).strict()]),fn=c.object({cancelRequested:c.boolean(),killRequested:c.boolean()}).strict(),$o=2147483646,Fo=c.object({stepId:c.uuid(),stepIndex:c.number().int().min(0).max($o),status:c.enum(["passed","failed","skipped"]),failureCode:c.string().max(64).regex(/^[a-z0-9_]+$/).nullable(),notes:c.string().max(4e3).nullable(),startedAt:c.iso.datetime().nullable(),completedAt:c.iso.datetime().nullable()}).strict(),_l=c.object({events:c.array(Fo).min(1).max(50)}).strict(),Rl=c.object({updated:c.number().int().min(0),control:fn}).strict(),Sl=c.object({phase:c.enum(["running","paused"])}).strict(),kl=c.object({control:fn}).strict(),Tl=c.object({reason:pn,message:c.string().max(500).optional()}).strict(),yn=c.object({status:c.enum(["failed","already_terminal"])}).strict();var Nl=f.union([f.object({}).strict(),f.object({capabilities:nn}).strict()]);function Pt(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(Pt,"checkClaimRunIdAgreement");function jo(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(jo,"checkPlaybackClaimProjectAgreement");var Bo=f.object({runId:f.uuid(),scenarioId:f.uuid(),projectId:f.uuid(),applicationId:f.uuid().nullable(),projectDomain:f.string().min(1),entryUrl:f.url({protocol:/^https?$/}),environmentId:f.uuid().nullable(),runPurpose:mn,headful:f.boolean(),maxRunDurationSec:f.number().int().min(60).max(3600),extensionSession:f.object({accessToken:f.string().min(1),refreshToken:f.string().min(1)}).strict(),command:xt}).strict().check(Pt).check(jo),En=f.object({accessToken:f.string().min(1),refreshToken:f.string().min(1)}).strict(),qo=f.object({kind:f.literal("make_auto"),runId:f.uuid(),entryUrl:f.url({protocol:/^https?$/}),headful:f.boolean(),maxRunDurationSec:f.number().int().min(60).max(604800),extensionSession:En,command:It}).strict().check(Pt),Vo=f.object({kind:f.literal("atlas_crawl"),runId:f.uuid(),entryUrl:f.url({protocol:/^https?$/}),headful:f.boolean(),maxRunDurationSec:f.number().int().min(60).max(604800),extensionSession:En,command:Ot}).strict().check(Pt),vn=f.union([Bo,qo,Vo]);import{spawn as Qo}from"node:child_process";import{existsSync as ei}from"node:fs";import{createRequire as ti}from"node:module";import{dirname as Rn,join as ni}from"node:path";import Xo from"pino";var Ho=new Set(["token","agenttoken","accesstoken","refreshtoken","pgrttoken","jobtoken","authorization","secret","password","resolvedvariables","cookie","set-cookie","x-api-key","proxy-authorization","api-key"]),Jo=/\b(?:pgat_|rr_|pgrt_)[A-Za-z0-9_-]+/g,Ko=/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,Wo=["token","secret","password","authorization","api_key","api-key","apikey"],Yo=new RegExp(`([?&](?:${Wo.join("|")})=)([^&\\s]+)`,"gi"),Me="[REDACTED]";function bn(t){let e=t.replace(Ko,Me);return e=e.replace(Jo,Me),e=e.replace(Yo,`$1${Me}`),e}i(bn,"redactValueString");function Y(t){if(Array.isArray(t))return t.map(Y);if(t!==null&&typeof t=="object"){let e=t,n={};for(let r of Object.keys(e))Ho.has(r.toLowerCase())?n[r]=Me:n[r]=Y(e[r]);return n}return typeof t=="string"?bn(t):t}i(Y,"redactSecrets");function G(t){return bn(t)}i(G,"redactSensitiveText");function zo(){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(zo,"resolveLogLevel");function Zo(){if(process.env.NODE_ENV!=="production")return{target:"pino-pretty",options:{translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname"}}}i(Zo,"buildTransport");var _n=Xo({name:"qa-runner",level:zo(),transport:Zo(),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 Nt(t){return{debug(e,n){n!==void 0?t.debug(Y(n),e):t.debug(e)},info(e,n){n!==void 0?t.info(Y(n),e):t.info(e)},warn(e,n){n!==void 0?t.warn(Y(n),e):t.warn(e)},error(e,n){n!==void 0?t.error(Y(n),e):t.error(e)},child(e){return Nt(t.child(e))}}}i(Nt,"adaptPino");function u(t){return Nt(_n.child({module:t}))}i(u,"createLogger");var Jl=Nt(_n);var Ct=u("browser-provision"),ri=60*6e4,B=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}},Sn=[" - 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 oi(){let t=ti(import.meta.url),e;try{e=t.resolve("playwright-core/package.json")}catch(r){throw new B(`[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=ni(Rn(e),"cli.js");if(!ei(n))throw new B(`[browser-provision] 'playwright-core' resolved to ${Rn(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(oi,"resolveInstallCommand");async function Ue(t){let e=t.commandOverride===void 0?oi():t.commandOverride,n=t.deadlineMs===void 0?ri:t.deadlineMs,r=t.stdio==="pipe"?[...e.args,"--no-progress"]:[...e.args],o=`${e.execPath} ${e.cliPath} ${r.join(" ")}`,a=Date.now();Ct.info("Provisioning Chromium",{cliPath:e.cliPath,args:r,deadlineMs:n});let s=Qo(e.execPath,[e.cliPath,...r],{env:process.env,stdio:t.stdio==="inherit"?"inherit":["ignore","pipe","pipe"]});if(t.stdio==="pipe"){let{stdout:g,stderr:h}=s;if(g===null||h===null)throw new B(`[browser-provision] The installer was spawned without the stdout/stderr pipes this module requested (${o}).`);kn(g,"stdout"),kn(h,"stderr")}let l=!1,d=setTimeout(()=>{l=!0,s.kill("SIGKILL")},n),m=new Map,y=i(()=>{for(let[g,h]of m)process.off(g,h);m.clear()},"removeSignalHandlers");for(let g of["SIGTERM","SIGINT"]){let h=i(()=>{s.kill("SIGKILL"),y(),process.stderr.write(JSON.stringify({level:"warn",module:"browser-provision",msg:"Chromium provisioning aborted by signal: the installer was killed, and the next start downloads again",signal:g,installerPid:s.pid})+`
4
+ `),process.kill(process.pid,g)},"handler");m.set(g,h),process.on(g,h)}try{await new Promise((g,h)=>{s.once("error",k=>{h(new B(`[browser-provision] Could not start the Playwright installer (${o}): ${k.message}`,{cause:k}))}),s.once("close",(k,S)=>{if(l){h(new B(`[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
+ ${Sn}`,{exitCode:k,timedOut:!0}));return}if(k===0){g();return}let De=k===null?`was terminated by signal ${String(S)}`:`exited with code ${k}`;h(new B(`[browser-provision] Chromium could not be installed: the Playwright installer ${De} (${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
+ ${Sn}`,{exitCode:k}))})})}finally{clearTimeout(d),y()}Ct.info("Chromium is provisioned",{durationMs:Date.now()-a})}i(Ue,"provisionBrowser");function kn(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
+ `))Tn(s,e)}),t.on("end",()=>{let r=n;n="",Tn(r,e)})}i(kn,"forwardLinesToLogger");function Tn(t,e){let n=t.replace(/\r/g,"").trim();n!==""&&Ct.info("Chromium provisioning output",{stream:e,line:n})}i(Tn,"logLine");import{homedir as Hi}from"node:os";import{isAbsolute as Xn,join as He}from"node:path";var p=class extends Error{static{i(this,"OperatorRefusalError")}};var ii=new Set(["localhost","127.0.0.1","::1","[::1]"]);function X(t){let e;try{e=new URL(t)}catch{throw new p("[config] PROGON_SERVER_URL is not a valid https:// URL. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.")}if(e.protocol!=="https:"&&!(e.protocol==="http:"&&ii.has(e.hostname)))throw new p(`[config] PROGON_SERVER_URL must use the https:// scheme (encrypted HTTP). http:// is only allowed for loopback hosts (localhost, 127.0.0.1, [::1]). Got scheme: ${JSON.stringify(e.protocol)} with host: ${JSON.stringify(e.hostname)}. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`);if(e.host==="")throw new p(`[config] PROGON_SERVER_URL must include a non-empty host. Got: ${JSON.stringify(t)}. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`);if(e.username!==""||e.password!=="")throw new p("[config] PROGON_SERVER_URL must not contain embedded credentials (userinfo). Use the PROGON_AGENT_TOKEN env var for authentication instead. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.");if(e.search!==""||e.hash!=="")throw new p(`[config] PROGON_SERVER_URL must be a base URL with no query string and no fragment \u2014 the agent-gateway routes are appended to it, and a query or a fragment would swallow them instead of preceding them. Got query ${JSON.stringify(e.search)} and fragment ${JSON.stringify(e.hash)}. Use scheme + host + optional path prefix only (https://host, https://host/prefix). See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`)}i(X,"validateServerUrl");function Ae(t){if(!ne.test(t))throw new p("[config] Agent token must match the pgat_ wire format (CONTRACT-la \xA75.1). Got a token that does not match this format. Ensure PROGON_AGENT_TOKEN was copied from the server correctly.")}i(Ae,"validateRunnerToken");function Dt(t){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))throw new p(`[config] agentId must be a valid UUID (issued by the server at enroll). Got: ${JSON.stringify(t)}. The state file may be corrupted \u2014 remove it and re-enroll.`)}i(Dt,"validateRunnerMachineId");function Lt(t){if(t!==1)throw new p(`[config] Protocol version mismatch: state file records version ${t} but this daemon requires version ${1}. Remove the state file and re-enroll with the correct daemon version.`)}i(Lt,"validateProtocolVersion");import{Agent as ai,EnvHttpProxyAgent as si}from"undici";var An=u("gateway-proxy"),li=["http_proxy","HTTP_PROXY"],di=["https_proxy","HTTPS_PROXY"],ci=["no_proxy","NO_PROXY"];function ui(t){return t.http!==void 0||t.https!==void 0}i(ui,"gatewayIsProxied");var pi=/^[A-Za-z][A-Za-z0-9+.-]*:\/\//,mi=/:\d+$/,hi=/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)?[^/?#]*@/;function gi(t){let e=hi.exec(t);if(e===null)return t;let n=e[1];return`${n===void 0?"":n}***@${t.slice(e[0].length)}`}i(gi,"withoutProxyCredentials");function oe(t,e,n){return new Error(`[config] ${t} does not name a proxy this agent can use: ${n}. Got: ${JSON.stringify(gi(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(oe,"refuseProxyValue");function xn(t,e){for(let n of e){let r=t[n];if(r!==void 0)return r===""?void 0:{variable:n,raw:r}}}i(xn,"readProxyVariable");function fi(t){for(let e of ci){let n=t[e];if(n!==void 0)return n}}i(fi,"readNoProxy");function In(t,e){if(pi.test(e)){let s;try{s=new URL(e)}catch{throw oe(t,e,"it carries a scheme but is not a URL that parses")}if(s.protocol!=="http:"&&s.protocol!=="https:")throw oe(t,e,`its scheme is ${JSON.stringify(s.protocol)}, not http: or https:`);if(s.hostname==="")throw oe(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(!mi.test(r))throw oe(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 oe(t,e,'it is neither a URL nor a "host:port" pair')}if(a.hostname==="")throw oe(t,e,"it names no host");return{variable:t,url:o,schemeCompleted:!0}}i(In,"parseProxyValue");function Gt(t){let e=xn(t,li),n=xn(t,di);return{http:e===void 0?void 0:In(e.variable,e.raw),https:n===void 0?void 0:In(n.variable,n.raw),noProxy:fi(t)}}i(Gt,"resolveGatewayProxyConfig");function On(t,e,n){if(!ui(t))return new ai(e);An.info("Gateway traffic follows the proxy configured in this environment",{httpProxy:t.http!==void 0,httpsProxy:t.https!==void 0,noProxy:t.noProxy!==void 0});let r=[];for(let a of[t.http,t.https])a!==void 0&&a.schemeCompleted&&r.push(a.variable);r.length>0&&An.info('A proxy variable carries no scheme and is read as an HTTP proxy (curl convention: "host:port" means "http://host:port")',{variables:r});let o={...e,...n===void 0?{}:{requestTls:{ca:n},proxyTls:{ca:n}},httpProxy:t.http?.url,httpsProxy:t.https?.url,noProxy:t.noProxy};return new si(o)}i(On,"createProxyAwareDispatcher");function Pn(t){Gt(t)}i(Pn,"validateGatewayProxyEnv");import{readFileSync as yi,statSync as wi}from"node:fs";import{isAbsolute as Ei}from"node:path";import{rootCertificates as Nn}from"node:tls";var vi=u("gateway-tls-trust"),Fe="PROGON_AGENT_EXTRA_CA_CERTS";function $e(t,e,n){let r=`[config] ${Fe} does not name a certificate bundle this agent can use: ${e}. Got: ${JSON.stringify(t)}. Accepted: an ABSOLUTE path to a readable PEM file holding the corporate root certificate (one or more "-----BEGIN CERTIFICATE-----" blocks). It extends the trust of the agent's OWN connections to the Progon backend; it does not reach the browser, which trusts what the operating system trusts. Unset ${Fe} to trust only the public roots.`;return n===void 0?new Error(r):new Error(r,{cause:n})}i($e,"refuseExtraCaValue");function Cn(t){let e=t[Fe];if(e===void 0||e==="")return;if(!Ei(e))throw $e(e,"it is not an absolute path, and a relative one would be resolved against the working directory the daemon happens to have been started in");let n;try{n=wi(e)}catch(o){throw $e(e,"it cannot be read",o)}if(!n.isFile())throw $e(e,"it is not a file");let r;try{r=yi(e,"utf8")}catch(o){throw $e(e,"its contents could not be read",o)}return{variable:Fe,path:e,pem:r}}i(Cn,"resolveExtraCaTrust");function Dn(t){let e=Cn(t);if(e!==void 0)return vi.info("Trusting an extra certificate authority for the agent's own connections",{variable:e.variable,path:e.path,publicRootCount:Nn.length}),[...Nn,e.pem]}i(Dn,"readTrustedCaBundle");function Ln(t){Cn(t)}i(Ln,"validateExtraCaTrustEnv");import{readFileSync as ki}from"node:fs";import{dirname as Ti,join as Ai}from"node:path";import{fileURLToPath as xi}from"node:url";function z(t){if(typeof t!="object"||t===null)return!1;let e=t.code;return e==="ENOENT"||e==="ENOTDIR"}i(z,"isAbsentPathError");import{statSync as bi}from"node:fs";import{dirname as _i,join as Ri}from"node:path";var Gn="package.json";function je(t){let e=t;for(;;){if(Si(e))return e;let n=_i(e);if(n===e)throw new Error(`[package-root] No ${Gn} 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(je,"findPackageRoot");function Si(t){try{return bi(Ri(t,Gn)),!0}catch(e){if(z(e))return!1;throw e}}i(Si,"holdsPackageManifest");var Ii="extension-bundle.json";function Mt(){return Oi(Ai(je(Ti(xi(import.meta.url))),Ii))}i(Mt,"readBundledAppUrl");function Oi(t){let e;try{e=ki(t,"utf-8")}catch(o){if(z(o))return null;throw new p(`[extension-bundle] ${t} exists but could not be read: ${String(o)}. It records the deployment this package was built for, so the agent cannot tell which Progon it belongs to until the file is readable. Check the permissions on the installed package, or reinstall it: npm i -g progon-agent@latest.`,{cause:o})}let n;try{n=JSON.parse(e)}catch(o){throw new p(`[extension-bundle] ${t} contains invalid JSON: ${String(o)}. This package's record of the deployment it was built for is damaged \u2014 reinstall it: npm i -g progon-agent@latest.`,{cause:o})}if(typeof n!="object"||n===null||Array.isArray(n)){let o=n===null?"null":Array.isArray(n)?"array":typeof n;throw new p(`[extension-bundle] ${t} must contain a JSON object, got: ${o}. Reinstall the package: npm i -g progon-agent@latest.`)}let r=n.appUrl;if(typeof r!="string"||r==="")throw new p(`[extension-bundle] ${t} has no usable 'appUrl' (expected a non-empty string). That field is the deployment this package was built for; without it the agent cannot tell which Progon it belongs to. Reinstall the package (npm i -g progon-agent@latest), or name the deployment explicitly with --server / PROGON_SERVER_URL.`);try{X(r)}catch(o){throw new p(`[extension-bundle] ${t} has an invalid 'appUrl': ${String(o)}`,{cause:o})}return r}i(Oi,"readBundledAppUrlFrom");import{unlinkSync as qi}from"node:fs";import{readFileSync as Pi,writeFileSync as Ni,renameSync as Ci,mkdirSync as Di,existsSync as Li,chmodSync as Gi,fchmodSync as Mi,openSync as Mn,fsyncSync as Un,closeSync as $n,unlinkSync as Ui}from"node:fs";import{join as Fn}from"node:path";var Be=u("state-file");function qe(t){return Fn(t,"runner-state.json")}i(qe,"stateFilePath");function Ut(t){return Fn(t,"runner-state.json.tmp")}i(Ut,"stateTmpPath");function jn(t){let e=qe(t);if(!Li(e))return Be.debug("No state file found \u2014 first start",{filePath:e}),null;let n;try{n=Pi(e,"utf-8")}catch(a){throw new p(`[state-file] Failed to read state file at ${e}: ${String(a)}. Check that this user owns the file and its directory. If it is beyond repair, remove it and enroll the machine again with 'progon-agent enroll' (a source checkout, which carries no bundled deployment, also needs --server <url>).`)}let r;try{r=JSON.parse(n)}catch(a){throw new p(`[state-file] State file at ${e} contains invalid JSON: ${String(a)}. Remove the file and enroll the machine again with 'progon-agent enroll' (a source checkout, which carries no bundled deployment, also needs --server <url>).`)}let o=ji(r,e);return Be.info("State file loaded",{agentId:o.agentId,protocolVersion:o.protocolVersion}),o}i(jn,"readState");function Bn(t,e){Di(t,{recursive:!0,mode:448}),Gi(t,448);let n=qe(t),r=Ut(t),o=JSON.stringify(e,null,2);try{let a=Mn(r,"w",384);try{Mi(a,384),Ni(a,o,{encoding:"utf-8"}),Un(a)}finally{$n(a)}Ci(r,n),Fi(t)}catch(a){throw $i(r),new p(`[state-file] Failed to write state file at ${n}: ${String(a)}. Check permissions on stateDir ${t}.`)}Be.info("State file written",{agentId:e.agentId,filePath:n})}i(Bn,"writeState");function $i(t){try{Ui(t)}catch(e){if(e.code==="ENOENT")return;Be.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($i,"removeStateTmp");function Fi(t){let e=Mn(t,"r");try{Un(e)}finally{$n(e)}}i(Fi,"fsyncDirectory");function ji(t,e){if(typeof t!="object"||t===null||Array.isArray(t)){let l=t===null?"null":Array.isArray(t)?"array":typeof t;throw new p(`[state-file] State file ${e} must contain a JSON object, got: ${l}`)}let n=t,r=n.agentId;if(typeof r!="string"||r==="")throw new p(`[state-file] State file ${e} is missing or has invalid 'agentId' (expected non-empty string).`);Dt(r);let o=n.agentToken;if(typeof o!="string"||o==="")throw new p(`[state-file] State file ${e} is missing or has invalid 'agentToken' (expected non-empty string).`);Ae(o);let a=n.protocolVersion;if(typeof a!="number"||!Number.isInteger(a))throw new p(`[state-file] State file ${e} is missing or has invalid 'protocolVersion' (expected integer).`);Lt(a);let s=n.serverUrl;if(typeof s!="string"||s==="")throw new p(`[state-file] State file ${e} is missing or has invalid 'serverUrl' (expected non-empty string).`);try{X(s)}catch(l){throw new p(`[state-file] State file ${e} has an invalid 'serverUrl': ${String(l)}`)}return{agentId:r,agentToken:o,protocolVersion:a,serverUrl:s,tokenRotatedAt:Bi(n,e)}}i(ji,"validateState");function Bi(t,e){let n=t.tokenRotatedAt;if(n==null)return null;if(typeof n!="string"||n==="")throw new p(`[state-file] State file ${e} has an invalid 'tokenRotatedAt' (expected a non-empty ISO string, null, or the key to be absent on a file written before agent token rotation shipped).`);return n}i(Bi,"readTokenRotatedAt");var qn=u("token-store");function M(t){return jn(t)}i(M,"loadAgentIdentity");function ie(t,e){Bn(t,e)}i(ie,"saveAgentIdentity");function Hn(t){let e=qe(t),n=Ut(t),r=Vn(n,"temporary state file"),o=Vn(e,"identity");if(!o&&!r){qn.info("Agent identity wipe: no state file to remove",{filePath:e,tmpPath:n});return}qn.warn("Agent identity wiped \u2014 this agent was revoked and must be re-enrolled",{filePath:e,tmpPath:n,removedState:o,removedTmp:r})}i(Hn,"wipeAgentIdentity");function Vn(t,e){try{return qi(t),!0}catch(n){if(Vi(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(Vn,"removeCredentialFile");function Vi(t){return t.code==="ENOENT"}i(Vi,"isFileNotFound");var Jn="extension-bundle.json";function Ve(t,e){return Kn(t)===Kn(e)}i(Ve,"isSameDeployment");function Kn(t){let e=new URL(t);return`${e.origin}${e.pathname.replace(/\/+$/,"")}`}i(Kn,"normalizeDeployment");function Wn(t){let{envUrl:e,envTokenPresent:n,stateDir:r}=t;if(e!==void 0)return X(e),{url:e,source:"env"};if(n){let s=Mt();if(s!==null)return{url:s,source:"bundle"};throw new p(`[config] PROGON_SERVER_URL is not set, and PROGON_AGENT_TOKEN names no deployment \u2014 a pgat_ token is only meaningful at the backend that minted it, and this daemon will not guess which one that is.
9
+ This build carries no ${Jn} either, so it was not built for a particular deployment \u2014 that is what a source checkout is, and an installed progon-agent from npm always has one.
9
10
  The state file in ${r} is deliberately NOT consulted on this path: PROGON_AGENT_TOKEN is the rotation and recovery mechanism, and it must not start depending on the very file an operator sets it to recover from.
10
11
  Set PROGON_SERVER_URL to the deployment this token belongs to; or unset PROGON_AGENT_TOKEN, after which an enrolled machine takes both its credential and its server from that state file.
11
- See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`);let i=G(r);if(i===null)throw new Error(`[config] This machine is not enrolled and PROGON_SERVER_URL is not set, so the agent does not know which Progon deployment to talk to. There is no state file in ${r}.
12
+ See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`)}let o=M(r);if(o!==null)return{url:o.serverUrl,source:"state_file"};let a=Mt();if(a!==null)return{url:a,source:"bundle"};throw new p(`[config] This machine is not enrolled and no deployment is configured, so the agent does not know which Progon to talk to \u2014 none of the three places it looks names one.
13
+ PROGON_SERVER_URL is not set; there is no state file in ${r}; and this build carries no ${Jn}, so it was not built for a particular deployment \u2014 that is what a source checkout is, and an installed progon-agent from npm always has one.
12
14
  Enroll this machine \u2014 'progon-agent enroll --server <url>' (approved in a browser), or 'progon-agent enroll <code> --server <url>' with a code from Progon (Settings \u2192 Agents). Enrollment persists the server together with the credential, so every later command finds it with no environment at all.
13
15
  If this machine WAS enrolled with PROGON_RUNNER_STATE_DIR set, set the same variable again \u2014 that directory is where its credential and its server are.
14
16
  Setting PROGON_SERVER_URL on its own names a server but no agent: it is what an 'enroll' needs, and it is enough for 'start' only alongside PROGON_AGENT_TOKEN.
15
- See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`);return{url:i.serverUrl,source:"state_file"}}o(qn,"resolveServerUrl");function Te(t){let e=process.env[t];return e!==void 0&&e!==""?e:void 0}o(Te,"getOptional");function Bn(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.`)}o(Bn,"getOptionalBool");var Be="progon-agent";function Ni(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 qe(n,"Library","Application Support",Be);case"linux":{let r=e.XDG_STATE_HOME;if(r===void 0||r==="")return qe(n,".local","state",Be);if(!Hn(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 qe(r,Be)}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 qe(r,Be)}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.`)}}o(Ni,"resolveDefaultStateDir");function re(){An(process.env),Pn(process.env);let t=process.env.PROGON_AGENT_TOKEN;if(t==="")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 e=t;e!==void 0&&ke(e);let n=Te("PROGON_RUNNER_STATE_DIR")??Ni(process.platform,process.env,Pi()),r=qn({envUrl:Te("PROGON_SERVER_URL"),envTokenPresent:e!==void 0,stateDir:n}),i=Te("PROGON_AGENT_EXTENSION_DIST");if(i!==void 0&&!Hn(i))throw new Error(`[config] PROGON_AGENT_EXTENSION_DIST must be an absolute path, got: ${JSON.stringify(i)}. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`);let a=Te("PROGON_AGENT_ENROLL_CODE");if(a!==void 0&&a.length<32)throw new Error(`[config] PROGON_AGENT_ENROLL_CODE is shorter than the ${32} characters an enrollment code has (got ${a.length}). Copy the whole code from the agent's enrollment dialog. See docs/working/local-agent-v1/CONTRACT-la.md \xA75.1.`);return{serverUrl:r.url,serverUrlSource:r.source,initialToken:e,stateDir:n,extensionDistOverride:i,headfulOverride:Bn("PROGON_AGENT_HEADFUL",!1),allowInsecureHttps:Bn("PROGON_AGENT_ALLOW_INSECURE_HTTPS",!1),enrollmentCode:a,nodeEnv:Te("NODE_ENV")??"production"}}o(re,"loadConfig");function Ae(t,e,n){process.stderr.write(JSON.stringify({level:t,module:"process-guards",msg:e,...n})+`
16
- `)}o(Ae,"writeLine");function Jn(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}}o(Jn,"describeError");function Vn(t,e,n){Ae("fatal",`Unhandled ${t} \u2014 terminating the daemon`,{event:t,...Jn(e),...n})}o(Vn,"writeFatalLine");function Kn(){process.on("uncaughtException",(t,e)=>{Vn("uncaughtException",t,{origin:e}),process.exit(1)}),process.on("unhandledRejection",t=>{Vn("unhandledRejection",t,{}),process.exit(1)})}o(Kn,"installProcessGuards");function Wn(t){let e=!1,n=o(r=>{if(e){Ae("info","Shutdown already in progress \u2014 signal ignored",{signal:r});return}e=!0,Ae("info","Signal received \u2014 shutting down",{signal:r}),(async()=>{try{await t(r)}catch(i){Ae("fatal","Shutdown hook failed \u2014 the daemon may leave resources behind",{signal:r,...Jn(i)}),process.exit(1)}Ae("info","Shutdown complete",{signal:r}),process.exit(0)})()},"handle");process.on("SIGTERM",n),process.on("SIGINT",n)}o(Wn,"installShutdownHandlers");import{chmodSync as Mi,cpSync as Ui,mkdirSync as $i,readdirSync as Fi,renameSync as ji,rmSync as Gt,statSync as zn,writeFileSync as qi}from"node:fs";import{dirname as Bi,join as oe}from"node:path";import{fileURLToPath as Hi}from"node:url";import{statSync as Ci}from"node:fs";import{dirname as Di,join as Li}from"node:path";var Yn="package.json";function Xn(t){let e=t;for(;;){if(Gi(e))return e;let n=Di(e);if(n===e)throw new Error(`[package-root] No ${Yn} was found in ${t} or in any of its parent directories, so the root of the package this file belongs to cannot be determined. This is a packaging defect, not a configuration one: the module asking is supposed to be running from inside an installed or checked-out package.`);e=n}}o(Xn,"findPackageRoot");function Gi(t){try{return Ci(Li(t,Yn)),!0}catch(e){if(typeof e=="object"&&e!==null){let n=e.code;if(n==="ENOENT"||n==="ENOTDIR")return!1}throw e}}o(Gi,"holdsPackageManifest");var He=u("extension-dist"),Vi="extension-dist",er="extension-dist",tr=`${er}.tmp-`,Mt="agent-manifest.json",Zn="manifest.json";function Ji(){return Xn(Bi(Hi(import.meta.url)))}o(Ji,"packageRoot");function Ki(){return Wi(oe(Ji(),Vi))}o(Ki,"resolveBundledExtensionSource");function Wi(t){let e;try{e=zn(t)}catch(r){throw Qn(r)?new Error(Lt(t,"the directory does not exist"),{cause:r}):r}if(!e.isDirectory())throw new Error(Lt(t,"that path is not a directory"));let n=oe(t,Zn);try{zn(n)}catch(r){throw Qn(r)?new Error(Lt(t,`it holds no ${Zn}`),{cause:r}):r}return t}o(Wi,"assertBundledExtensionSource");function Qn(t){if(typeof t!="object"||t===null)return!1;let e=t.code;return e==="ENOENT"||e==="ENOTDIR"}o(Qn,"isAbsentPathError");function Lt(t,e){return`[extension-dist] No extension dist is bundled in this package (${t}): ${e}.
17
+ See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`)}i(Wn,"resolveServerUrl");function xe(t){let e=process.env[t];return e!==void 0&&e!==""?e:void 0}i(xe,"getOptional");function Yn(t,e){let n=process.env[t];if(n===void 0||n==="")return e;let r=n.trim().toLowerCase();if(r==="true"||r==="1")return!0;if(r==="false"||r==="0")return!1;throw new p(`[config] Environment variable ${t} must be one of true/false/1/0, got: ${JSON.stringify(n)}. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`)}i(Yn,"getOptionalBool");var Je="progon-agent";function Ji(t,e,n){if(n==="")throw new p("[config] Cannot resolve the default state directory: the current user has no home directory (os.homedir() returned an empty string \u2014 happens in service/container contexts without HOME). Set PROGON_RUNNER_STATE_DIR explicitly.");switch(t){case"darwin":return He(n,"Library","Application Support",Je);case"linux":{let r=e.XDG_STATE_HOME;if(r===void 0||r==="")return He(n,".local","state",Je);if(!Xn(r))throw new p(`[config] XDG_STATE_HOME must be an absolute path (XDG Base Directory specification), got: ${JSON.stringify(r)}. Fix the variable or set PROGON_RUNNER_STATE_DIR explicitly.`);return He(r,Je)}case"win32":{let r=e.APPDATA;if(r===void 0||r==="")throw new p("[config] %APPDATA% is not set, so the default Windows state directory cannot be resolved. Set PROGON_RUNNER_STATE_DIR explicitly.");return He(r,Je)}default:throw new p(`[config] No default state directory is defined for platform ${JSON.stringify(t)} (supported: darwin, linux, win32 \u2014 CONTRACT-la \xA75.1, \xA710.3). Set PROGON_RUNNER_STATE_DIR explicitly.`)}}i(Ji,"resolveDefaultStateDir");function ae(){Pn(process.env),Ln(process.env);let t=process.env.PROGON_AGENT_TOKEN;if(t==="")throw new p("[config] PROGON_AGENT_TOKEN is set but empty. To use the persisted state-file token, unset this variable entirely. To rotate the token, set it to the new pgat_ token. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.");let e=t;e!==void 0&&Ae(e);let n=xe("PROGON_RUNNER_STATE_DIR")??Ji(process.platform,process.env,Hi()),r=Wn({envUrl:xe("PROGON_SERVER_URL"),envTokenPresent:e!==void 0,stateDir:n}),o=xe("PROGON_AGENT_EXTENSION_DIST");if(o!==void 0&&!Xn(o))throw new p(`[config] PROGON_AGENT_EXTENSION_DIST must be an absolute path, got: ${JSON.stringify(o)}. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`);let a=xe("PROGON_AGENT_ENROLL_CODE");if(a!==void 0&&a.length<32)throw new p(`[config] PROGON_AGENT_ENROLL_CODE is shorter than the ${32} characters an enrollment code has (got ${a.length}). Copy the whole code from the agent's enrollment dialog. See docs/working/local-agent-v1/CONTRACT-la.md \xA75.1.`);return{serverUrl:r.url,serverUrlSource:r.source,initialToken:e,stateDir:n,extensionDistOverride:o,headfulOverride:Yn("PROGON_AGENT_HEADFUL",!1),allowInsecureHttps:Yn("PROGON_AGENT_ALLOW_INSECURE_HTTPS",!1),enrollmentCode:a,nodeEnv:xe("NODE_ENV")??"production"}}i(ae,"loadConfig");function Ie(t,e,n){process.stderr.write(JSON.stringify({level:t,module:"process-guards",msg:e,...n})+`
18
+ `)}i(Ie,"writeLine");function Zn(t){let e=t instanceof Error?t.message:String(t),n=t instanceof Error?t.stack:void 0;return{err:G(e),stack:n!==void 0?G(n):void 0}}i(Zn,"describeError");function zn(t,e,n){Ie("fatal",`Unhandled ${t} \u2014 terminating the daemon`,{event:t,...Zn(e),...n})}i(zn,"writeFatalLine");function Qn(){process.on("uncaughtException",(t,e)=>{zn("uncaughtException",t,{origin:e}),process.exit(1)}),process.on("unhandledRejection",t=>{zn("unhandledRejection",t,{}),process.exit(1)})}i(Qn,"installProcessGuards");function er(t){let e=!1,n=i(r=>{if(e){Ie("info","Shutdown already in progress \u2014 signal ignored",{signal:r});return}e=!0,Ie("info","Signal received \u2014 shutting down",{signal:r}),(async()=>{try{await t(r)}catch(o){Ie("fatal","Shutdown hook failed \u2014 the daemon may leave resources behind",{signal:r,...Zn(o)}),process.exit(1)}Ie("info","Shutdown complete",{signal:r}),process.exit(0)})()},"handle");process.on("SIGTERM",n),process.on("SIGINT",n)}i(er,"installShutdownHandlers");import{chmodSync as Ki,cpSync as Wi,mkdirSync as Yi,readdirSync as Xi,renameSync as zi,rmSync as Ft,statSync as tr,writeFileSync as Zi}from"node:fs";import{dirname as Qi,join as se}from"node:path";import{fileURLToPath as ea}from"node:url";var Ke=u("extension-dist"),ta="extension-dist",rr="extension-dist",or=`${rr}.tmp-`,jt="agent-manifest.json",nr="manifest.json";function na(){return je(Qi(ea(import.meta.url)))}i(na,"packageRoot");function ra(){return oa(se(na(),ta))}i(ra,"resolveBundledExtensionSource");function oa(t){let e;try{e=tr(t)}catch(r){throw z(r)?new Error($t(t,"the directory does not exist"),{cause:r}):r}if(!e.isDirectory())throw new Error($t(t,"that path is not a directory"));let n=se(t,nr);try{tr(n)}catch(r){throw z(r)?new Error($t(t,`it holds no ${nr}`),{cause:r}):r}return t}i(oa,"assertBundledExtensionSource");function $t(t,e){return`[extension-dist] No extension dist is bundled in this package (${t}): ${e}.
17
19
  This package was built WITHOUT the bundling step. Run 'npm run bundle:extension' in the agent package (it copies a built qa-extension dist in; set PROGON_EXTENSION_DIST_SRC to point at that dist if it is not the sibling checkout), then reinstall or restart the daemon.
18
- For a dev or E2E stand you can instead set PROGON_AGENT_EXTENSION_DIST to an already agent-mode dist, which bypasses the bundled copy entirely (CONTRACT-la \xA78).`}o(Lt,"bundledMissingMessage");function Yi(t){let{stateDir:e,agentId:n}=t;if(n==="")throw new Error(`[extension-dist] agentId is required: ${Mt} carries it (CONTRACT-la \xA71 D-C) and this module does not invent identity.`);let r=t.sourceDir??Ki(),i=oe(e,er),a=oe(e,`${tr}${process.pid}`);return $i(e,{recursive:!0,mode:448}),zi(e),Gt(a,{recursive:!0,force:!0}),Ui(r,a,{recursive:!0}),Mi(a,448),Xi(a,n),Gt(i,{recursive:!0,force:!0}),ji(a,i),He.info("Agent-mode extension dist prepared",{extensionDist:i,sourceDir:r,agentId:n,protocolVersion:1}),i}o(Yi,"prepareAgentExtensionDist");function Xi(t,e){let n={agentMode:!0,agentId:e,protocolVersion:1};qi(oe(t,Mt),JSON.stringify(n,null,2)+`
19
- `,"utf8")}o(Xi,"writeAgentManifest");function zi(t){let e;try{e=Fi(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(tr))continue;let r=oe(t,n.name);try{Gt(r,{recursive:!0,force:!0}),He.warn("Removed a leftover extension-dist staging directory",{leftover:r})}catch(i){He.error("Failed to remove a leftover extension-dist staging directory",{leftover:r,err:i instanceof Error?i.message:String(i)})}}}o(zi,"removeLeftoverStagingDirs");function nr(t){if(t.overridePath!==void 0)return He.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 ${Mt} must name the agent the browser reports as (CONTRACT-la \xA71 D-C).
20
- 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 Yi({stateDir:t.stateDir,agentId:t.agentId})}o(nr,"resolveExtensionDist");import{fetch as ea}from"undici";var S=class extends Error{static{o(this,"GatewayError")}operation;constructor(e,n,r){super(n,{cause:r}),this.name=new.target.name,this.operation=e}},M=class extends S{static{o(this,"GatewayTransportError")}constructor(e,n,r){super(e,`[gateway] ${e} failed before a response was received: ${n}`,r)}},v=class extends S{static{o(this,"GatewayHttpError")}status;errorCode;params;constructor(e,n,r,i,a){super(e,`[gateway] ${e} refused with HTTP ${n}: ${a}`),this.status=n,this.errorCode=r,this.params=i}},ie=class extends v{static{o(this,"GatewayUnauthorizedError")}},_=class extends v{static{o(this,"TokenSupersededError")}},y=class extends S{static{o(this,"TerminalSignalError")}signal;constructor(e,n,r){super(e,`[gateway] agent revoked (${n}) during ${e}: ${r}`),this.signal=n}},Ve=class extends v{static{o(this,"EnrollmentCodeRejectedError")}},Ie=class extends v{static{o(this,"ProtocolVersionMismatchError")}},ae=class extends v{static{o(this,"RunNotClaimableError")}},Y=class extends v{static{o(this,"RunNotFoundError")}},U=class extends S{static{o(this,"GatewayResponseSchemaError")}constructor(e,n,r){super(e,`[gateway] ${e} returned a body that violates the contract: ${n}`,r)}};var rr=u("gateway-http");async function X(t){let e={accept:"application/json"};t.agentToken!==null&&(e.authorization=`Bearer ${t.agentToken}`),t.body!==null&&(e["content-type"]="application/json"),rr.debug("Gateway request",{operation:t.operation,method:t.method,url:t.url.toString()});let n;try{n=await t.fetchImpl(t.url,{method:t.method,headers:e,body:t.body===null?void 0:JSON.stringify(t.body),signal:t.signal})}catch(i){throw new M(t.operation,or(i),i)}let r;try{r=await n.text()}catch(i){throw new M(t.operation,or(i),i)}if(!n.ok){let i=Zi(n.status,r);throw rr.debug("Gateway request refused",{operation:t.operation,status:i.status,errorCode:i.errorCode}),t.mapHttpError(i)}try{return JSON.parse(r)}catch(i){throw new U(t.operation,`the ${n.status} response body is not valid JSON`,i)}}o(X,"executeGatewayRequest");function P(t,e){if(e.success)return e.data;throw new U(t,Qi(e.error),e.error)}o(P,"parseGatewayBody");function Zi(t,e){let n;try{n=JSON.parse(e)}catch{return{status:t,errorCode:null,params:null,message:Ut}}if(typeof n!="object"||n===null||Array.isArray(n))return{status:t,errorCode:null,params:null,message:Ut};let r=n,i=r.error_code,a=r.params,s=r.message;return{status:t,errorCode:typeof i=="string"?i:null,params:typeof a=="object"&&a!==null&&!Array.isArray(a)?a:null,message:typeof s=="string"?L(s):Ut}}o(Zi,"readErrorEnvelope");var Ut="the response body carried no Progon error envelope";function or(t){return L(t instanceof Error?t.message:String(t))}o(or,"describeCause");function Qi(t){let e=t.issues;if(!Array.isArray(e)||e.length===0)return"the response body failed schema validation (the validator reported no issue list)";let n=e.map(r=>{let i=r.path;return!Array.isArray(i)||i.length===0?"<root>":i.map(a=>String(a)).join(".")});return`${e.length} schema violation(s) at: ${n.join(", ")}`}o(Qi,"summarizeSchemaViolation");var se=class extends v{static{o(this,"EnrollmentSlowDownError")}retryAfterSec;constructor(e,n,r,i,a,s){super(e,n,r,i,a),this.retryAfterSec=s}},le=class extends v{static{o(this,"EnrollmentAccessDeniedError")}},de=class extends v{static{o(this,"EnrollmentRequestExpiredError")}},ce=class extends v{static{o(this,"EnrollmentAlreadyCompletedError")}},ue=class extends v{static{o(this,"EnrollmentRequestInvalidError")}};function ir(t){return t.status===401&&t.errorCode==="agent_enroll.invalid_code"?x(Ve,"enroll",t):t.status===409&&t.errorCode==="agent_enroll.protocol_version"?x(Ie,"enroll",t):C("enroll",t)}o(ir,"mapEnrollError");function ar(t){return t.status===409&&t.errorCode==="agent_enroll.protocol_version"?x(Ie,"enrollment_request_create",t):C("enrollment_request_create",t)}o(ar,"mapEnrollmentRequestCreateError");function sr(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 se("enrollment_request_poll",t.status,t.errorCode,t.params,t.message,n)}return t.status===403&&t.errorCode==="agent_enroll.access_denied"?x(le,"enrollment_request_poll",t):t.status===410&&t.errorCode==="agent_enroll.expired"?x(de,"enrollment_request_poll",t):t.status===410&&t.errorCode==="agent_enroll.already_completed"?x(ce,"enrollment_request_poll",t):t.status===401&&t.errorCode==="agent_enroll.invalid_request"?x(ue,"enrollment_request_poll",t):C("enrollment_request_poll",t)}o(sr,"mapEnrollmentRequestPollError");function lr(t){return C("enrollment_request_cancel",t)}o(lr,"mapEnrollmentRequestCancelError");function dr(t){return me("poll_desired_state",t,()=>C("poll_desired_state",t))}o(dr,"mapPollDesiredStateError");function cr(t){return me("claim",t,()=>t.status===409&&t.errorCode==="run.not_claimable"?x(ae,"claim",t):t.status===404?x(Y,"claim",t):C("claim",t))}o(cr,"mapClaimError");function ur(t){return me("fail",t,()=>t.status===404?x(Y,"fail",t):C("fail",t))}o(ur,"mapFailError");function mr(t){return me("token_status",t,()=>C("token_status",t))}o(mr,"mapTokenStatusError");function pr(t){return me("token_rotate",t,()=>C("token_rotate",t))}o(pr,"mapTokenRotateError");function hr(t){return me("declare_capabilities",t,()=>C("declare_capabilities",t))}o(hr,"mapDeclareCapabilitiesError");function me(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(_,t,e):e.status===401?x(ie,t,e):n()}o(me,"bearerRoute");function x(t,e,n){return new t(e,n.status,n.errorCode,n.params,n.message)}o(x,"named");function C(t,e){return x(v,t,e)}o(C,"generic");var Je=[...Qt,en,tn];import{z}from"zod";var gr=z.object({rotationDue:z.boolean(),tokenRotatedAt:z.string().nullable(),anchorAt:z.string(),intervalDays:z.number().int()}),fr=z.object({agentToken:z.string().regex(Q)});var Ke=u("gateway-client"),ta="/api/agent-gateway";function N(t,e){return new URL(`${t.replace(/\/+$/,"")}${ta}${e}`)}o(N,"buildGatewayUrl");var yr=3e5,Er=1e4,wr={headersTimeout:yr,bodyTimeout:yr,connect:{timeout:Er}};function na(){let t=On(process.env);return Tn(Ct(process.env),t===void 0?wr:{...wr,connect:{timeout:Er,ca:t}},t)}o(na,"buildGatewayDispatcher");var $t,Xe=o((t,e)=>{if($t===void 0){let n=na();$t=o((r,i)=>ea(r,{...i,dispatcher:n}),"defaultGatewayFetch")}return $t(t,e)},"pinnedGatewayFetch"),We=class{static{o(this,"GatewayEnrollmentClient")}serverUrl;machine;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.machine=e.machine,this.fetchImpl=e.fetchImpl??Xe}async enroll(e){let n={...this.machine,enrollmentCode:e,protocolVersion:1},r=await X({operation:"enroll",method:"POST",url:N(this.serverUrl,"/enroll"),agentToken:null,body:n,signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:ir}),i=P("enroll",De.safeParse(r));return Ke.info("Agent enrolled",{agentId:i.agentId,pollWaitSec:i.pollWaitSec,protocolVersion:i.protocolVersion}),i}},Ye=class{static{o(this,"GatewayClient")}serverUrl;agentToken;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.agentToken=e.agentToken,this.fetchImpl=e.fetchImpl??Xe}async authenticatedRequest(e){return X({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:dr}),i=P("poll_desired_state",cn.safeParse(r));if(i.agent.revoked)throw new y("poll_desired_state","desired_state_snapshot","the desired-state snapshot reports this agent as revoked");return i}async claimRun(e){let n=await this.authenticatedRequest({operation:"claim",method:"POST",url:N(this.serverUrl,`/runs/${encodeURIComponent(e)}/claim`),body:{capabilities:Je},signal:void 0,mapHttpError:cr});return P("claim",fn.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:ur}),i=P("fail",pn.safeParse(r));return Ke.info("Reported run failure to the gateway",{runId:e,reason:n.reason,status:i.status}),i}async getTokenRotationStatus(e){let n=await this.authenticatedRequest({operation:"token_status",method:"GET",url:N(this.serverUrl,"/token"),body:null,signal:e?.signal,mapHttpError:mr});return P("token_status",gr.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:pr});return P("token_rotate",fr.safeParse(n))}async declareCapabilities(e){await this.authenticatedRequest({operation:"declare_capabilities",method:"POST",url:N(this.serverUrl,"/capabilities"),body:{capabilities:Je},signal:e?.signal,mapHttpError:hr}),Ke.info("Capabilities declared",{capabilities:Je})}useAgentToken(e){this.agentToken=e,Ke.info("Adopted a rotated agent token for all subsequent gateway requests")}};var ra=u("debug-env-guard"),oa=["pw:protocol","pw:api"];function ia(t){return t.replace(/[\\^$.|?+()[\]{}]/g,"\\$&")}o(ia,"escapeRegExp");function vr(t){if(t.startsWith("-"))return!1;let e=`^${t.split("*").map(ia).join(".*?")}$`,n=new RegExp(e);return oa.some(r=>n.test(r))}o(vr,"enablesPlaywright");function aa(){let t=process.env.DEBUG;if(t===void 0||t==="")return[];let e=t.split(/[\s,]+/).map(i=>i.trim()).filter(i=>i!==""),n=e.filter(i=>vr(i));if(n.length===0)return[];let r=e.filter(i=>!vr(i));return r.length===0?delete process.env.DEBUG:process.env.DEBUG=r.join(","),ra.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}o(aa,"sanitizePlaywrightDebugEnv");aa();import{statSync as Sr}from"node:fs";import{isAbsolute as la,join as da}from"node:path";import{createRequire as sa}from"node:module";var $=sa(import.meta.url)("playwright-core"),ze=$.chromium,Tc=$.firefox,Ac=$.webkit,Ic=$.selectors,xc=$.devices,Oc=$.errors,Pc=$.request,Nc=$._electron,Cc=$._android;var Ze="chromium";var _r="instances",Qe="instance.json";async function Rr(t){return ze.launchPersistentContext(t.userDataDir,{headless:!t.headful,channel:Ze,ignoreHTTPSErrors:t.allowInsecureHttps,args:[`--disable-extensions-except=${t.extensionDist}`,`--load-extension=${t.extensionDist}`,"--no-first-run","--no-default-browser-check"]})}o(Rr,"launchExtensionContext");function ca(t){let e=t.browser();if(e===null)throw new Error("context.browser() returned null for a persistent context \u2014 the browser handle is unusable, so neither its PID nor its version can be read");return e}o(ca,"requireBrowser");function br(t){return ca(t).version()}o(br,"readChromeVersion");async function kr(t,e){let n,r=new Promise(i=>{n=setTimeout(()=>i({settled:"timeout"}),e)});try{return await Promise.race([t.close().then(()=>({settled:"closed"}),i=>({settled:"rejected",error:i})),r])}finally{n!==void 0&&clearTimeout(n)}}o(kr,"raceClose");function Tr(t){if(!la(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=Sr(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=da(t,"manifest.json");try{Sr(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})}}o(Tr,"assertUsableExtensionDist");var ua=u("worker-evaluate"),Ft=class extends Error{static{o(this,"EvaluateDeadlineError")}operation;timeoutMs;constructor(e,n){super(`[runtime] ${e}: the extension service worker did not answer worker.evaluate within ${n}ms \u2014 the worker is wedged or gone`),this.name="EvaluateDeadlineError",this.operation=e,this.timeoutMs=n}};async function q(t){let e=t.evaluate(),n=!1;e.catch(a=>{n&&ua.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,i=new Promise((a,s)=>{r=setTimeout(()=>{n=!0,s(new Ft(t.operation,t.timeoutMs))},t.timeoutMs)});try{return await Promise.race([e,i])}finally{r!==void 0&&clearTimeout(r)}}o(q,"evaluateWithDeadline");var Ar="accessToken",Ir="refreshToken";async function Or(t,e){await q({operation:"write the run session into chrome.storage.local",timeoutMs:1e4,evaluate:o(()=>t.evaluate(([r,i,a,s])=>new Promise(l=>chrome.storage.local.set({[r]:a,[i]:s},()=>l())),[Ar,Ir,e.accessToken,e.refreshToken]),"evaluate")});let n=await q({operation:"read the run session back out of chrome.storage.local",timeoutMs:1e4,evaluate:o(()=>t.evaluate(([r,i])=>new Promise(a=>chrome.storage.local.get([r,i],s=>{let l=s[r],d=s[i];a({accessTokenLength:typeof l=="string"?l.length:null,refreshTokenLength:typeof d=="string"?d.length:null})})),[Ar,Ir]),"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}o(Or,"seedRunSession");function xr(t){return JSON.stringify(Object.keys(t).sort().map(e=>[e,t[e]]))}o(xr,"canonicalise");async function Pr(t,e){await q({operation:`write the command envelope to chrome.storage.local['${Se}']`,timeoutMs:1e4,evaluate:o(()=>t.evaluate(([a,s])=>new Promise(l=>chrome.storage.local.set({[a]:s},()=>l())),[Se,e]),"evaluate")});let n=await q({operation:"read the command envelope back out of chrome.storage.local",timeoutMs:1e4,evaluate:o(()=>t.evaluate(a=>new Promise(s=>chrome.storage.local.get([a],l=>{let d=l[a];s(d===void 0?null:d)})),Se),"evaluate")});if(typeof n!="object"||n===null)throw new Error(`command envelope read-back returned ${JSON.stringify(n)} \u2014 chrome.storage.local['${Se}'] does not hold the envelope`);let r=xr({...e}),i=xr(n);if(r!==i)throw new Error(`command envelope read-back mismatch: wrote ${r}, read ${i}`)}o(Pr,"seedCommandEnvelope");async function pa(t,e,n){let r=await q({operation:`read chrome.storage.local['${Ce}']`,timeoutMs:n,evaluate:o(()=>t.evaluate(a=>new Promise(s=>chrome.storage.local.get([a],l=>{let d=l[a];s(d===void 0?null:d)})),Ce),"evaluate")});if(r===null)return{kind:"absent"};let i=un.safeParse(r);return i.success?i.data.runId!==e?{kind:"other_run",detail:`the ack under that key belongs to run ${i.data.runId}`}:{kind:"ack",ack:i.data}:{kind:"invalid",detail:`the value under that key failed agentCommandAckSchema: ${String(i.error)}`}}o(pa,"pollCommandAck");async function Nr(t,e,n){let r=Date.now()+n,i="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 ${i}. chrome.storage.local['${Ce}'] is the only success signal (CONTRACT-la \xA75.4).`);let s=t.serviceWorkers()[0];if(s===void 0)i="the context exposed no service worker while polling (evicted, restarting)";else{let l;try{l=await pa(s,e,a)}catch(d){i=`the last poll failed: ${d instanceof Error?d.message:String(d)}`,l={kind:"invalid",detail:i}}if(l.kind==="ack")return l.ack;l.kind!=="absent"&&(i=l.detail)}await new Promise(l=>setTimeout(l,250))}}o(Nr,"waitForCommandAck");import tt from"node:os";import{createRequire as ha}from"node:module";var Cr=ha(import.meta.url);function ga(){let t=Cr.resolve("playwright-core/package.json"),e=Cr(t);if(typeof e!="object"||e===null)throw new Error(`[runtime] ${t} did not parse into an object.`);let n=e.version;if(typeof n!="string"||n==="")throw new Error(`[runtime] ${t} declares no version string.`);return n}o(ga,"readPlaywrightCoreVersion");function Dr(t){return{node:process.version,platform:`${tt.platform()} ${tt.release()} ${tt.arch()}`,cpus:tt.cpus().length,playwrightCore:ga(),chromiumExecutable:ze.executablePath(),channel:Ze,extensionDist:t}}o(Dr,"buildEnvFingerprint");import{mkdirSync as jr,readdirSync as Oa,readFileSync as Pa,renameSync as Na,rmSync as qt,writeFileSync as Ca}from"node:fs";import{join as xe}from"node:path";var B=class extends Error{static{o(this,"RuntimeLaunchError")}runId;stage;failReason="launch_error";constructor(e,n,r,i){super(`[runtime] launch failed at stage ${n} for run ${e}: ${r}`,{cause:i}),this.name="RuntimeLaunchError",this.runId=e,this.stage=n}};function Lr(t){let e=new Set,n=t;for(;n instanceof Error&&!e.has(n)&&(e.add(n),n.cause!==void 0);)n=n.cause;return n instanceof Error?n.message:String(n)}o(Lr,"deepestCauseMessage");var H=class extends Error{static{o(this,"InstanceAlreadyRegisteredError")}runId;userDataDir;constructor(e,n,r){super(`[runtime] refusing to launch run ${e}: instance directory already exists at ${n}. Either this run is already live, or a previous daemon left it behind (the startup sweep clears leftovers \u2014 CONTRACT-la \xA715 A3, gate G-3).`,{cause:r}),this.name="InstanceAlreadyRegisteredError",this.runId=e,this.userDataDir=n}},nt=class extends Error{static{o(this,"RuntimeBusyError")}requestedRunId;activeRunId;constructor(e,n){super(`[runtime] refusing to launch run ${e}: this runtime already owns the browser instance for run ${n}. An agent runs at most one run at a time (CONTRACT-la \xA73.1, \xA715 A3).`),this.name="RuntimeBusyError",this.requestedRunId=e,this.activeRunId=n}};import{execFile as ya}from"node:child_process";import{promisify as wa}from"node:util";import{setTimeout as $r}from"node:timers/promises";var rt=wa(ya),ot={timeout:5e3};function Fr(t){if(typeof t!="object"||t===null)return null;let e=t;return typeof e.code!="number"?null:{code:e.code,stdout:typeof e.stdout=="string"?e.stdout:"",stderr:typeof e.stderr=="string"?e.stderr:""}}o(Fr,"asExecFailure");function Ea(t){let e=[];for(let n of t.split(`
21
- `)){let r=n.trim();if(r==="")continue;let i=Number(r);!Number.isInteger(i)||i===process.pid||e.push(i)}return e}o(Ea,"parsePidLines");var jt="--user-data-dir=",va=new Set([" "," ",'"',"'"]),_a=new Set([" "," ",'"',"'"]);function Sa(t){return t.replace(/[\\^$.|?*+()[\]{}]/g,"\\$&")}o(Sa,"escapeEre");function Ra(t){return`(^|[[:space:]'"])${Sa(`${jt}${t}`)}([[:space:]'"]|$)`}o(Ra,"buildAnchorPattern");function ba(t,e){let n=t.toLowerCase(),r=`${jt}${e}`.toLowerCase();for(let i=n.indexOf(r);i!==-1;i=n.indexOf(r,i+1)){let a=i===0?void 0:n[i-1],s=n[i+r.length],l=a===void 0||va.has(a),d=s===void 0||_a.has(s);if(l&&d)return!0}return!1}o(ba,"matchesAnchor");async function ka(t){try{let{stdout:e}=await rt("pgrep",["-f",Ra(t)],ot);return Ea(e)}catch(e){let n=Fr(e);if(n!==null&&n.code===1&&n.stdout.trim()==="")return[];throw e}}o(ka,"discoverPosix");async function Gr(t){let n=`Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Where-Object { $_.ProcessId -ne $PID -and $_.CommandLine -and $_.CommandLine.Contains('${`${jt}${t}`.replace(/'/g,"''")}') } | ForEach-Object { "$($_.ProcessId)\`t$($_.CommandLine)" }`,{stdout:r}=await rt("powershell.exe",["-NoProfile","-NonInteractive","-Command",n],ot),i=[];for(let a of r.split(`
22
- `)){let s=a.indexOf(" ");if(s===-1)continue;let l=Number(a.slice(0,s).trim()),d=a.slice(s+1);!Number.isInteger(l)||l===process.pid||ba(d,t)&&i.push(l)}return i}o(Gr,"discoverWin32");async function Mr(){let{stdout:t}=await rt("ps",["-A","-o","pid=,ppid=,pgid="],ot),e=[];for(let n of t.split(`
23
- `)){let r=n.trim().split(/\s+/);if(r.length<3)continue;let[i,a,s]=r,l=Number(i),d=Number(a),m=Number(s);!Number.isInteger(l)||!Number.isInteger(d)||!Number.isInteger(m)||e.push({pid:l,ppid:d,pgid:m})}return e}o(Mr,"readProcessTable");function Ta(t,e){let n=new Map;for(let d of t){let m=n.get(d.ppid);m===void 0?n.set(d.ppid,[d.pid]):m.push(d.pid)}let r=new Set(e),i=[...e];for(let d=i.pop();d!==void 0;d=i.pop()){let m=n.get(d);if(m!==void 0)for(let f of m)r.has(f)||(r.add(f),i.push(f))}let a=t.find(d=>d.pid===process.pid),s=a===void 0?null:a.pgid,l=new Set;for(let d of t)r.has(d.pid)&&(d.pgid<=0||s!==null&&d.pgid===s||l.add(d.pgid));return r.delete(process.pid),{members:[...r],groups:[...l]}}o(Ta,"expandTree");function Aa(t){try{return process.kill(t,"SIGKILL"),"signalled"}catch(e){if(typeof e=="object"&&e!==null&&e.code==="ESRCH")return"already_gone";throw e}}o(Aa,"sigkill");async function it(t){return process.platform==="win32"?xa(t):Ia(t)}o(it,"killProcessTree");async function Ia(t){let e=await ka(t);if(e.length===0)return{platform:process.platform,userDataDir:t,discoveredPids:[],signalledPids:[],survivorPids:[]};let n=await Mr(),{members:r,groups:i}=Ta(n,e),a=[];for(let d of r)Aa(d)==="signalled"&&a.push(d);for(let d of i)try{process.kill(-d,"SIGKILL")}catch(m){if(typeof m!="object"||m===null||m.code!=="ESRCH")throw m}await $r(500);let s=await Mr(),l=new Set(s.map(d=>d.pid));return{platform:process.platform,userDataDir:t,discoveredPids:e,signalledPids:a,survivorPids:r.filter(d=>l.has(d))}}o(Ia,"killProcessTreePosix");async function xa(t){let e=await Gr(t),n=[];for(let i of e)try{await rt("taskkill.exe",["/T","/F","/PID",String(i)],ot),n.push(i)}catch(a){let s=Fr(a);if(s===null||s.code!==128)throw a}await $r(500);let r=await Gr(t);return{platform:"win32",userDataDir:t,discoveredPids:e,signalledPids:n,survivorPids:r}}o(xa,"killProcessTreeWin32");var Z=u("instance-registry");function at(t){return typeof t=="string"&&t!==""}o(at,"isNonEmptyString");function Da(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(!at(n.runId))throw new Error(`[instance-registry] ${e} has a missing or empty runId.`);if(!at(n.userDataDir))throw new Error(`[instance-registry] ${e} has a missing or empty userDataDir.`);if(!at(n.startedAt)||!at(n.deadlineAt))throw new Error(`[instance-registry] ${e} has a missing or empty timestamp field.`);if(typeof n.agentPid!="number"||!Number.isInteger(n.agentPid))throw new Error(`[instance-registry] ${e} has a non-integer agentPid.`);return{v:1,runId:n.runId,agentPid:n.agentPid,userDataDir:n.userDataDir,startedAt:n.startedAt,deadlineAt:n.deadlineAt}}o(Da,"parseInstanceRecord");function La(t,e){let n=`${t}.tmp`;Ca(n,JSON.stringify(e,null,2),{encoding:"utf8",mode:384}),Na(n,t)}o(La,"writeMarkerAtomically");var st=class{static{o(this,"InstanceRegistry")}#e;constructor(e){this.#e=xe(e,_r)}get instancesRoot(){return this.#e}userDataDirFor(e){return xe(this.#e,e)}reserve(e,n){jr(this.#e,{recursive:!0,mode:448});let r=this.userDataDirFor(e);try{jr(r,{recursive:!1,mode:448})}catch(a){throw typeof a=="object"&&a!==null&&a.code==="EEXIST"?new H(e,r,a):a}let i=new Date().toISOString();try{La(xe(r,Qe),{v:1,runId:e,agentPid:process.pid,userDataDir:r,startedAt:i,deadlineAt:n})}catch(a){try{qt(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:i,deadlineAt:n}}read(e){return this.#n(xe(this.userDataDirFor(e),Qe))}release(e){let n=this.userDataDirFor(e);qt(n,{recursive:!0,force:!0}),Z.info("Instance released",{runId:e,userDataDir:n})}listRunIds(){let e;try{e=Oa(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=xe(n,Qe),i=null,a;try{i=this.#n(r),a="valid"}catch(l){a=(typeof l=="object"&&l!==null?l.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:l instanceof Error?l.message:String(l)})}let s=await it(n);return Z.warn("Leftover browser instance swept",{runId:e,userDataDir:n,marker:a,kill:s}),qt(n,{recursive:!0,force:!0}),{runId:e,userDataDir:n,marker:a,record:i,kill:s,removed:!0}}#n(e){let n=Pa(e,"utf8");return Da(JSON.parse(n),e)}};async function qr(t){let e=new Date().toISOString(),r=t.serviceWorkers()[0];if(r===void 0)return{ok:!1,observedAt:e,reason:"service_worker_absent",detail:"the browser context exposes no service worker \u2014 the extension is not running"};try{let i=await q({operation:`read chrome.storage.session['tabStates'] and ['${bt}']`,timeoutMs:1e4,evaluate:o(()=>r.evaluate(async a=>{let s=await new Promise(h=>chrome.storage.session.get(["tabStates",a],h)),l=s.tabStates,d=typeof l!="object"||l===null?[]:Object.entries(l).map(([h,p])=>{let b=typeof p=="object"&&p!==null?p.playback:null;if(typeof b!="object"||b===null)return{tabId:h,playback:null};let R=b;return{tabId:h,playback:{runId:typeof R.runId=="string"?R.runId:null,status:typeof R.status=="string"?R.status:null,currentStepIndex:typeof R.currentStepIndex=="number"?R.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:d,agentJob:f}},bt),"evaluate")});return{ok:!0,observedAt:e,tabs:i.tabs,agentJob:i.agentJob}}catch(i){return{ok:!1,observedAt:e,reason:"evaluate_failed",detail:i instanceof Error?i.message:String(i)}}}o(qr,"probePlaybackSession");async function Br(t,e){let r=t.serviceWorkers()[0];return r!==void 0?r:t.waitForEvent("serviceworker",{timeout:e})}o(Br,"waitForServiceWorker");async function Hr(t,e){let n,r=new Promise((i,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 i=await Promise.race([t.evaluate(()=>chrome.runtime.id),r]);if(typeof i!="string"||i==="")throw new Error(`chrome.runtime.id returned ${JSON.stringify(i)} \u2014 expected a non-empty extension id`);return i}finally{n!==void 0&&clearTimeout(n)}}o(Hr,"readRuntimeId");function lt(t,e){let n=t-Date.now();if(n<=0)throw new Error(`the ${45e3}ms extension readiness budget was already spent before ${e} could run`);return n}o(lt,"remainingBudgetMs");async function Jr(t){let e=Date.now(),n=e+45e3,r=n-5e3,i=await Br(t,Math.min(5e3,lt(r,"the service-worker target wait")));try{let a=await Hr(i,lt(r,"the first readiness evaluate"));return{worker:i,extensionId:a,serviceWorkerUrl:i.url(),attempts:1,readyAfterMs:Date.now()-e}}catch(a){let s=await t.newPage();try{let l=await Br(t,Math.min(5e3,lt(n,"the retry service-worker target wait"))),d=await Hr(l,lt(n,"the retry readiness evaluate"));return{worker:l,extensionId:d,serviceWorkerUrl:l.url(),attempts:2,readyAfterMs:Date.now()-e}}catch(l){let d=a instanceof Error?a.message:String(a),m=l instanceof Error?l.message:String(l);throw new Error(`extension readiness probe failed on both exp5 lanes. Direct attempt: ${d}. Page-open retry: ${m}.`,{cause:l})}finally{await s.close()}}}o(Jr,"probeExtensionReadiness");var E=u("playwright-execution-runtime"),Vt=class extends Error{static{o(this,"LaunchAbortedError")}runId;constructor(e){super(`[runtime] launch of run ${e} was aborted: the instance was disposed while the browser was still coming up, so it was torn down instead of being published (CONTRACT-la \xA715 A3, A19.1).`),this.name="LaunchAbortedError",this.runId=e}},dt=class{static{o(this,"PlaywrightExecutionRuntime")}#e;#t;#n;#r;#a;#s;#o=null;#i=null;#u=!1;#l=null;#c=null;constructor(e){Tr(e.extensionDist),this.#e=e.extensionDist,this.#t=e.headfulOverride,this.#n=e.allowInsecureHttps,this.#r=e.onInstanceLost,this.#a=new st(e.stateDir),this.#s=Dr(e.extensionDist),E.info("Execution runtime constructed",{stateDir:e.stateDir,instancesRoot:this.#a.instancesRoot,headfulOverride:e.headfulOverride,allowInsecureHttps:e.allowInsecureHttps,envFingerprint:this.#s})}getActiveInstance(){let e=this.#o;return e===null?null:{runId:e.runId,userDataDir:e.userDataDir,headful:e.headful,extensionId:e.extensionId,chromeVersion:e.chromeVersion,startedAt:e.startedAt,deadlineAt:e.deadlineAt}}async sweepOrphanInstances(){return this.#a.sweepOrphans()}async probePlaybackSession(){let e=this.#o;return e===null?{ok:!1,observedAt:new Date().toISOString(),reason:"service_worker_absent",detail:"the runtime owns no browser instance"}:qr(e.context)}async startRun(e){let n=this.#o;if(n!==null)throw new nt(e.runId,n.runId);let r=Date.now(),i=new Date(r+e.maxRunDurationSec*1e3).toISOString(),a=await V(e.runId,"instance_reserve",()=>this.#a.reserve(e.runId,i));this.#c?.runId===e.runId&&(this.#c=null);let s={runId:e.runId,userDataDir:a.userDataDir,context:null,disposeRequested:!1};this.#i=s;let l=this.#p(e);E.info("Launching browser for run",{runId:e.runId,headful:l,requestHeadful:e.headful,headfulOverride:this.#t,userDataDir:a.userDataDir,maxRunDurationSec:e.maxRunDurationSec,deadlineAt:i,envFingerprint:this.#s});let d=null;try{let m=await V(e.runId,"browser_launch",()=>Rr({userDataDir:a.userDataDir,extensionDist:this.#e,headful:l,allowInsecureHttps:this.#n}));d=m,s.context=m,this.#m(s);let f=await V(e.runId,"browser_version",()=>br(m)),h=await V(e.runId,"readiness_probe",()=>Jr(m));await this.#h(e,h.worker),await V(e.runId,"entry_navigation",()=>Ua(m,e)),await this.#d(e,m);let p={runId:e.runId,context:d,userDataDir:a.userDataDir,headful:l,extensionId:h.extensionId,chromeVersion:f,startedAt:a.startedAt,deadlineAt:i};this.#m(s),this.#g(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:d,userDataDir:a.userDataDir,timeoutMs:2e4,trigger:s.disposeRequested?"dispose_during_launch":"launch_failure"}),m}finally{this.#i===s&&(this.#i=null)}}async cancelRun(e){await this.disposeRun(e)}async disposeRun(e,n=2e4){let r=this.#l;if(r!==null&&r.runId===e)return E.info("Dispose requested for a lost instance \u2014 joining the teardown already running",{runId:e}),r.promise;let i=this.#i;if(i!==null&&i.runId===e)return i.disposeRequested=!0,E.warn("Dispose requested for a run that is still launching \u2014 aborting the launch",{runId:e,userDataDir:i.userDataDir,contextPresent:i.context!==null}),this.#f({runId:e,context:i.context,userDataDir:i.userDataDir,timeoutMs:n,trigger:"dispose_during_launch"});let a=this.#o;return a===null||a.runId!==e?this.#w(e):(this.#o=null,this.#f({runId:e,context:a.context,userDataDir:a.userDataDir,timeoutMs:n,trigger:"dispose"}))}#p(e){return e.headful||this.#t}async#h(e,n){let r=await V(e.runId,"token_seed",()=>Or(n,e.extensionSession));E.info("Run session seeded into the browser profile",{runId:e.runId,accessTokenLength:r.accessTokenLength,refreshTokenLength:r.refreshTokenLength}),await V(e.runId,"command_seed",()=>Pr(n,e.command)),E.info("Command envelope seeded",{runId:e.runId,command:e.command})}async#d(e,n){let r=await V(e.runId,"command_ack",()=>Nr(n,e.runId,15e3));if(r.outcome==="rejected")throw new B(e.runId,"command_ack",`the extension refused the command envelope: ${r.reason}`);E.info("Command envelope dispatched by the extension",{runId:e.runId})}#m(e){if(e.disposeRequested)throw new Vt(e.runId)}#g(e){let n=o(i=>{if(this.#u||this.#o?.runId!==e.runId)return;this.#o=null;let a=this.#f({runId:e.runId,context:e.context,userDataDir:e.userDataDir,timeoutMs:2e4,trigger:"instance_lost"});this.#l={runId:e.runId,promise:a},a.catch(l=>{E.error("Teardown after a lost browser instance failed",{runId:e.runId,userDataDir:e.userDataDir,err:l instanceof Error?l.message:String(l)})}).finally(()=>{this.#l?.promise===a&&(this.#l=null)});let s={runId:e.runId,at:new Date().toISOString(),source:i};E.error("Browser instance disappeared without a dispose",{...s}),this.#r(s)},"report");e.context.on("close",()=>n("context_closed"));let r=e.context.browser();r!==null&&r.on("disconnected",()=>n("browser_disconnected"))}#w(e){let n=this.#c;if(n===null||n.runId!==e)return E.info("Dispose requested for a run this runtime does not own \u2014 no-op",{requestedRunId:e,activeRunId:this.#o===null?null:this.#o.runId,disposeOutcome:"closed"}),{runId:e,outcome:"closed",kill:null,instanceReleased:!1,durationMs:0};if(n.result.instanceReleased)return E.info("Dispose repeated for a run already torn down \u2014 replaying its outcome",{runId:e,disposeOutcome:n.result.outcome,instanceReleased:!0}),n.result;if(!n.killConfirmed)throw E.error("Dispose repeated for a run whose force-kill was never confirmed \u2014 the instance directory stays for the startup sweep",{runId:e,disposeOutcome:n.result.outcome,kill:n.result.kill,instanceReleased:!1}),new Error(`[runtime] the instance directory for run ${e} is deliberately retained: the force-kill of its process tree was never confirmed, and this runtime does not retry it. The startup sweep (CONTRACT-la \xA715 A3 rule 2) is the next eraser.`);let r=Date.now();E.warn("Dispose repeated for a run whose instance directory survived \u2014 retrying",{runId:e,disposeOutcome:n.result.outcome}),this.#a.release(e);let i={...n.result,instanceReleased:!0,durationMs:Date.now()-r};return this.#c={runId:e,result:i,killConfirmed:!0},E.info("Instance released on a repeated dispose",{runId:e,disposeOutcome:i.outcome,instanceReleased:!0,durationMs:i.durationMs}),i}async#f(e){let n=Date.now();this.#u=!0;let r="closed",i=null,a=null;try{if(e.context!==null){let p=await kr(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{i=await it(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 l=a===null&&(i===null||i.survivorPids.length===0),d=null,m=!1;if(l)try{this.#a.release(e.runId),m=!0}catch(p){d=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:i===null?null:i.survivorPids});let f={runId:e.runId,outcome:r,kill:i,instanceReleased:m,durationMs:Date.now()-n};this.#c={runId:e.runId,result:f,killConfirmed:l};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||d!==null?E.error("Instance disposed with a failed cleanup step",h):E.info("Instance disposed",h),d!==null)throw d;if(a!==null)throw a;if(i!==null&&i.survivorPids.length>0)throw new Error(`[runtime] force-kill for run ${e.runId} left ${i.survivorPids.length} process(es) alive after the settle delay (${i.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.#u=!1}}};async function V(t,e,n){try{return await n()}catch(r){throw r instanceof B||r instanceof H?r:new B(t,e,r instanceof Error?r.message:String(r),r)}}o(V,"stage");async function Ua(t,e){let n=t.pages()[0];await(n===void 0?await t.newPage():n).goto(e.entryUrl,{waitUntil:"load"})}o(Ua,"navigateToEntry");import{setTimeout as Fa}from"node:timers/promises";function pe(t,e=Math.random){if(t<0)throw new Error(`[backoff] attempt must be >= 0, got ${t}. Pass 0 for the first reconnect after a disconnect.`);let n=Math.min(6e4,1e3*Math.pow(2,Math.min(t,26)));return Math.floor(e()*n)}o(pe,"computeBackoffDelayMs");function he(t){let e=$a(t.error);return e!==null?{retry:!1,reason:e}:{retry:!0,delayMs:pe(t.attempt,t.rng)}}o(he,"decideGatewayRetry");function $a(t){if(t instanceof y)return"terminal_signal";if(t instanceof U)return"contract_breach";if(t instanceof _)return"semantic_refusal";if(t.operation==="claim"||t.operation==="token_rotate")return"one_shot_operation";if(t instanceof M||t instanceof ie)return null;if(t instanceof v)return t.status===429?"rate_limited":t.status>=500?null:"semantic_refusal";throw new Error(`[backoff-policy] No retry row for ${t.name} on operation '${t.operation}'. A new GatewayError subclass was added without extending the decision table in src/gateway/backoff-policy.ts.`)}o($a,"classifyFailure");var J=u("supervisor-identity");async function ge(t){let{config:e}=t;if(e.initialToken!==void 0)return ja(e,e.initialToken);let n=G(e.stateDir);if(n!==null)return Va(n.serverUrl,e.serverUrl),J.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 Ba(t,e.enrollmentCode);throw new Error(`[progon-agent] This machine has no agent identity, so the daemon cannot start.
20
+ For a dev or E2E stand you can instead set PROGON_AGENT_EXTENSION_DIST to an already agent-mode dist, which bypasses the bundled copy entirely (CONTRACT-la \xA78).`}i($t,"bundledMissingMessage");function ia(t){let{stateDir:e,agentId:n}=t;if(n==="")throw new Error(`[extension-dist] agentId is required: ${jt} carries it (CONTRACT-la \xA71 D-C) and this module does not invent identity.`);let r=t.sourceDir??ra(),o=se(e,rr),a=se(e,`${or}${process.pid}`);return Yi(e,{recursive:!0,mode:448}),sa(e),Ft(a,{recursive:!0,force:!0}),Wi(r,a,{recursive:!0}),Ki(a,448),aa(a,n),Ft(o,{recursive:!0,force:!0}),zi(a,o),Ke.info("Agent-mode extension dist prepared",{extensionDist:o,sourceDir:r,agentId:n,protocolVersion:1}),o}i(ia,"prepareAgentExtensionDist");function aa(t,e){let n={agentMode:!0,agentId:e,protocolVersion:1};Zi(se(t,jt),JSON.stringify(n,null,2)+`
21
+ `,"utf8")}i(aa,"writeAgentManifest");function sa(t){let e;try{e=Xi(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(or))continue;let r=se(t,n.name);try{Ft(r,{recursive:!0,force:!0}),Ke.warn("Removed a leftover extension-dist staging directory",{leftover:r})}catch(o){Ke.error("Failed to remove a leftover extension-dist staging directory",{leftover:r,err:o instanceof Error?o.message:String(o)})}}}i(sa,"removeLeftoverStagingDirs");function ir(t){if(t.overridePath!==void 0)return Ke.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 ${jt} must name the agent the browser reports as (CONTRACT-la \xA71 D-C).
22
+ Either enroll the agent ('progon-agent enroll <code>'), which persists the identity the server issued, or set PROGON_AGENT_EXTENSION_DIST to a dist that is already in agent mode (dev/E2E path, \xA78).`);return ia({stateDir:t.stateDir,agentId:t.agentId})}i(ir,"resolveExtensionDist");import{fetch as ca}from"undici";var R=class extends Error{static{i(this,"GatewayError")}operation;constructor(e,n,r){super(n,{cause:r}),this.name=new.target.name,this.operation=e}},U=class extends R{static{i(this,"GatewayTransportError")}constructor(e,n,r){super(e,`[gateway] ${e} failed before a response was received: ${n}`,r)}},b=class extends R{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}},le=class extends b{static{i(this,"GatewayUnauthorizedError")}},_=class extends b{static{i(this,"TokenSupersededError")}},w=class extends R{static{i(this,"TerminalSignalError")}signal;constructor(e,n,r){super(e,`[gateway] agent revoked (${n}) during ${e}: ${r}`),this.signal=n}},We=class extends b{static{i(this,"EnrollmentCodeRejectedError")}},Oe=class extends b{static{i(this,"ProtocolVersionMismatchError")}},de=class extends b{static{i(this,"RunNotClaimableError")}},Z=class extends b{static{i(this,"RunNotFoundError")}},$=class extends R{static{i(this,"GatewayResponseSchemaError")}constructor(e,n,r){super(e,`[gateway] ${e} returned a body that violates the contract: ${n}`,r)}};var ar=u("gateway-http");async function Q(t){let e={accept:"application/json"};t.agentToken!==null&&(e.authorization=`Bearer ${t.agentToken}`),t.body!==null&&(e["content-type"]="application/json"),ar.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 U(t.operation,sr(o),o)}let r;try{r=await n.text()}catch(o){throw new U(t.operation,sr(o),o)}if(!n.ok){let o=la(n.status,r);throw ar.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 $(t.operation,`the ${n.status} response body is not valid JSON`,o)}}i(Q,"executeGatewayRequest");function N(t,e){if(e.success)return e.data;throw new $(t,da(e.error),e.error)}i(N,"parseGatewayBody");function la(t,e){let n;try{n=JSON.parse(e)}catch{return{status:t,errorCode:null,params:null,message:Bt}}if(typeof n!="object"||n===null||Array.isArray(n))return{status:t,errorCode:null,params:null,message:Bt};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"?G(s):Bt}}i(la,"readErrorEnvelope");var Bt="the response body carried no Progon error envelope";function sr(t){return G(t instanceof Error?t.message:String(t))}i(sr,"describeCause");function da(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(da,"summarizeSchemaViolation");var ce=class extends b{static{i(this,"EnrollmentSlowDownError")}retryAfterSec;constructor(e,n,r,o,a,s){super(e,n,r,o,a),this.retryAfterSec=s}},ue=class extends b{static{i(this,"EnrollmentAccessDeniedError")}},pe=class extends b{static{i(this,"EnrollmentRequestExpiredError")}},me=class extends b{static{i(this,"EnrollmentAlreadyCompletedError")}},he=class extends b{static{i(this,"EnrollmentRequestInvalidError")}};function lr(t){return t.status===401&&t.errorCode==="agent_enroll.invalid_code"?O(We,"enroll",t):t.status===409&&t.errorCode==="agent_enroll.protocol_version"?O(Oe,"enroll",t):D("enroll",t)}i(lr,"mapEnrollError");function dr(t){return t.status===409&&t.errorCode==="agent_enroll.protocol_version"?O(Oe,"enrollment_request_create",t):D("enrollment_request_create",t)}i(dr,"mapEnrollmentRequestCreateError");function cr(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 ce("enrollment_request_poll",t.status,t.errorCode,t.params,t.message,n)}return t.status===403&&t.errorCode==="agent_enroll.access_denied"?O(ue,"enrollment_request_poll",t):t.status===410&&t.errorCode==="agent_enroll.expired"?O(pe,"enrollment_request_poll",t):t.status===410&&t.errorCode==="agent_enroll.already_completed"?O(me,"enrollment_request_poll",t):t.status===401&&t.errorCode==="agent_enroll.invalid_request"?O(he,"enrollment_request_poll",t):D("enrollment_request_poll",t)}i(cr,"mapEnrollmentRequestPollError");function ur(t){return D("enrollment_request_cancel",t)}i(ur,"mapEnrollmentRequestCancelError");function pr(t){return ge("poll_desired_state",t,()=>D("poll_desired_state",t))}i(pr,"mapPollDesiredStateError");function mr(t){return ge("claim",t,()=>t.status===409&&t.errorCode==="run.not_claimable"?O(de,"claim",t):t.status===404?O(Z,"claim",t):D("claim",t))}i(mr,"mapClaimError");function hr(t){return ge("fail",t,()=>t.status===404?O(Z,"fail",t):D("fail",t))}i(hr,"mapFailError");function gr(t){return ge("token_status",t,()=>D("token_status",t))}i(gr,"mapTokenStatusError");function fr(t){return ge("token_rotate",t,()=>D("token_rotate",t))}i(fr,"mapTokenRotateError");function yr(t){return ge("declare_capabilities",t,()=>D("declare_capabilities",t))}i(yr,"mapDeclareCapabilitiesError");function ge(t,e,n){return e.status===403&&e.errorCode==="agents.revoked"?new w(t,"http_403_agents_revoked",e.message):e.status===401&&e.errorCode==="agents.token_superseded"?O(_,t,e):e.status===401?O(le,t,e):n()}i(ge,"bearerRoute");function O(t,e,n){return new t(e,n.status,n.errorCode,n.params,n.message)}i(O,"named");function D(t,e){return O(b,t,e)}i(D,"generic");var Ye=[...rn,on,an];import{z as ee}from"zod";var wr=ee.object({rotationDue:ee.boolean(),tokenRotatedAt:ee.string().nullable(),anchorAt:ee.string(),intervalDays:ee.number().int()}),Er=ee.object({agentToken:ee.string().regex(ne)});var Xe=u("gateway-client"),ua="/api/agent-gateway";function C(t,e){return new URL(`${t.replace(/\/+$/,"")}${ua}${e}`)}i(C,"buildGatewayUrl");var vr=3e5,_r=1e4,br={headersTimeout:vr,bodyTimeout:vr,connect:{timeout:_r}};function pa(){let t=Dn(process.env);return On(Gt(process.env),t===void 0?br:{...br,connect:{timeout:_r,ca:t}},t)}i(pa,"buildGatewayDispatcher");var qt,Qe=i((t,e)=>{if(qt===void 0){let n=pa();qt=i((r,o)=>ca(r,{...o,dispatcher:n}),"defaultGatewayFetch")}return qt(t,e)},"pinnedGatewayFetch"),ze=class{static{i(this,"GatewayEnrollmentClient")}serverUrl;machine;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.machine=e.machine,this.fetchImpl=e.fetchImpl??Qe}async enroll(e){let n={...this.machine,enrollmentCode:e,protocolVersion:1},r=await Q({operation:"enroll",method:"POST",url:C(this.serverUrl,"/enroll"),agentToken:null,body:n,signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:lr}),o=N("enroll",Ge.safeParse(r));return Xe.info("Agent enrolled",{agentId:o.agentId,pollWaitSec:o.pollWaitSec,protocolVersion:o.protocolVersion}),o}},Ze=class{static{i(this,"GatewayClient")}serverUrl;agentToken;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.agentToken=e.agentToken,this.fetchImpl=e.fetchImpl??Qe}async authenticatedRequest(e){return Q({operation:e.operation,method:e.method,url:e.url,agentToken:this.agentToken,body:e.body,signal:e.signal,fetchImpl:this.fetchImpl,mapHttpError:e.mapHttpError})}async pollDesiredState(e){let n=C(this.serverUrl,"/state");e?.waitSec!==void 0&&n.searchParams.set("waitSec",String(e.waitSec));let r=await this.authenticatedRequest({operation:"poll_desired_state",method:"GET",url:n,body:null,signal:e?.signal,mapHttpError:pr}),o=N("poll_desired_state",hn.safeParse(r));if(o.agent.revoked)throw new w("poll_desired_state","desired_state_snapshot","the desired-state snapshot reports this agent as revoked");return o}async claimRun(e){let n=await this.authenticatedRequest({operation:"claim",method:"POST",url:C(this.serverUrl,`/runs/${encodeURIComponent(e)}/claim`),body:{capabilities:Ye},signal:void 0,mapHttpError:mr});return N("claim",vn.safeParse(n))}async failRun(e,n){let r=await this.authenticatedRequest({operation:"fail",method:"POST",url:C(this.serverUrl,`/runs/${encodeURIComponent(e)}/fail`),body:n,signal:void 0,mapHttpError:hr}),o=N("fail",yn.safeParse(r));return Xe.info("Reported run failure to the gateway",{runId:e,reason:n.reason,status:o.status}),o}async getTokenRotationStatus(e){let n=await this.authenticatedRequest({operation:"token_status",method:"GET",url:C(this.serverUrl,"/token"),body:null,signal:e?.signal,mapHttpError:gr});return N("token_status",wr.safeParse(n))}async rotateToken(e){let n=await this.authenticatedRequest({operation:"token_rotate",method:"POST",url:C(this.serverUrl,"/token/rotate"),body:null,signal:e?.signal,mapHttpError:fr});return N("token_rotate",Er.safeParse(n))}async declareCapabilities(e){await this.authenticatedRequest({operation:"declare_capabilities",method:"POST",url:C(this.serverUrl,"/capabilities"),body:{capabilities:Ye},signal:e?.signal,mapHttpError:yr}),Xe.info("Capabilities declared",{capabilities:Ye})}useAgentToken(e){this.agentToken=e,Xe.info("Adopted a rotated agent token for all subsequent gateway requests")}};var ma=u("debug-env-guard"),ha=["pw:protocol","pw:api"];function ga(t){return t.replace(/[\\^$.|?+()[\]{}]/g,"\\$&")}i(ga,"escapeRegExp");function Rr(t){if(t.startsWith("-"))return!1;let e=`^${t.split("*").map(ga).join(".*?")}$`,n=new RegExp(e);return ha.some(r=>n.test(r))}i(Rr,"enablesPlaywright");function fa(){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=>Rr(o));if(n.length===0)return[];let r=e.filter(o=>!Rr(o));return r.length===0?delete process.env.DEBUG:process.env.DEBUG=r.join(","),ma.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(fa,"sanitizePlaywrightDebugEnv");fa();import{statSync as kr}from"node:fs";import{isAbsolute as wa,join as Ea}from"node:path";import{createRequire as ya}from"node:module";var F=ya(import.meta.url)("playwright-core"),et=F.chromium,nu=F.firefox,ru=F.webkit,ou=F.selectors,iu=F.devices,au=F.errors,su=F.request,lu=F._electron,du=F._android;var tt="chromium";var Sr="instances",nt="instance.json";async function Tr(t){return et.launchPersistentContext(t.userDataDir,{headless:!t.headful,channel:tt,ignoreHTTPSErrors:t.allowInsecureHttps,args:[`--disable-extensions-except=${t.extensionDist}`,`--load-extension=${t.extensionDist}`,"--no-first-run","--no-default-browser-check"]})}i(Tr,"launchExtensionContext");function va(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(va,"requireBrowser");function Ar(t){return va(t).version()}i(Ar,"readChromeVersion");async function xr(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(xr,"raceClose");function Ir(t){if(!wa(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=kr(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=Ea(t,"manifest.json");try{kr(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(Ir,"assertUsableExtensionDist");var ba=u("worker-evaluate"),Vt=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 q(t){let e=t.evaluate(),n=!1;e.catch(a=>{n&&ba.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 Vt(t.operation,t.timeoutMs))},t.timeoutMs)});try{return await Promise.race([e,o])}finally{r!==void 0&&clearTimeout(r)}}i(q,"evaluateWithDeadline");var Or="accessToken",Pr="refreshToken";async function Cr(t,e){await q({operation:"write the run session into chrome.storage.local",timeoutMs:1e4,evaluate:i(()=>t.evaluate(([r,o,a,s])=>new Promise(l=>chrome.storage.local.set({[r]:a,[o]:s},()=>l())),[Or,Pr,e.accessToken,e.refreshToken]),"evaluate")});let n=await q({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 l=s[r],d=s[o];a({accessTokenLength:typeof l=="string"?l.length:null,refreshTokenLength:typeof d=="string"?d.length:null})})),[Or,Pr]),"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(Cr,"seedRunSession");function Nr(t){return JSON.stringify(Object.keys(t).sort().map(e=>[e,t[e]]))}i(Nr,"canonicalise");async function Dr(t,e){await q({operation:`write the command envelope to chrome.storage.local['${ke}']`,timeoutMs:1e4,evaluate:i(()=>t.evaluate(([a,s])=>new Promise(l=>chrome.storage.local.set({[a]:s},()=>l())),[ke,e]),"evaluate")});let n=await q({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],l=>{let d=l[a];s(d===void 0?null:d)})),ke),"evaluate")});if(typeof n!="object"||n===null)throw new Error(`command envelope read-back returned ${JSON.stringify(n)} \u2014 chrome.storage.local['${ke}'] does not hold the envelope`);let r=Nr({...e}),o=Nr(n);if(r!==o)throw new Error(`command envelope read-back mismatch: wrote ${r}, read ${o}`)}i(Dr,"seedCommandEnvelope");async function Ra(t,e,n){let r=await q({operation:`read chrome.storage.local['${Le}']`,timeoutMs:n,evaluate:i(()=>t.evaluate(a=>new Promise(s=>chrome.storage.local.get([a],l=>{let d=l[a];s(d===void 0?null:d)})),Le),"evaluate")});if(r===null)return{kind:"absent"};let o=gn.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(Ra,"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['${Le}'] 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 l;try{l=await Ra(s,e,a)}catch(d){o=`the last poll failed: ${d instanceof Error?d.message:String(d)}`,l={kind:"invalid",detail:o}}if(l.kind==="ack")return l.ack;l.kind!=="absent"&&(o=l.detail)}await new Promise(l=>setTimeout(l,250))}}i(Lr,"waitForCommandAck");import ot from"node:os";import{createRequire as Sa}from"node:module";var Gr=Sa(import.meta.url);function ka(){let t=Gr.resolve("playwright-core/package.json"),e=Gr(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(ka,"readPlaywrightCoreVersion");function Mr(t){return{node:process.version,platform:`${ot.platform()} ${ot.release()} ${ot.arch()}`,cpus:ot.cpus().length,playwrightCore:ka(),chromiumExecutable:et.executablePath(),channel:tt,extensionDist:t}}i(Mr,"buildEnvFingerprint");import{mkdirSync as Vr,readdirSync as Fa,readFileSync as ja,renameSync as Ba,rmSync as Jt,writeFileSync as qa}from"node:fs";import{join as Pe}from"node:path";var V=class extends Error{static{i(this,"RuntimeLaunchError")}runId;stage;failReason="launch_error";constructor(e,n,r,o){super(`[runtime] launch failed at stage ${n} for run ${e}: ${r}`,{cause:o}),this.name="RuntimeLaunchError",this.runId=e,this.stage=n}};function Ur(t){let e=new Set,n=t;for(;n instanceof Error&&!e.has(n)&&(e.add(n),n.cause!==void 0);)n=n.cause;return n instanceof Error?n.message:String(n)}i(Ur,"deepestCauseMessage");var H=class extends Error{static{i(this,"InstanceAlreadyRegisteredError")}runId;userDataDir;constructor(e,n,r){super(`[runtime] refusing to launch run ${e}: instance directory already exists at ${n}. Either this run is already live, or a previous daemon left it behind (the startup sweep clears leftovers \u2014 CONTRACT-la \xA715 A3, gate G-3).`,{cause:r}),this.name="InstanceAlreadyRegisteredError",this.runId=e,this.userDataDir=n}},it=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 Aa}from"node:child_process";import{promisify as xa}from"node:util";import{setTimeout as Br}from"node:timers/promises";var at=xa(Aa),st={timeout:5e3};function qr(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(qr,"asExecFailure");function Ia(t){let e=[];for(let n of t.split(`
23
+ `)){let r=n.trim();if(r==="")continue;let o=Number(r);!Number.isInteger(o)||o===process.pid||e.push(o)}return e}i(Ia,"parsePidLines");var Ht="--user-data-dir=",Oa=new Set([" "," ",'"',"'"]),Pa=new Set([" "," ",'"',"'"]);function Na(t){return t.replace(/[\\^$.|?*+()[\]{}]/g,"\\$&")}i(Na,"escapeEre");function Ca(t){return`(^|[[:space:]'"])${Na(`${Ht}${t}`)}([[:space:]'"]|$)`}i(Ca,"buildAnchorPattern");function Da(t,e){let n=t.toLowerCase(),r=`${Ht}${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],l=a===void 0||Oa.has(a),d=s===void 0||Pa.has(s);if(l&&d)return!0}return!1}i(Da,"matchesAnchor");async function La(t){try{let{stdout:e}=await at("pgrep",["-f",Ca(t)],st);return Ia(e)}catch(e){let n=qr(e);if(n!==null&&n.code===1&&n.stdout.trim()==="")return[];throw e}}i(La,"discoverPosix");async function $r(t){let n=`Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Where-Object { $_.ProcessId -ne $PID -and $_.CommandLine -and $_.CommandLine.Contains('${`${Ht}${t}`.replace(/'/g,"''")}') } | ForEach-Object { "$($_.ProcessId)\`t$($_.CommandLine)" }`,{stdout:r}=await at("powershell.exe",["-NoProfile","-NonInteractive","-Command",n],st),o=[];for(let a of r.split(`
24
+ `)){let s=a.indexOf(" ");if(s===-1)continue;let l=Number(a.slice(0,s).trim()),d=a.slice(s+1);!Number.isInteger(l)||l===process.pid||Da(d,t)&&o.push(l)}return o}i($r,"discoverWin32");async function Fr(){let{stdout:t}=await at("ps",["-A","-o","pid=,ppid=,pgid="],st),e=[];for(let n of t.split(`
25
+ `)){let r=n.trim().split(/\s+/);if(r.length<3)continue;let[o,a,s]=r,l=Number(o),d=Number(a),m=Number(s);!Number.isInteger(l)||!Number.isInteger(d)||!Number.isInteger(m)||e.push({pid:l,ppid:d,pgid:m})}return e}i(Fr,"readProcessTable");function Ga(t,e){let n=new Map;for(let d of t){let m=n.get(d.ppid);m===void 0?n.set(d.ppid,[d.pid]):m.push(d.pid)}let r=new Set(e),o=[...e];for(let d=o.pop();d!==void 0;d=o.pop()){let m=n.get(d);if(m!==void 0)for(let y of m)r.has(y)||(r.add(y),o.push(y))}let a=t.find(d=>d.pid===process.pid),s=a===void 0?null:a.pgid,l=new Set;for(let d of t)r.has(d.pid)&&(d.pgid<=0||s!==null&&d.pgid===s||l.add(d.pgid));return r.delete(process.pid),{members:[...r],groups:[...l]}}i(Ga,"expandTree");function Ma(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(Ma,"sigkill");async function lt(t){return process.platform==="win32"?$a(t):Ua(t)}i(lt,"killProcessTree");async function Ua(t){let e=await La(t);if(e.length===0)return{platform:process.platform,userDataDir:t,discoveredPids:[],signalledPids:[],survivorPids:[]};let n=await Fr(),{members:r,groups:o}=Ga(n,e),a=[];for(let d of r)Ma(d)==="signalled"&&a.push(d);for(let d of o)try{process.kill(-d,"SIGKILL")}catch(m){if(typeof m!="object"||m===null||m.code!=="ESRCH")throw m}await Br(500);let s=await Fr(),l=new Set(s.map(d=>d.pid));return{platform:process.platform,userDataDir:t,discoveredPids:e,signalledPids:a,survivorPids:r.filter(d=>l.has(d))}}i(Ua,"killProcessTreePosix");async function $a(t){let e=await $r(t),n=[];for(let o of e)try{await at("taskkill.exe",["/T","/F","/PID",String(o)],st),n.push(o)}catch(a){let s=qr(a);if(s===null||s.code!==128)throw a}await Br(500);let r=await $r(t);return{platform:"win32",userDataDir:t,discoveredPids:e,signalledPids:n,survivorPids:r}}i($a,"killProcessTreeWin32");var te=u("instance-registry");function dt(t){return typeof t=="string"&&t!==""}i(dt,"isNonEmptyString");function Va(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(!dt(n.runId))throw new Error(`[instance-registry] ${e} has a missing or empty runId.`);if(!dt(n.userDataDir))throw new Error(`[instance-registry] ${e} has a missing or empty userDataDir.`);if(!dt(n.startedAt)||!dt(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(Va,"parseInstanceRecord");function Ha(t,e){let n=`${t}.tmp`;qa(n,JSON.stringify(e,null,2),{encoding:"utf8",mode:384}),Ba(n,t)}i(Ha,"writeMarkerAtomically");var ct=class{static{i(this,"InstanceRegistry")}#e;constructor(e){this.#e=Pe(e,Sr)}get instancesRoot(){return this.#e}userDataDirFor(e){return Pe(this.#e,e)}reserve(e,n){Vr(this.#e,{recursive:!0,mode:448});let r=this.userDataDirFor(e);try{Vr(r,{recursive:!1,mode:448})}catch(a){throw typeof a=="object"&&a!==null&&a.code==="EEXIST"?new H(e,r,a):a}let o=new Date().toISOString();try{Ha(Pe(r,nt),{v:1,runId:e,agentPid:process.pid,userDataDir:r,startedAt:o,deadlineAt:n})}catch(a){try{Jt(r,{recursive:!0,force:!0})}catch(s){te.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 te.info("Instance reserved",{runId:e,userDataDir:r,deadlineAt:n}),{runId:e,userDataDir:r,startedAt:o,deadlineAt:n}}read(e){return this.#n(Pe(this.userDataDirFor(e),nt))}release(e){let n=this.userDataDirFor(e);Jt(n,{recursive:!0,force:!0}),te.info("Instance released",{runId:e,userDataDir:n})}listRunIds(){let e;try{e=Fa(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?te.warn("Startup sweep found leftover browser instances",{instancesRoot:this.#e,count:n.length,outcomes:n}):te.info("Startup sweep found no leftover browser instances",{instancesRoot:this.#e}),{scannedAt:e,instancesRoot:this.#e,outcomes:n}}async#t(e){let n=this.userDataDirFor(e),r=Pe(n,nt),o=null,a;try{o=this.#n(r),a="valid"}catch(l){a=(typeof l=="object"&&l!==null?l.code:null)==="ENOENT"?"missing":"unreadable",te.warn("Leftover instance marker is unusable \u2014 killing by directory path anyway",{runId:e,userDataDir:n,marker:a,err:l instanceof Error?l.message:String(l)})}let s=await lt(n);return te.warn("Leftover browser instance swept",{runId:e,userDataDir:n,marker:a,kill:s}),Jt(n,{recursive:!0,force:!0}),{runId:e,userDataDir:n,marker:a,record:o,kill:s,removed:!0}}#n(e){let n=ja(e,"utf8");return Va(JSON.parse(n),e)}};async function Hr(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 q({operation:`read chrome.storage.session['tabStates'] and ['${At}']`,timeoutMs:1e4,evaluate:i(()=>r.evaluate(async a=>{let s=await new Promise(g=>chrome.storage.session.get(["tabStates",a],g)),l=s.tabStates,d=typeof l!="object"||l===null?[]:Object.entries(l).map(([g,h])=>{let k=typeof h=="object"&&h!==null?h.playback:null;if(typeof k!="object"||k===null)return{tabId:g,playback:null};let S=k;return{tabId:g,playback:{runId:typeof S.runId=="string"?S.runId:null,status:typeof S.status=="string"?S.status:null,currentStepIndex:typeof S.currentStepIndex=="number"?S.currentStepIndex:null}}}),m=s[a],y=typeof m!="object"||m===null?null:(()=>{let g=m;return{agentJobId:typeof g.agentJobId=="string"?g.agentJobId:null,updatedAt:typeof g.updatedAt=="string"?g.updatedAt:null}})();return{tabs:d,agentJob:y}},At),"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(Hr,"probePlaybackSession");async function Jr(t,e){let r=t.serviceWorkers()[0];return r!==void 0?r:t.waitForEvent("serviceworker",{timeout:e})}i(Jr,"waitForServiceWorker");async function Kr(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(Kr,"readRuntimeId");function ut(t,e){let n=t-Date.now();if(n<=0)throw new Error(`the ${45e3}ms extension readiness budget was already spent before ${e} could run`);return n}i(ut,"remainingBudgetMs");async function Yr(t){let e=Date.now(),n=e+45e3,r=n-5e3,o=await Jr(t,Math.min(5e3,ut(r,"the service-worker target wait")));try{let a=await Kr(o,ut(r,"the first readiness evaluate"));return{worker:o,extensionId:a,serviceWorkerUrl:o.url(),attempts:1,readyAfterMs:Date.now()-e}}catch(a){let s=await t.newPage();try{let l=await Jr(t,Math.min(5e3,ut(n,"the retry service-worker target wait"))),d=await Kr(l,ut(n,"the retry readiness evaluate"));return{worker:l,extensionId:d,serviceWorkerUrl:l.url(),attempts:2,readyAfterMs:Date.now()-e}}catch(l){let d=a instanceof Error?a.message:String(a),m=l instanceof Error?l.message:String(l);throw new Error(`extension readiness probe failed on both exp5 lanes. Direct attempt: ${d}. Page-open retry: ${m}.`,{cause:l})}finally{await s.close()}}}i(Yr,"probeExtensionReadiness");var v=u("playwright-execution-runtime"),Yt=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}},pt=class{static{i(this,"PlaywrightExecutionRuntime")}#e;#t;#n;#r;#a;#s;#o=null;#i=null;#u=!1;#l=null;#c=null;constructor(e){Ir(e.extensionDist),this.#e=e.extensionDist,this.#t=e.headfulOverride,this.#n=e.allowInsecureHttps,this.#r=e.onInstanceLost,this.#a=new ct(e.stateDir),this.#s=Mr(e.extensionDist),v.info("Execution runtime constructed",{stateDir:e.stateDir,instancesRoot:this.#a.instancesRoot,headfulOverride:e.headfulOverride,allowInsecureHttps:e.allowInsecureHttps,envFingerprint:this.#s})}getActiveInstance(){let e=this.#o;return e===null?null:{runId:e.runId,userDataDir:e.userDataDir,headful:e.headful,extensionId:e.extensionId,chromeVersion:e.chromeVersion,startedAt:e.startedAt,deadlineAt:e.deadlineAt}}async sweepOrphanInstances(){return this.#a.sweepOrphans()}async probePlaybackSession(){let e=this.#o;return e===null?{ok:!1,observedAt:new Date().toISOString(),reason:"service_worker_absent",detail:"the runtime owns no browser instance"}:Hr(e.context)}async startRun(e){let n=this.#o;if(n!==null)throw new it(e.runId,n.runId);let r=Date.now(),o=new Date(r+e.maxRunDurationSec*1e3).toISOString(),a=await J(e.runId,"instance_reserve",()=>this.#a.reserve(e.runId,o));this.#c?.runId===e.runId&&(this.#c=null);let s={runId:e.runId,userDataDir:a.userDataDir,context:null,disposeRequested:!1};this.#i=s;let l=this.#m(e);v.info("Launching browser for run",{runId:e.runId,headful:l,requestHeadful:e.headful,headfulOverride:this.#t,userDataDir:a.userDataDir,maxRunDurationSec:e.maxRunDurationSec,deadlineAt:o,envFingerprint:this.#s});let d=null;try{let m=await J(e.runId,"browser_launch",()=>Tr({userDataDir:a.userDataDir,extensionDist:this.#e,headful:l,allowInsecureHttps:this.#n}));d=m,s.context=m,this.#p(s);let y=await J(e.runId,"browser_version",()=>Ar(m)),g=await J(e.runId,"readiness_probe",()=>Yr(m));await this.#h(e,g.worker),await J(e.runId,"entry_navigation",()=>Wa(m,e)),await this.#d(e,m);let h={runId:e.runId,context:d,userDataDir:a.userDataDir,headful:l,extensionId:g.extensionId,chromeVersion:y,startedAt:a.startedAt,deadlineAt:o};this.#p(s),this.#g(h),this.#o=h,this.#i===s&&(this.#i=null),v.info("Run launched",{runId:e.runId,chromeVersion:y,extensionId:g.extensionId,readinessAttempts:g.attempts,readyAfterMs:g.readyAfterMs,launchDurationMs:Date.now()-r})}catch(m){throw this.#i===s&&(this.#i=null),await this.#f({runId:e.runId,context:d,userDataDir:a.userDataDir,timeoutMs:2e4,trigger:s.disposeRequested?"dispose_during_launch":"launch_failure"}),m}finally{this.#i===s&&(this.#i=null)}}async cancelRun(e){await this.disposeRun(e)}async disposeRun(e,n=2e4){let r=this.#l;if(r!==null&&r.runId===e)return v.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,v.warn("Dispose requested for a run that is still launching \u2014 aborting the launch",{runId:e,userDataDir:o.userDataDir,contextPresent:o.context!==null}),this.#f({runId:e,context:o.context,userDataDir:o.userDataDir,timeoutMs:n,trigger:"dispose_during_launch"});let a=this.#o;return a===null||a.runId!==e?this.#w(e):(this.#o=null,this.#f({runId:e,context:a.context,userDataDir:a.userDataDir,timeoutMs:n,trigger:"dispose"}))}#m(e){return e.headful||this.#t}async#h(e,n){let r=await J(e.runId,"token_seed",()=>Cr(n,e.extensionSession));v.info("Run session seeded into the browser profile",{runId:e.runId,accessTokenLength:r.accessTokenLength,refreshTokenLength:r.refreshTokenLength}),await J(e.runId,"command_seed",()=>Dr(n,e.command)),v.info("Command envelope seeded",{runId:e.runId,command:e.command})}async#d(e,n){let r=await J(e.runId,"command_ack",()=>Lr(n,e.runId,15e3));if(r.outcome==="rejected")throw new V(e.runId,"command_ack",`the extension refused the command envelope: ${r.reason}`);v.info("Command envelope dispatched by the extension",{runId:e.runId})}#p(e){if(e.disposeRequested)throw new Yt(e.runId)}#g(e){let n=i(o=>{if(this.#u||this.#o?.runId!==e.runId)return;this.#o=null;let a=this.#f({runId:e.runId,context:e.context,userDataDir:e.userDataDir,timeoutMs:2e4,trigger:"instance_lost"});this.#l={runId:e.runId,promise:a},a.catch(l=>{v.error("Teardown after a lost browser instance failed",{runId:e.runId,userDataDir:e.userDataDir,err:l instanceof Error?l.message:String(l)})}).finally(()=>{this.#l?.promise===a&&(this.#l=null)});let s={runId:e.runId,at:new Date().toISOString(),source:o};v.error("Browser instance disappeared without a dispose",{...s}),this.#r(s)},"report");e.context.on("close",()=>n("context_closed"));let r=e.context.browser();r!==null&&r.on("disconnected",()=>n("browser_disconnected"))}#w(e){let n=this.#c;if(n===null||n.runId!==e)return v.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 v.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 v.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();v.warn("Dispose repeated for a run whose instance directory survived \u2014 retrying",{runId:e,disposeOutcome:n.result.outcome}),this.#a.release(e);let o={...n.result,instanceReleased:!0,durationMs:Date.now()-r};return this.#c={runId:e,result:o,killConfirmed:!0},v.info("Instance released on a repeated dispose",{runId:e,disposeOutcome:o.outcome,instanceReleased:!0,durationMs:o.durationMs}),o}async#f(e){let n=Date.now();this.#u=!0;let r="closed",o=null,a=null;try{if(e.context!==null){let h=await xr(e.context,e.timeoutMs);h.settled==="closed"?r="closed":h.settled==="timeout"?(r="timeout-force-killed",v.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",v.error("context.close() rejected \u2014 force-killing",{runId:e.runId,userDataDir:e.userDataDir,err:h.error instanceof Error?h.error.message:String(h.error)}))}if(r!=="closed"||e.trigger==="instance_lost"||e.trigger==="dispose_during_launch")try{o=await lt(e.userDataDir)}catch(h){a=h,v.error("Force-kill of the run process tree failed",{runId:e.runId,userDataDir:e.userDataDir,trigger:e.trigger,disposeOutcome:r,err:h instanceof Error?h.message:String(h)})}let l=a===null&&(o===null||o.survivorPids.length===0),d=null,m=!1;if(l)try{this.#a.release(e.runId),m=!0}catch(h){d=h,v.error("Failed to remove the instance directory after teardown",{runId:e.runId,userDataDir:e.userDataDir,err:h instanceof Error?h.message:String(h)})}else v.error("Instance directory KEPT \u2014 the force-kill is unconfirmed and the startup sweep must still be able to find this tree",{runId:e.runId,userDataDir:e.userDataDir,disposeOutcome:r,killFailed:a!==null,survivorPids:o===null?null:o.survivorPids});let y={runId:e.runId,outcome:r,kill:o,instanceReleased:m,durationMs:Date.now()-n};this.#c={runId:e.runId,result:y,killConfirmed:l};let g={runId:y.runId,disposeOutcome:y.outcome,trigger:e.trigger,contextPresent:e.context!==null,kill:y.kill,killFailed:a!==null,instanceReleased:y.instanceReleased,durationMs:y.durationMs};if(a!==null||d!==null?v.error("Instance disposed with a failed cleanup step",g):v.info("Instance disposed",g),d!==null)throw d;if(a!==null)throw a;if(o!==null&&o.survivorPids.length>0)throw new Error(`[runtime] force-kill for run ${e.runId} left ${o.survivorPids.length} process(es) alive after the settle delay (${o.survivorPids.join(", ")}). The instance directory ${e.userDataDir} is kept so the startup sweep can re-discover them (CONTRACT-la \xA715 A3 rule 2).`);return y}finally{this.#u=!1}}};async function J(t,e,n){try{return await n()}catch(r){throw r instanceof V||r instanceof H?r:new V(t,e,r instanceof Error?r.message:String(r),r)}}i(J,"stage");async function Wa(t,e){let n=t.pages()[0];await(n===void 0?await t.newPage():n).goto(e.entryUrl,{waitUntil:"load"})}i(Wa,"navigateToEntry");import{setTimeout as Xa}from"node:timers/promises";function fe(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(fe,"computeBackoffDelayMs");function ye(t){let e=Ya(t.error);return e!==null?{retry:!1,reason:e}:{retry:!0,delayMs:fe(t.attempt,t.rng)}}i(ye,"decideGatewayRetry");function Ya(t){if(t instanceof w)return"terminal_signal";if(t instanceof $)return"contract_breach";if(t instanceof _)return"semantic_refusal";if(t.operation==="claim"||t.operation==="token_rotate")return"one_shot_operation";if(t instanceof U||t instanceof le)return null;if(t instanceof b)return t.status===429?"rate_limited":t.status>=500?null:"semantic_refusal";throw new Error(`[backoff-policy] No retry row for ${t.name} on operation '${t.operation}'. A new GatewayError subclass was added without extending the decision table in src/gateway/backoff-policy.ts.`)}i(Ya,"classifyFailure");var K=u("supervisor-identity");async function we(t){let{config:e}=t;if(e.initialToken!==void 0)return za(e,e.initialToken);let n=M(e.stateDir);if(n!==null)return ts(n.serverUrl,e.serverUrl),K.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 Qa(t,e.enrollmentCode);throw new p(`[progon-agent] This machine has no agent identity, so the daemon cannot start.
24
26
  There is no state file in ${e.stateDir} and neither PROGON_AGENT_TOKEN nor PROGON_AGENT_ENROLL_CODE is set.
25
- To enroll: create the agent in Progon (Settings \u2192 Agents), mint its enrollment code, then start the daemon once with PROGON_AGENT_ENROLL_CODE=<code>. The code is one-shot and expires in 15 minutes (CONTRACT-la \xA75.1); the minted pgat_ token is persisted to the state file, so later starts need neither variable.`)}o(ge,"resolveAgentIdentity");function ja(t,e){return t.enrollmentCode!==void 0&&J.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)"),J.info("Agent identity taken from PROGON_AGENT_TOKEN",{stateFile:qa(t.stateDir)}),{agentToken:e,agentId:null,pollWaitSec:void 0,source:"env_token"}}o(ja,"identityFromEnvToken");function qa(t){try{return G(t)===null?"absent":"present"}catch(e){return J.warn("The state file could not be read \u2014 continuing on PROGON_AGENT_TOKEN, which does not need it. The persisted credential is NOT usable: once this variable is unset, the daemon will refuse to start until the file is removed and the machine re-enrolled",{stateDir:t,err:e instanceof Error?e.message:String(e)}),"unreadable"}}o(qa,"describeStateFile");async function Ba(t,e){let{config:n,machine:r}=t;J.info("No agent identity found \u2014 redeeming the enrollment code",{hostname:r.hostname,platform:r.platform,arch:r.arch,agentVersion:r.agentVersion});let i=new We(t.fetchImpl===void 0?{serverUrl:n.serverUrl,machine:r}:{serverUrl:n.serverUrl,machine:r,fetchImpl:t.fetchImpl}),a=await Ha(i,e,t.rng);return ne(n.stateDir,{agentId:a.agentId,agentToken:a.agentToken,protocolVersion:a.protocolVersion,serverUrl:n.serverUrl,tokenRotatedAt:null}),J.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"}}o(Ba,"enrollThisMachine");var Kr=900*1e3;async function Ha(t,e,n){let r=Date.now()+Kr;for(let i=0;;i+=1)try{return await t.enroll(e)}catch(a){if(!(a instanceof S))throw a;let s=he({attempt:i,error:a,rng:n});if(!s.retry)throw J.warn("Enrollment refused definitively \u2014 not retrying",{attempt:i,reason:s.reason,err:a.message}),a;if(Date.now()+s.delayMs>=r)throw new Error(`[progon-agent] Enrollment kept failing for the ${Kr/6e4} minutes an enrollment code stays valid (CONTRACT-la \xA75.1), so this code can no longer be redeemed. Last failure: ${a.message}
26
- Mint a fresh code in Progon (Settings \u2192 Agents) once the server is reachable, then run 'progon-agent enroll <code>' again.`,{cause:a});J.warn("Enrollment attempt failed \u2014 backing off and retrying",{attempt:i,retryInMs:s.delayMs,err:a.message}),await Fa(s.delayMs)}}o(Ha,"enrollWithRetry");function ct(t,e){if(t.source==="enrollment")return;let n=" The code itself was not spent and stays valid until it expires.";throw t.source==="env_token"?new Error(`[progon-agent] The enrollment code was not redeemed: PROGON_AGENT_TOKEN is set, and a credential supplied that way takes precedence over any code (CONTRACT-la \xA78).
27
+ To enroll: create the agent in Progon (Settings \u2192 Agents), mint its enrollment code, then start the daemon once with PROGON_AGENT_ENROLL_CODE=<code>. The code is one-shot and expires in 15 minutes (CONTRACT-la \xA75.1); the minted pgat_ token is persisted to the state file, so later starts need neither variable.`)}i(we,"resolveAgentIdentity");function za(t,e){return t.enrollmentCode!==void 0&&K.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)"),K.info("Agent identity taken from PROGON_AGENT_TOKEN",{stateFile:Za(t.stateDir)}),{agentToken:e,agentId:null,pollWaitSec:void 0,source:"env_token"}}i(za,"identityFromEnvToken");function Za(t){try{return M(t)===null?"absent":"present"}catch(e){return K.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(Za,"describeStateFile");async function Qa(t,e){let{config:n,machine:r}=t;K.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 ze(t.fetchImpl===void 0?{serverUrl:n.serverUrl,machine:r}:{serverUrl:n.serverUrl,machine:r,fetchImpl:t.fetchImpl}),a=await es(o,e,t.rng);return ie(n.stateDir,{agentId:a.agentId,agentToken:a.agentToken,protocolVersion:a.protocolVersion,serverUrl:n.serverUrl,tokenRotatedAt:null}),K.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(Qa,"enrollThisMachine");var Xr=900*1e3;async function es(t,e,n){let r=Date.now()+Xr;for(let o=0;;o+=1)try{return await t.enroll(e)}catch(a){if(!(a instanceof R))throw a;let s=ye({attempt:o,error:a,rng:n});if(!s.retry)throw K.warn("Enrollment refused definitively \u2014 not retrying",{attempt:o,reason:s.reason,err:a.message}),a;if(Date.now()+s.delayMs>=r)throw new p(`[progon-agent] Enrollment kept failing for the ${Xr/6e4} minutes an enrollment code stays valid (CONTRACT-la \xA75.1), so this code can no longer be redeemed. Last failure: ${a.message}
28
+ Mint a fresh code in Progon (Settings \u2192 Agents) once the server is reachable, then run 'progon-agent enroll <code>' again.`,{cause:a});K.warn("Enrollment attempt failed \u2014 backing off and retrying",{attempt:o,retryInMs:s.delayMs,err:a.message}),await Xa(s.delayMs)}}i(es,"enrollWithRetry");function mt(t,e){if(t.source==="enrollment")return;let n=" The code itself was not spent and stays valid until it expires.";throw t.source==="env_token"?new p(`[progon-agent] The enrollment code was not redeemed: PROGON_AGENT_TOKEN is set, and a credential supplied that way takes precedence over any code (CONTRACT-la \xA78).
27
29
  Unset PROGON_AGENT_TOKEN, then run the same command again. A separate state directory does NOT help here: the variable is read before any state file and wins wherever that file lives.
28
- `+n):new Error(`[progon-agent] The enrollment code was not redeemed: this machine already holds a credential enrolled against ${e.serverUrl}, and a persisted credential takes precedence over a code (CONTRACT-la \xA78).
30
+ `+n):new p(`[progon-agent] The enrollment code was not redeemed: this machine already holds a credential enrolled against ${e.serverUrl}, and a persisted credential takes precedence over a code (CONTRACT-la \xA78).
29
31
  To enroll this machine as a SECOND agent \u2014 for another deployment, or as another agent record \u2014 give it its own state directory: PROGON_RUNNER_STATE_DIR=<dir> progon-agent enroll <code> --server <url> (and give 'progon-agent start' the same variable).
30
- To REPLACE the credential it already holds, remove the state file in ${e.stateDir}, then run: progon-agent enroll <code> --server ${e.serverUrl} \u2014 with that file gone nothing on this machine names a deployment any more, so --server is required.
31
- `+n)}o(ct,"assertEnrollmentCodeWasRedeemed");function Va(t,e){if(!je(t,e))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.
32
- Either point PROGON_SERVER_URL back at ${t} \u2014 or unset it entirely, since an enrolled machine reads the server from its own state file (CONTRACT-la \xA78) \u2014 or enroll this machine against ${e} instead: remove the state file, then run 'progon-agent enroll <code> --server ${e}'. To keep BOTH, enroll the second one under its own PROGON_RUNNER_STATE_DIR rather than replacing this credential.`)}o(Va,"assertServerMatchesEnrollment");import{createRequire as Ja}from"node:module";import{hostname as Ka}from"node:os";var Wr=["darwin","linux","win32"],Yr=["x64","arm64"];function Wa(t){return Wr.includes(t)}o(Wa,"isSupportedPlatform");function Ya(t){return Yr.includes(t)}o(Ya,"isSupportedArch");function Xa(){let e=Ja(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}o(Xa,"readAgentVersion");function fe(){let t=process.platform;if(!Wa(t))throw new Error(`[supervisor] Unsupported platform ${JSON.stringify(t)}. The local agent runs on ${Wr.join(", ")} (CONTRACT-la \xA75.1, \xA710.3).`);let e=process.arch;if(!Ya(e))throw new Error(`[supervisor] Unsupported CPU architecture ${JSON.stringify(e)}. The local agent runs on ${Yr.join(", ")} (CONTRACT-la \xA75.1).`);let n=Ka();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:Xa()}}o(fe,"describeAgentMachine");var Xr=o(()=>{},"noop"),ut=class{static{o(this,"ActionQueue")}#e=Promise.resolve();run(e){let n=this.#e.then(e,e);return this.#e=n.then(Xr,Xr),n}};var zr=u("supervisor-deadline"),Oe=class extends Error{static{o(this,"DeadlineExceededError")}operation;timeoutMs;constructor(e,n){super(`[supervisor] ${e} did not settle within ${n}ms`),this.name="DeadlineExceededError",this.operation=e,this.timeoutMs=n}};async function mt(t){let e=t.work(),n=!1;e.then(()=>{n&&zr.warn("Abandoned work settled successfully after its deadline had passed",{operation:t.operation,timeoutMs:t.timeoutMs})},a=>{n&&zr.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,i=new Promise((a,s)=>{r=setTimeout(()=>{n=!0,s(new Oe(t.operation,t.timeoutMs))},t.timeoutMs)});try{return await Promise.race([e,i])}finally{r!==void 0&&clearTimeout(r)}}o(mt,"withDeadline");function pt(t,e){return new Promise(n=>{if(e.aborted){n();return}let r=setTimeout(()=>{e.removeEventListener("abort",i),n()},t);function i(){clearTimeout(r),n()}o(i,"onAbort"),e.addEventListener("abort",i,{once:!0})})}o(pt,"sleep");var K=u("fail-reporter"),ht=class{static{o(this,"RunFailureReporter")}#e;#t=null;#n=null;constructor(e){this.#e=e}hasVerdictFor(e){return this.#n===e}async report(e){if(this.#n===e.runId){K.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&&K.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,K.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&&(K.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});K.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 _)throw K.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 S))throw n;let r=he({attempt:e.attempt,error:n});if(!r.retry){K.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},K.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 gt=120,Zr=gt*1e3,Jt=3e4,ye=3,Kt=45*1e3,Wt="agent shutdown";var F=u("launch-run");async function to(t){let e=await Za(t);return e.kind!=="claimed"?e:es(t,e.payload)}o(to,"claimAndLaunch");async function Za(t){try{let e=await t.client.claimRun(t.runId);return F.info("Run claimed",Qa(e)),{kind:"claimed",payload:e}}catch(e){if(e instanceof y)throw e;if(e instanceof _)throw F.error("Claim refused as superseded \u2014 not launching, leaving it to the sweep",{runId:t.runId,err:e.message}),e;if(e instanceof ae||e instanceof Y)return F.info("Claim refused \u2014 the desired-state snapshot was stale, not launching",{runId:t.runId,err:e.message}),{kind:"claim_refused"};if(!(e instanceof S))throw e;return F.error("Claim produced no usable answer \u2014 not launching, leaving it to the sweep",{runId:t.runId,err:e.message}),{kind:"claim_unavailable"}}}o(Za,"claimRun");function Qa(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}}o(Qa,"describeClaim");async function es(t,e){try{await mt({operation:`startRun(${e.runId})`,timeoutMs:Zr,work:o(()=>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",...ns(t.runId,r)}}let n=t.runtime.getActiveInstance();return n===null||n.runId!==e.runId?(F.error("The launched instance was already gone when the supervisor read it back",{runId:e.runId,activeRunId:n===null?null:n.runId}),{kind:"instance_lost_immediately",runId:e.runId}):{kind:"launched",instance:n}}o(es,"launchClaimedRun");var Qr=500,eo="\u2026";function ts(t){return t.length<=Qr?t:t.slice(0,Qr-eo.length)+eo}o(ts,"fitFailMessageToWire");function ns(t,e){return e instanceof B?(F.error("Launch failed",{runId:t,stage:e.stage,failReason:e.failReason,err:e.message}),{reason:e.failReason,message:ts(`stage ${e.stage}: ${Lr(e)}`)}):e instanceof Oe?(F.error("Launch exceeded the agent-side launch deadline \u2014 disposing and failing",{runId:t,launchTimeoutSec:gt,err:e.message}),{reason:"launch_error",message:`launch did not complete within ${gt}s`}):e instanceof H?(F.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"}):(F.error("Launch failed with an unexpected error class",{runId:t,errName:e instanceof Error?e.name:typeof e,err:e instanceof Error?e.message:String(e)}),{reason:"launch_error",message:"launch failed with an unexpected error"})}o(ns,"describeLaunchFailure");var we=u("run-monitor");function rs(t,e){let n=Date.now();return e.ok?e.tabs.some(i=>i.playback!==null&&i.playback.runId===t)?{healthy:!0}:os(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 (${is(e.tabs)}; ${as(e.agentJob,n)})`}:{healthy:!1,reason:e.reason,detail:e.detail}}o(rs,"judgeProbe");function os(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<=Kt}o(os,"isJobPulseStanding");function is(t){if(t.length===0)return"tabStates is empty";let e=t.map(n=>n.playback===null?"none":n.playback.runId);return`${t.length} tab(s), playback run ids: ${e.join(", ")}`}o(is,"describeTabs");function as(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(Kt)}ms)`}o(as,"describeJobMarker");var ft=class{static{o(this,"RunMonitor")}#e;#t;#n=null;#r=null;#a=0;#s=!1;constructor(e){this.#e=e;let n=Date.parse(e.deadlineAt);if(Number.isNaN(n))throw new Error(`[run-monitor] run ${e.runId} has an unparseable deadlineAt ${JSON.stringify(e.deadlineAt)} \u2014 the run deadline (CONTRACT-la \xA715 A7) cannot be armed.`);this.#t=n}get runId(){return this.#e.runId}start(){let e=Math.max(0,this.#t-Date.now());we.info("Monitoring launched run",{runId:this.#e.runId,deadlineAt:this.#e.deadlineAt,deadlineInMs:e,probeIntervalMs:Jt,probeStrikeLimit:ye}),this.#n=setInterval(()=>{this.#o()},Jt),this.#n.unref(),this.#r=setTimeout(()=>{this.#s||(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.#s=!0,this.#n!==null&&(clearInterval(this.#n),this.#n=null),this.#r!==null&&(clearTimeout(this.#r),this.#r=null)}async#o(){if(this.#s)return;let e=rs(this.#e.runId,await this.#i());if(this.#s)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#i(){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 ss(t){let e=o(()=>{},"markSettled"),n=new Promise(r=>{e=r});return{runId:t,cancelledBy:null,settled:n,markSettled:e}}o(ss,"createPendingLaunch");var yt=class{static{o(this,"InstanceReconciler")}#e;#t;#n;#r;#a=new Set;#s=null;#o=null;#i=null;constructor(e){this.#e=e.client,this.#t=e.runtime,this.#n=e.reporter,this.#r=e.detach}get activeRunId(){let e=this.#t.getActiveInstance();return e===null?null:e.runId}async sweepAtStartup(){let e=await this.#t.sweepOrphanInstances();this.#a=new Set(e.outcomes.map(n=>n.runId)),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.#o;if(r!==null){if(n!==null&&n.runId===r.runId||r.cancelledBy!==null)return;await this.#h(r,n===null?"desired_state_run_absent":"desired_state_runid_mismatch");return}let i=this.#t.getActiveInstance();if(n===null){i!==null&&await this.dispose(i.runId,"desired_state_run_absent");return}if(i!==null){if(i.runId===n.runId)return;await this.dispose(i.runId,"desired_state_runid_mismatch");return}if(!this.#n.hasVerdictFor(n.runId)){if(n.phase==="queued"){if(this.#i===n.runId){D.info("Not re-claiming a run this agent has already attempted (one-shot CAS)",{runId:n.runId});return}this.#i=n.runId,this.#u(n.runId);return}await this.#m(n.runId,n.phase)}}async cancelLaunchAndSettle(e){let n=this.#o;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.#s?.stop(),this.#s=null}#u(e){let n=ss(e);this.#o=n,this.#l(n)}async#l(e){try{let n=await this.#c(e.runId);await this.#r(()=>this.#p(e,n))}finally{e.markSettled()}}async#c(e){try{return{kind:"outcome",outcome:await to({client:this.#e,runtime:this.#t,runId:e})}}catch(n){return{kind:"thrown",error:n}}}async#p(e,n){if(this.#o===e&&(this.#o=null),n.kind==="thrown")throw n.error;let r=n.outcome;switch(r.kind){case"launched":if(e.cancelledBy!==null){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.#s=new ft({runId:e,deadlineAt:n,probe:o(()=>this.#t.probePlaybackSession(),"probe"),onBrowserGone:o(r=>{this.#r(()=>this.#g(e,"browser_gone",r,"browser_gone"))},"onBrowserGone"),onDeadline:o(()=>{this.#r(()=>this.#g(e,"max_duration","the run reached its server-authored deadline","max_duration"))},"onDeadline")}),this.#s.start()}async#m(e,n){let r=this.#a.has(e),i=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:i}),await this.#n.report({runId:e,reason:i,message:r?"a leftover browser instance for this run was killed by the agent startup sweep":"this agent holds no browser instance for the run"})}async#g(e,n,r,i){await this.dispose(e,i),await this.#n.report({runId:e,reason:n,message:r})}};var no={revoked:"agent_revoked",reenroll_required:"agent_superseded",credential_unusable:"agent_superseded",fatal:"shutdown",stopped:"shutdown"};var A=u("token-rotation"),ro=1440*60*1e3,wt=class{static{o(this,"TokenRotationCoordinator")}#e;#t;#n;#r=null;#a=!1;#s=!1;constructor(e){this.#e=e.client,this.#t=e.stateDir,this.#n=e.identitySource}async runCycle(e){let n=this.#r;if(n!==null)return n;let r=this.#o(e);this.#r=r;try{return await r}finally{this.#r=null}}get canDiagnoseFromTheWire(){return this.#n!=="env_token"}async diagnoseSuperseded(e){if(this.#n==="env_token")return 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 _)return"reenroll_required";if(n instanceof y)throw n;if(n instanceof S)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#o(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.#s)return{kind:"superseded_in_grace"};let n=this.#m();if(n.kind!=="identity")return this.#g(n);let r=n.identity,i=await this.#i(e);return i.kind!=="status"?i.outcome:i.value.rotationDue?await this.#l(r,i.value.tokenRotatedAt,e):this.#u(r,i.value.tokenRotatedAt)}async#i(e){try{return{kind:"status",value:e===void 0?await this.#e.getTokenRotationStatus():await this.#e.getTokenRotationStatus({signal:e})}}catch(n){if(n instanceof _)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 S)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}}#u(e,n){return e.tokenRotatedAt===n?{kind:"not_due"}:e.tokenRotatedAt===null?(this.#d({...e,tokenRotatedAt:n},"first observed rotation marker"),{kind:"not_due"}):(this.#s=!0,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 i;try{i=(await this.#e.rotateToken()).agentToken}catch(s){if(s instanceof y)throw s;if(s instanceof _)return await this.#c(r);if(s instanceof S)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.#p(n);throw s}this.#d({...e,agentToken:i,tokenRotatedAt:null},"rotated agent token"),this.#e.useAgentToken(i);let a=await this.#h();return a.kind==="reenroll_required"?a:(a.kind==="observed"&&this.#d({...e,agentToken:i,tokenRotatedAt:a.tokenRotatedAt},"rotation marker of the new agent token"),A.info("Agent token rotated"),{kind:"rotated"})}async#c(e){return await this.diagnoseSuperseded(e)==="reenroll_required"?{kind:"reenroll_required"}:(this.#s=!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#p(e){let n=await this.#i(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.#s=!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.#i(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 ne(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}}#m(){let e;try{e=G(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"),Yt=o(()=>Promise.resolve(),"noVerdictOwed"),Et=class{static{o(this,"RunSupervisor")}#e;#t;#n;#r=new ut;#a;#s;#o=null;#i=0;#u=!1;#l=new AbortController;#c=null;#p=!1;#h=!1;#d;#m=null;#g=null;constructor(e){this.#e=e.client,this.#a=e.stateDir,this.#s=e.pollWaitSec,this.#d=e.tokenRotation,this.#t=new ht(e.client),this.#l.signal.addEventListener("abort",()=>this.#P(),{once:!0});let n=e.createRuntime(r=>{this.#A(()=>this.#n.handleInstanceLost(r))});this.#n=new yt({client:e.client,runtime:n,reporter:this.#t,detach:o(r=>this.#A(r),"detach")})}async run(){await this.#r.run(()=>this.#n.sweepAtStartup());let e=await this.#x();if(e!==null)return e;for(this.#b(),await this.#w();!this.#u;){let n=this.#c;if(n!==null)return await this.#v(n),"revoked";if(this.#p)return await this.#_(),"reenroll_required";if(this.#h)return await this.#T(),"credential_unusable";try{await this.#r.run(()=>this.#t.retryPending());let r=await this.#N();this.#i=0,await this.#r.run(()=>this.#n.reconcile(r))}catch(r){if(r instanceof y)return await this.#v(r),"revoked";if(r instanceof _&&await this.#k(r))return await this.#_(),"reenroll_required";if(this.#u)break;if(this.#c!==null||this.#p||this.#h)continue;let i=await this.#D(r);if(i!==null)return i==="credential_unusable"?await this.#T():await this.#C(),i}}return"stopped"}async#w(){try{await this.#e.declareCapabilities({signal:this.#l.signal})}catch(e){if(e instanceof y||e instanceof _||!(e instanceof S))throw e;I.error("Could not declare capabilities \u2014 job kinds this build supports will not be published to this agent until the next start; playback is unaffected",{err:e.message})}}async shutdown(e){let n=this.#g;if(n!==null)return I.info("A shutdown is already in progress \u2014 joining it",{cause:e}),n;let r=this.#f(e);return this.#g=r,r}async#f(e){I.info("Shutting down",{cause:e}),await this.#y(e==="fatal"?"fatal":"stopped",n=>this.#R(n))}async#y(e,n){this.#u=!0,this.#o?.abort(),this.#l.abort();let r=no[e],i=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:i})}),await this.#d.settle()}async#R(e){let{activeRunId:n,launchingRunId:r}=e;if(n!==null){await this.#S(()=>this.#t.report({runId:n,reason:"browser_gone",message:Wt}));return}if(r!==null){await this.#S(()=>this.#t.report({runId:r,reason:"browser_gone",message:Wt}));return}await this.#S(()=>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.#v(e),"revoked";throw e}return await this.#_(),"reenroll_required"}#b(){if(this.#u||this.#l.signal.aborted)return;let e=setTimeout(()=>{this.#m=null,this.#O().finally(()=>{this.#b()})},ro);e.unref(),this.#m=e}async#O(){try{if((await this.#d.runCycle(this.#l.signal)).kind!=="reenroll_required")return;this.#p=!0,this.#o?.abort()}catch(e){await this.#I(e)}}#P(){this.#m!==null&&(clearTimeout(this.#m),this.#m=null)}async#k(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.#c=n,!1;throw n}}async#N(){let e=new AbortController;this.#o=e;try{return await this.#e.pollDesiredState({waitSec:this.#s,signal:e.signal})}finally{this.#o=null}}async#E(){await this.#d.settle(),Fn(this.#a)}async#v(e){I.error("This agent has been revoked \u2014 disposing, wiping the credential and stopping",{signal:e.signal}),await this.#y("revoked",Yt),await this.#E()}async#T(){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",Yt)}async#C(){await this.#y("fatal",e=>this.#R(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",Yt),await this.#E()}async#D(e){if(!(e instanceof S))throw e;let n=this.#L(e);return n.kind==="exit"?n.exit:(this.#i+=1,await pt(n.delayMs,this.#l.signal),null)}#L(e){if(e instanceof _){if(!this.#d.canDiagnoseFromTheWire)return{kind:"exit",exit:"credential_unusable"};let r=pe(this.#i);return I.error("The server refused this credential as superseded, but the probe did not confirm the token family is dead \u2014 the daemon keeps polling on the credential it holds. If this repeats, create a new enrollment code in Progon (Settings \u2192 Agents) and enroll this machine again.",{operation:e.operation,attempt:this.#i,retryInMs:r}),{kind:"retry",delayMs:r}}let n=he({attempt:this.#i,error:e});return n.retry?(I.warn("Desired-state poll failed \u2014 backing off",{attempt:this.#i,retryInMs:n.delayMs,err:e.message}),{kind:"retry",delayMs:n.delayMs}):(I.error("The desired-state poll was refused definitively and no repetition can change that \u2014 the daemon cannot reconcile without a snapshot, so it is disposing its browser and stopping. Restart duty belongs to the process supervisor.",{reason:n.reason,operation:e.operation,err:e.message}),{kind:"exit",exit:"fatal"})}#A(e){return this.#r.run(e).catch(n=>this.#I(n))}async#I(e){if(e instanceof y){this.#c=e,this.#o?.abort();return}if(e instanceof _){try{await this.#k(e)?this.#p=!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.#p||this.#h||this.#c!==null)&&this.#o?.abort();return}I.error("A background supervisor action failed",{err:e instanceof Error?e.message:String(e)})}async#S(e){try{await e()}catch(n){if(n instanceof _){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.#E(),I.error("This agent was revoked, so the run could not be reported and the credential has been wiped. Create a new enrollment code in Progon (Settings \u2192 Agents) and start the daemon once with PROGON_AGENT_ENROLL_CODE=<code> to enroll this machine again.",{signal:n.signal});return}throw n}}};var oo=u("supervisor-boot");async function io(){let t=re();oo.info("Config loaded",{serverUrlOrigin:new URL(t.serverUrl).origin,serverUrlSource:t.serverUrlSource,stateDir:t.stateDir,headfulOverride:t.headfulOverride,allowInsecureHttps:t.allowInsecureHttps});let e=fe(),n=await ge({config:t,machine:e});oo.info("Agent identity resolved",{source:n.source,agentId:n.agentId,hostname:e.hostname,platform:e.platform,arch:e.arch,agentVersion:e.agentVersion});let r=nr({overridePath:t.extensionDistOverride,stateDir:t.stateDir,agentId:n.agentId});await Ge({stdio:"pipe"});let i=new Ye({serverUrl:t.serverUrl,agentToken:n.agentToken}),a=new wt({client:i,stateDir:t.stateDir,identitySource:n.source});return new Et({client:i,stateDir:t.stateDir,pollWaitSec:n.pollWaitSec,tokenRotation:a,createRuntime:o(s=>new dt({stateDir:t.stateDir,extensionDist:r,headfulOverride:t.headfulOverride,allowInsecureHttps:t.allowInsecureHttps,onInstanceLost:s}),"createRuntime")})}o(io,"bootRunSupervisor");import{createHash as fs,randomBytes as ys}from"node:crypto";import{z as T}from"zod";var ao=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()}),so=T.object({status:T.literal("authorization_pending"),expiresAt:T.iso.datetime({offset:!0}),pollIntervalSec:T.number().int().positive()}),ls=T.object({companyName:T.string(),approvedByEmail:T.string(),approvedAt:T.string()}),lo=T.object({credential:De,approval:ls});var co=u("gateway-enrollment-request"),vt=class{static{o(this,"GatewayEnrollmentRequestClient")}serverUrl;machine;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.machine=e.machine,this.fetchImpl=e.fetchImpl??Xe}async create(e){let n=await X({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:ar}),r=P("enrollment_request_create",ao.safeParse(n));return co.info("Enrollment request opened",{requestId:r.requestId,mode:r.mode,pollIntervalSec:r.pollIntervalSec,expiresAt:r.expiresAt}),r}async poll(e){let n=await X({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:sr}),r=typeof n=="object"&&n!==null?n:null;if(r!==null&&"credential"in r){let i=P("enrollment_request_poll",lo.safeParse(n));return co.info("Enrollment request approved",{agentId:i.credential.agentId}),{kind:"enrolled",credential:i.credential,approval:i.approval}}if(r!==null&&"status"in r){let i=P("enrollment_request_poll",so.safeParse(n));return{kind:"pending",expiresAt:i.expiresAt,pollIntervalSec:i.pollIntervalSec}}throw new U("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 X({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:lr})}};import{spawn as ds}from"node:child_process";var Pe=u("browser-open");function _t(t){return t!==void 0&&t!==""}o(_t,"isSet");function cs(t,e){return!(_t(t.SSH_CONNECTION)||_t(t.SSH_TTY)||e==="linux"&&!_t(t.DISPLAY)&&!_t(t.WAYLAND_DISPLAY))}o(cs,"shouldAttemptBrowserOpen");var us=/[&|^<>"'` ]/;function ms(t){let e;try{e=new URL(t)}catch{return!1}return e.protocol!=="http:"&&e.protocol!=="https:"||t!==e.href?!1:!us.test(t)}o(ms,"isSpawnSafeUrl");function ps(t,e){switch(e){case"darwin":return{command:"open",args:[t]};case"linux":return{command:"xdg-open",args:[t]};case"win32":return{command:"cmd",args:["/d","/s","/c","start","",t]};default:return null}}o(ps,"browserOpenCommand");function uo(t,e,n){if(!cs(e,n)){Pe.debug("Not opening a browser: this host has no desktop to open one on",{platform:n});return}if(!ms(t)){Pe.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=ps(t,n);if(r===null){Pe.debug("Not opening a browser: no opener is defined for this platform",{platform:n});return}try{let i=ds(r.command,[...r.args],{detached:!0,stdio:"ignore"});i.on("error",a=>{Pe.debug("Could not start the browser; the approval URL was printed instead",{platform:n,command:r.command,err:a.message})}),i.unref()}catch(i){Pe.debug("Could not start the browser; the approval URL was printed instead",{platform:n,command:r.command,err:i instanceof Error?i.message:String(i)})}}o(uo,"openVerificationUrl");var hs=30,gs=5;function mo(t){return{intervalSec:t.pollIntervalSec,deadlineMs:t.timeoutSec===null?t.expiresAtMs:Math.min(t.expiresAtMs,t.nowMs+t.timeoutSec*1e3)}}o(mo,"initialPollSchedule");function St(t,e){if(e.kind==="pending")return{state:t,delayMs:t.intervalSec*1e3};if(e.kind==="slow_down"){let r=t.intervalSec+gs,i=e.retryAfterSec!==null&&e.retryAfterSec>r?e.retryAfterSec:r,a=Math.min(i,hs);return{state:{intervalSec:a,deadlineMs:t.deadlineMs},delayMs:a*1e3}}let n=pe(e.attempt,e.rng);return{state:t,delayMs:Math.max(t.intervalSec*1e3,n)}}o(St,"nextPollDelayMs");function po(t,e){return e>=t.deadlineMs}o(po,"isDeadlinePassed");function ho(t,e,n){return Math.max(0,Math.min(e,t.deadlineMs-n))}o(ho,"clampDelayToDeadline");var ve=u("device-enrollment"),ws=24,Es=2e3,Xt=0,Ee=1,fo=130,vs="This machine is already enrolled. Start the daemon with: progon-agent start",_s="Enrollment was denied in the browser. Nothing was created on this machine.",Ss="Cancelled. Nothing was saved on this machine.",Rs="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 go(t){return`Enrollment request expired. Run: progon-agent enroll --server ${t}`}o(go,"expiredLine");function bs(t,e,n){return`This machine is already enrolled against ${t}, not ${e}. An agent credential is only valid at the deployment that issued it, so nothing was requested from ${e}.
32
+ To REPLACE the credential it already holds, remove the state file in ${e.stateDir}, then run: progon-agent enroll <code> --server ${e.serverUrl} \u2014 with that file gone this machine no longer names that deployment itself, and --server is what keeps the new enrollment pointed at it.
33
+ `+n)}i(mt,"assertEnrollmentCodeWasRedeemed");function ts(t,e){if(!Ve(t,e))throw new p(`[progon-agent] The persisted agent credential was enrolled against ${t}, but PROGON_SERVER_URL is ${e}. A pgat_ token is meaningless at a different deployment (CONTRACT-la \xA78), so the daemon refuses to authenticate blind.
34
+ Either point PROGON_SERVER_URL back at ${t} \u2014 or unset it entirely, since an enrolled machine reads the server from its own state file (CONTRACT-la \xA78) \u2014 or enroll this machine against ${e} instead: remove the state file, then run 'progon-agent enroll <code> --server ${e}'. To keep BOTH, enroll the second one under its own PROGON_RUNNER_STATE_DIR rather than replacing this credential.`)}i(ts,"assertServerMatchesEnrollment");import{createRequire as ns}from"node:module";import{hostname as rs}from"node:os";var zr=["darwin","linux","win32"],Zr=["x64","arm64"];function os(t){return zr.includes(t)}i(os,"isSupportedPlatform");function is(t){return Zr.includes(t)}i(is,"isSupportedArch");function as(){let e=ns(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(as,"readAgentVersion");function Ee(){let t=process.platform;if(!os(t))throw new Error(`[supervisor] Unsupported platform ${JSON.stringify(t)}. The local agent runs on ${zr.join(", ")} (CONTRACT-la \xA75.1, \xA710.3).`);let e=process.arch;if(!is(e))throw new Error(`[supervisor] Unsupported CPU architecture ${JSON.stringify(e)}. The local agent runs on ${Zr.join(", ")} (CONTRACT-la \xA75.1).`);let n=rs();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:as()}}i(Ee,"describeAgentMachine");var Qr=i(()=>{},"noop"),ht=class{static{i(this,"ActionQueue")}#e=Promise.resolve();run(e){let n=this.#e.then(e,e);return this.#e=n.then(Qr,Qr),n}};var eo=u("supervisor-deadline"),Ne=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 gt(t){let e=t.work(),n=!1;e.then(()=>{n&&eo.warn("Abandoned work settled successfully after its deadline had passed",{operation:t.operation,timeoutMs:t.timeoutMs})},a=>{n&&eo.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 Ne(t.operation,t.timeoutMs))},t.timeoutMs)});try{return await Promise.race([e,o])}finally{r!==void 0&&clearTimeout(r)}}i(gt,"withDeadline");function ft(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(ft,"sleep");var W=u("fail-reporter"),yt=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){W.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&&W.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,W.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&&(W.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});W.info("Fail verdict delivered",{runId:e.runId,reason:e.reason,status:n.status,attempts:e.attempt+1}),this.#t=null}catch(n){if(n instanceof w)throw n;if(n instanceof _)throw W.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 R))throw n;let r=ye({attempt:e.attempt,error:n});if(!r.retry){W.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},W.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 wt=120,to=wt*1e3,Xt=3e4,ve=3,zt=45*1e3,Zt="agent shutdown";var j=u("launch-run");async function oo(t){let e=await ls(t);return e.kind!=="claimed"?e:cs(t,e.payload)}i(oo,"claimAndLaunch");async function ls(t){try{let e=await t.client.claimRun(t.runId);return j.info("Run claimed",ds(e)),{kind:"claimed",payload:e}}catch(e){if(e instanceof w)throw e;if(e instanceof _)throw j.error("Claim refused as superseded \u2014 not launching, leaving it to the sweep",{runId:t.runId,err:e.message}),e;if(e instanceof de||e instanceof Z)return j.info("Claim refused \u2014 the desired-state snapshot was stale, not launching",{runId:t.runId,err:e.message}),{kind:"claim_refused"};if(!(e instanceof R))throw e;return j.error("Claim produced no usable answer \u2014 not launching, leaving it to the sweep",{runId:t.runId,err:e.message}),{kind:"claim_unavailable"}}}i(ls,"claimRun");function ds(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(ds,"describeClaim");async function cs(t,e){try{await gt({operation:`startRun(${e.runId})`,timeoutMs:to,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",...ps(t.runId,r)}}let n=t.runtime.getActiveInstance();return n===null||n.runId!==e.runId?(j.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(cs,"launchClaimedRun");var no=500,ro="\u2026";function us(t){return t.length<=no?t:t.slice(0,no-ro.length)+ro}i(us,"fitFailMessageToWire");function ps(t,e){return e instanceof V?(j.error("Launch failed",{runId:t,stage:e.stage,failReason:e.failReason,err:e.message}),{reason:e.failReason,message:us(`stage ${e.stage}: ${Ur(e)}`)}):e instanceof Ne?(j.error("Launch exceeded the agent-side launch deadline \u2014 disposing and failing",{runId:t,launchTimeoutSec:wt,err:e.message}),{reason:"launch_error",message:`launch did not complete within ${wt}s`}):e instanceof H?(j.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"}):(j.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(ps,"describeLaunchFailure");var be=u("run-monitor");function ms(t,e){let n=Date.now();return e.ok?e.tabs.some(o=>o.playback!==null&&o.playback.runId===t)?{healthy:!0}:hs(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 (${gs(e.tabs)}; ${fs(e.agentJob,n)})`}:{healthy:!1,reason:e.reason,detail:e.detail}}i(ms,"judgeProbe");function hs(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<=zt}i(hs,"isJobPulseStanding");function gs(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(gs,"describeTabs");function fs(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(zt)}ms)`}i(fs,"describeJobMarker");var Et=class{static{i(this,"RunMonitor")}#e;#t;#n=null;#r=null;#a=0;#s=!1;constructor(e){this.#e=e;let n=Date.parse(e.deadlineAt);if(Number.isNaN(n))throw new Error(`[run-monitor] run ${e.runId} has an unparseable deadlineAt ${JSON.stringify(e.deadlineAt)} \u2014 the run deadline (CONTRACT-la \xA715 A7) cannot be armed.`);this.#t=n}get runId(){return this.#e.runId}start(){let e=Math.max(0,this.#t-Date.now());be.info("Monitoring launched run",{runId:this.#e.runId,deadlineAt:this.#e.deadlineAt,deadlineInMs:e,probeIntervalMs:Xt,probeStrikeLimit:ve}),this.#n=setInterval(()=>{this.#o()},Xt),this.#n.unref(),this.#r=setTimeout(()=>{this.#s||(this.stop(),be.error("Run reached its server-authored deadline",{runId:this.#e.runId,deadlineAt:this.#e.deadlineAt}),this.#e.onDeadline())},e),this.#r.unref()}stop(){this.#s=!0,this.#n!==null&&(clearInterval(this.#n),this.#n=null),this.#r!==null&&(clearTimeout(this.#r),this.#r=null)}async#o(){if(this.#s)return;let e=ms(this.#e.runId,await this.#i());if(this.#s)return;if(e.healthy){this.#a>0&&be.info("Liveness probe recovered",{runId:this.#e.runId,clearedStrikes:this.#a}),this.#a=0;return}this.#a+=1;let n=`${e.reason}: ${e.detail}`;be.warn("Liveness probe failed",{runId:this.#e.runId,strike:this.#a,strikeLimit:ve,reason:e.reason,detail:e.detail}),!(this.#a<ve)&&(this.stop(),be.error("Liveness probe failed the strike limit \u2014 the browser is gone",{runId:this.#e.runId,strikes:ve,detail:n}),this.#e.onBrowserGone(`${ve} consecutive liveness probes failed (${n})`))}async#i(){try{return await this.#e.probe()}catch(e){let n=e instanceof Error?e.message:String(e);return be.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 L=u("instance-reconciler");function ys(t){let e=i(()=>{},"markSettled"),n=new Promise(r=>{e=r});return{runId:t,cancelledBy:null,settled:n,markSettled:e}}i(ys,"createPendingLaunch");var vt=class{static{i(this,"InstanceReconciler")}#e;#t;#n;#r;#a=new Set;#s=null;#o=null;#i=null;constructor(e){this.#e=e.client,this.#t=e.runtime,this.#n=e.reporter,this.#r=e.detach}get activeRunId(){let e=this.#t.getActiveInstance();return e===null?null:e.runId}async sweepAtStartup(){let e=await this.#t.sweepOrphanInstances();this.#a=new Set(e.outcomes.map(n=>n.runId)),L.info("Startup sweep finished",{instancesRoot:e.instancesRoot,leftoverCount:e.outcomes.length,sweptRunIds:[...this.#a]})}async reconcile(e){let n=e.run;this.#n.discardIfNotPublished(n===null?null:n.runId);let r=this.#o;if(r!==null){if(n!==null&&n.runId===r.runId||r.cancelledBy!==null)return;await this.#h(r,n===null?"desired_state_run_absent":"desired_state_runid_mismatch");return}let o=this.#t.getActiveInstance();if(n===null){o!==null&&await this.dispose(o.runId,"desired_state_run_absent");return}if(o!==null){if(o.runId===n.runId)return;await this.dispose(o.runId,"desired_state_runid_mismatch");return}if(!this.#n.hasVerdictFor(n.runId)){if(n.phase==="queued"){if(this.#i===n.runId){L.info("Not re-claiming a run this agent has already attempted (one-shot CAS)",{runId:n.runId});return}this.#i=n.runId,this.#u(n.runId);return}await this.#p(n.runId,n.phase)}}async cancelLaunchAndSettle(e){let n=this.#o;return n===null?null:(L.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){L.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);L.info("Instance disposed",{runId:e,trigger:n,disposeOutcome:r.outcome,instanceReleased:r.instanceReleased,kill:r.kill,durationMs:r.durationMs})}catch(r){L.error("Dispose finished with a failed cleanup step",{runId:e,trigger:n,err:r instanceof Error?r.message:String(r)})}}stopMonitor(){this.#s?.stop(),this.#s=null}#u(e){let n=ys(e);this.#o=n,this.#l(n)}async#l(e){try{let n=await this.#c(e.runId);await this.#r(()=>this.#m(e,n))}finally{e.markSettled()}}async#c(e){try{return{kind:"outcome",outcome:await oo({client:this.#e,runtime:this.#t,runId:e})}}catch(n){return{kind:"thrown",error:n}}}async#m(e,n){if(this.#o===e&&(this.#o=null),n.kind==="thrown")throw n.error;let r=n.outcome;switch(r.kind){case"launched":if(e.cancelledBy!==null){L.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){L.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){L.warn("The desired state withdrew a run that is still launching \u2014 disposing",{runId:e.runId,trigger:n}),e.cancelledBy=n,await this.dispose(e.runId,n)}#d(e,n){this.#s=new Et({runId:e,deadlineAt:n,probe:i(()=>this.#t.probePlaybackSession(),"probe"),onBrowserGone:i(r=>{this.#r(()=>this.#g(e,"browser_gone",r,"browser_gone"))},"onBrowserGone"),onDeadline:i(()=>{this.#r(()=>this.#g(e,"max_duration","the run reached its server-authored deadline","max_duration"))},"onDeadline")}),this.#s.start()}async#p(e,n){let r=this.#a.has(e),o=r?"browser_gone":"launch_error";L.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 io={revoked:"agent_revoked",reenroll_required:"agent_superseded",credential_unusable:"agent_superseded",fatal:"shutdown",stopped:"shutdown"};var x=u("token-rotation"),ao=1440*60*1e3,bt=class{static{i(this,"TokenRotationCoordinator")}#e;#t;#n;#r=null;#a=!1;#s=!1;constructor(e){this.#e=e.client,this.#t=e.stateDir,this.#n=e.identitySource}async runCycle(e){let n=this.#r;if(n!==null)return n;let r=this.#o(e);this.#r=r;try{return await r}finally{this.#r=null}}get canDiagnoseFromTheWire(){return this.#n!=="env_token"}async diagnoseSuperseded(e){if(this.#n==="env_token")return x.error("The agent token in PROGON_AGENT_TOKEN has been superseded and the server no longer accepts it. This daemon owns no copy of it and will not touch the state directory: set PROGON_AGENT_TOKEN to a current token and restart, or unset it and enroll this machine so the daemon can rotate on its own."),"alive";try{return await this.#e.getTokenRotationStatus({signal:e}),"alive"}catch(n){if(n instanceof _)return"reenroll_required";if(n instanceof w)throw n;if(n instanceof R)return x.warn("The superseded probe could not be answered \u2014 treating the credential as still usable, because only an explicit agents.token_superseded ends this identity",{operation:n.operation,err:n.message}),"alive";throw n}}async settle(){let e=this.#r;e!==null&&await e.then(()=>{},()=>{})}async#o(e){if(this.#n==="env_token")return this.#a||(this.#a=!0,x.warn("Agent token rotation is not available: this daemon runs on PROGON_AGENT_TOKEN, so the operator owns the credential and there is nowhere to persist a replacement. Rotate it by setting PROGON_AGENT_TOKEN to a new token and restarting, or enroll this machine so the daemon can rotate on its own.")),{kind:"unsupported_env_token"};if(this.#s)return{kind:"superseded_in_grace"};let n=this.#p();if(n.kind!=="identity")return this.#g(n);let r=n.identity,o=await this.#i(e);return o.kind!=="status"?o.outcome:o.value.rotationDue?await this.#l(r,o.value.tokenRotatedAt,e):this.#u(r,o.value.tokenRotatedAt)}async#i(e){try{return{kind:"status",value:e===void 0?await this.#e.getTokenRotationStatus():await this.#e.getTokenRotationStatus({signal:e})}}catch(n){if(n instanceof _)return x.error("This agent token has been superseded and no longer authenticates \u2014 the token family is dead and this machine must be enrolled again"),{kind:"outcome",outcome:{kind:"reenroll_required"}};if(n instanceof w)throw n;if(n instanceof R)return x.warn("The rotation status check failed \u2014 retrying on the next scheduled cycle",{operation:n.operation,err:n.message}),{kind:"outcome",outcome:{kind:"status_unavailable"}};throw n}}#u(e,n){return e.tokenRotatedAt===n?{kind:"not_due"}:e.tokenRotatedAt===null?(this.#d({...e,tokenRotatedAt:n},"first observed rotation marker"),{kind:"not_due"}):(this.#s=!0,x.error("The server reports a newer generation of this agent token than this daemon holds \u2014 either a rotation response was lost before it could be persisted, or another process rotated this identity. The current token keeps working until the server closes its rotation grace window; after that this machine must be enrolled again. No further rotation will be attempted with the current credential.",{observedTokenRotatedAt:e.tokenRotatedAt,serverTokenRotatedAt:n}),{kind:"superseded_in_grace"})}async#l(e,n,r){let o;try{o=(await this.#e.rotateToken()).agentToken}catch(s){if(s instanceof w)throw s;if(s instanceof _)return await this.#c(r);if(s instanceof R)return x.warn("The rotation request produced no usable answer \u2014 probing what the server actually committed",{operation:s.operation,err:s.message}),await this.#m(n);throw s}this.#d({...e,agentToken:o,tokenRotatedAt:null},"rotated agent token"),this.#e.useAgentToken(o);let a=await this.#h();return a.kind==="reenroll_required"?a:(a.kind==="observed"&&this.#d({...e,agentToken:o,tokenRotatedAt:a.tokenRotatedAt},"rotation marker of the new agent token"),x.info("Agent token rotated"),{kind:"rotated"})}async#c(e){return await this.diagnoseSuperseded(e)==="reenroll_required"?{kind:"reenroll_required"}:(this.#s=!0,x.error("This agent token is no longer the current generation, so it could not be rotated. It still authenticates for now \u2014 the server closes its rotation grace window shortly after, and this machine must then be enrolled again. No further rotation will be attempted with the current credential."),{kind:"superseded_in_grace"})}async#m(e){let n=await this.#i(void 0);return n.kind!=="status"?n.outcome:n.value.tokenRotatedAt===e?(x.warn("The rotation request never reached the server \u2014 nothing was committed and the current token is unchanged. The next scheduled check will try again."),{kind:"not_committed"}):(this.#s=!0,x.error("The rotation was committed by the server but its response was lost, so the new token cannot be recovered \u2014 the server hands out the plaintext exactly once. The current token keeps working until the server closes its rotation grace window; after that this machine must be enrolled again.",{anchorTokenRotatedAt:e,serverTokenRotatedAt:n.value.tokenRotatedAt}),{kind:"superseded_in_grace"})}async#h(){let e=await this.#i(void 0);return e.kind==="status"?{kind:"observed",tokenRotatedAt:e.value.tokenRotatedAt}:e.outcome.kind==="reenroll_required"?{kind:"reenroll_required"}:(x.warn("The rotated token could not be confirmed against the server, so its generation marker was not recorded. The next scheduled check re-establishes it."),{kind:"unconfirmed"})}#d(e,n){try{return ie(this.#t,e),!0}catch(r){return x.error(`The ${n} could not be written to the state directory. This process keeps using the credential it holds, but a restart would fall back to the token on disk, which the server will refuse once its rotation grace window closes. Fix the permissions on the state directory BEFORE restarting the daemon; if it has already been restarted, enroll this machine again.`,{stateDir:this.#t,err:r instanceof Error?r.message:String(r)}),!1}}#p(){let e;try{e=M(this.#t)}catch(n){return{kind:"unreadable",err:n instanceof Error?n.message:String(n)}}return e===null?{kind:"absent"}:{kind:"identity",identity:e}}#g(e){return e.kind==="unreadable"?(x.error("The agent identity in the state directory cannot be read, so the credential this daemon is running on can neither be rotated nor replaced. The daemon keeps working on the token it holds in memory and will look again on the next scheduled check \u2014 restore the state directory from a backup, or enroll this machine again before restarting the daemon.",{stateDir:this.#t,identitySource:this.#n,err:e.err}),{kind:"identity_unavailable"}):(x.error("The agent identity is no longer in the state directory, so the credential this daemon is running on can neither be rotated nor replaced. The daemon keeps working on the token it holds in memory and will look again on the next scheduled check \u2014 restore the state directory, or enroll this machine again before restarting the daemon.",{stateDir:this.#t,identitySource:this.#n}),{kind:"identity_unavailable"})}};var I=u("run-supervisor"),Qt=i(()=>Promise.resolve(),"noVerdictOwed"),_t=class{static{i(this,"RunSupervisor")}#e;#t;#n;#r=new ht;#a;#s;#o=null;#i=0;#u=!1;#l=new AbortController;#c=null;#m=!1;#h=!1;#d;#p=null;#g=null;constructor(e){this.#e=e.client,this.#a=e.stateDir,this.#s=e.pollWaitSec,this.#d=e.tokenRotation,this.#t=new yt(e.client),this.#l.signal.addEventListener("abort",()=>this.#P(),{once:!0});let n=e.createRuntime(r=>{this.#A(()=>this.#n.handleInstanceLost(r))});this.#n=new vt({client:e.client,runtime:n,reporter:this.#t,detach:i(r=>this.#A(r),"detach")})}async run(){await this.#r.run(()=>this.#n.sweepAtStartup());let e=await this.#I();if(e!==null)return e;for(this.#S(),await this.#w();!this.#u;){let n=this.#c;if(n!==null)return await this.#v(n),"revoked";if(this.#m)return await this.#b(),"reenroll_required";if(this.#h)return await this.#T(),"credential_unusable";try{await this.#r.run(()=>this.#t.retryPending());let r=await this.#N();this.#i=0,await this.#r.run(()=>this.#n.reconcile(r))}catch(r){if(r instanceof w)return await this.#v(r),"revoked";if(r instanceof _&&await this.#k(r))return await this.#b(),"reenroll_required";if(this.#u)break;if(this.#c!==null||this.#m||this.#h)continue;let o=await this.#D(r);if(o!==null)return o==="credential_unusable"?await this.#T():await this.#C(),o}}return"stopped"}async#w(){try{await this.#e.declareCapabilities({signal:this.#l.signal})}catch(e){if(e instanceof w||e instanceof _||!(e instanceof R))throw e;I.error("Could not declare capabilities \u2014 job kinds this build supports will not be published to this agent until the next start; playback is unaffected",{err:e.message})}}async shutdown(e){let n=this.#g;if(n!==null)return I.info("A shutdown is already in progress \u2014 joining it",{cause:e}),n;let r=this.#f(e);return this.#g=r,r}async#f(e){I.info("Shutting down",{cause:e}),await this.#y(e==="fatal"?"fatal":"stopped",n=>this.#R(n))}async#y(e,n){this.#u=!0,this.#o?.abort(),this.#l.abort();let r=io[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#R(e){let{activeRunId:n,launchingRunId:r}=e;if(n!==null){await this.#_(()=>this.#t.report({runId:n,reason:"browser_gone",message:Zt}));return}if(r!==null){await this.#_(()=>this.#t.report({runId:r,reason:"browser_gone",message:Zt}));return}await this.#_(()=>this.#t.retryPending())}async#I(){try{if((await this.#d.runCycle(this.#l.signal)).kind!=="reenroll_required")return null}catch(e){if(e instanceof w)return await this.#v(e),"revoked";throw e}return await this.#b(),"reenroll_required"}#S(){if(this.#u||this.#l.signal.aborted)return;let e=setTimeout(()=>{this.#p=null,this.#O().finally(()=>{this.#S()})},ao);e.unref(),this.#p=e}async#O(){try{if((await this.#d.runCycle(this.#l.signal)).kind!=="reenroll_required")return;this.#m=!0,this.#o?.abort()}catch(e){await this.#x(e)}}#P(){this.#p!==null&&(clearTimeout(this.#p),this.#p=null)}async#k(e){I.warn("A gateway call was refused as superseded \u2014 diagnosing the credential",{operation:e.operation});try{return await this.#d.diagnoseSuperseded(this.#l.signal)==="reenroll_required"}catch(n){if(n instanceof w)return this.#c=n,!1;throw n}}async#N(){let e=new AbortController;this.#o=e;try{return await this.#e.pollDesiredState({waitSec:this.#s,signal:e.signal})}finally{this.#o=null}}async#E(){await this.#d.settle(),Hn(this.#a)}async#v(e){I.error("This agent has been revoked \u2014 disposing, wiping the credential and stopping",{signal:e.signal}),await this.#y("revoked",Qt),await this.#E()}async#T(){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",Qt)}async#C(){await this.#y("fatal",e=>this.#R(e))}async#b(){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",Qt),await this.#E()}async#D(e){if(!(e instanceof R))throw e;let n=this.#L(e);return n.kind==="exit"?n.exit:(this.#i+=1,await ft(n.delayMs,this.#l.signal),null)}#L(e){if(e instanceof _){if(!this.#d.canDiagnoseFromTheWire)return{kind:"exit",exit:"credential_unusable"};let r=fe(this.#i);return I.error("The server refused this credential as superseded, but the probe did not confirm the token family is dead \u2014 the daemon keeps polling on the credential it holds. If this repeats, create a new enrollment code in Progon (Settings \u2192 Agents) and enroll this machine again.",{operation:e.operation,attempt:this.#i,retryInMs:r}),{kind:"retry",delayMs:r}}let n=ye({attempt:this.#i,error:e});return n.retry?(I.warn("Desired-state poll failed \u2014 backing off",{attempt:this.#i,retryInMs:n.delayMs,err:e.message}),{kind:"retry",delayMs:n.delayMs}):(I.error("The desired-state poll was refused definitively and no repetition can change that \u2014 the daemon cannot reconcile without a snapshot, so it is disposing its browser and stopping. Restart duty belongs to the process supervisor.",{reason:n.reason,operation:e.operation,err:e.message}),{kind:"exit",exit:"fatal"})}#A(e){return this.#r.run(e).catch(n=>this.#x(n))}async#x(e){if(e instanceof w){this.#c=e,this.#o?.abort();return}if(e instanceof _){try{await this.#k(e)?this.#m=!0:this.#d.canDiagnoseFromTheWire||(this.#h=!0)}catch(n){I.error("The superseded diagnosis failed after a background gateway refusal",{err:n instanceof Error?n.message:String(n)});return}(this.#m||this.#h||this.#c!==null)&&this.#o?.abort();return}I.error("A background supervisor action failed",{err:e instanceof Error?e.message:String(e)})}async#_(e){try{await e()}catch(n){if(n instanceof _){I.error("This agent token is no longer accepted as current, so the run could not be reported. The credential on disk is left alone \u2014 the next start diagnoses it and will say whether this machine has to be enrolled again.",{operation:n.operation});return}if(n instanceof w){await this.#E(),I.error("This agent was revoked, so the run could not be reported and the credential has been wiped. Create a new enrollment code in Progon (Settings \u2192 Agents) and start the daemon once with PROGON_AGENT_ENROLL_CODE=<code> to enroll this machine again.",{signal:n.signal});return}throw n}}};var so=u("supervisor-boot");async function lo(){let t=ae();so.info("Config loaded",{serverUrlOrigin:new URL(t.serverUrl).origin,serverUrlSource:t.serverUrlSource,stateDir:t.stateDir,headfulOverride:t.headfulOverride,allowInsecureHttps:t.allowInsecureHttps});let e=Ee(),n=await we({config:t,machine:e});so.info("Agent identity resolved",{source:n.source,agentId:n.agentId,hostname:e.hostname,platform:e.platform,arch:e.arch,agentVersion:e.agentVersion});let r=ir({overridePath:t.extensionDistOverride,stateDir:t.stateDir,agentId:n.agentId});await Ue({stdio:"pipe"});let o=new Ze({serverUrl:t.serverUrl,agentToken:n.agentToken}),a=new bt({client:o,stateDir:t.stateDir,identitySource:n.source});return new _t({client:o,stateDir:t.stateDir,pollWaitSec:n.pollWaitSec,tokenRotation:a,createRuntime:i(s=>new pt({stateDir:t.stateDir,extensionDist:r,headfulOverride:t.headfulOverride,allowInsecureHttps:t.allowInsecureHttps,onInstanceLost:s}),"createRuntime")})}i(lo,"bootRunSupervisor");import{createHash as Ts,randomBytes as As}from"node:crypto";import{z as A}from"zod";var co=A.object({requestId:A.uuid(),mode:A.literal("device"),userCode:A.string().min(1),verificationUrl:A.url(),expiresAt:A.iso.datetime({offset:!0}),pollIntervalSec:A.number().int().positive()}),uo=A.object({status:A.literal("authorization_pending"),expiresAt:A.iso.datetime({offset:!0}),pollIntervalSec:A.number().int().positive()}),ws=A.object({companyName:A.string(),approvedByEmail:A.string(),approvedAt:A.string()}),po=A.object({credential:Ge,approval:ws});var mo=u("gateway-enrollment-request"),Rt=class{static{i(this,"GatewayEnrollmentRequestClient")}serverUrl;machine;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.machine=e.machine,this.fetchImpl=e.fetchImpl??Qe}async create(e){let n=await Q({operation:"enrollment_request_create",method:"POST",url:C(this.serverUrl,"/enrollment-requests"),agentToken:null,body:{deviceSecretHash:e,protocolVersion:1,...this.machine},signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:dr}),r=N("enrollment_request_create",co.safeParse(n));return mo.info("Enrollment request opened",{requestId:r.requestId,mode:r.mode,pollIntervalSec:r.pollIntervalSec,expiresAt:r.expiresAt}),r}async poll(e){let n=await Q({operation:"enrollment_request_poll",method:"POST",url:C(this.serverUrl,"/enrollment-requests/poll"),agentToken:null,body:{deviceSecret:e},signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:cr}),r=typeof n=="object"&&n!==null?n:null;if(r!==null&&"credential"in r){let o=N("enrollment_request_poll",po.safeParse(n));return mo.info("Enrollment request approved",{agentId:o.credential.agentId}),{kind:"enrolled",credential:o.credential,approval:o.approval}}if(r!==null&&"status"in r){let o=N("enrollment_request_poll",uo.safeParse(n));return{kind:"pending",expiresAt:o.expiresAt,pollIntervalSec:o.pollIntervalSec}}throw new $("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 Q({operation:"enrollment_request_cancel",method:"POST",url:C(this.serverUrl,"/enrollment-requests/cancel"),agentToken:null,body:{deviceSecret:e},signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:ur})}};import{spawn as Es}from"node:child_process";var Ce=u("browser-open");function St(t){return t!==void 0&&t!==""}i(St,"isSet");function vs(t,e){return!(St(t.SSH_CONNECTION)||St(t.SSH_TTY)||e==="linux"&&!St(t.DISPLAY)&&!St(t.WAYLAND_DISPLAY))}i(vs,"shouldAttemptBrowserOpen");var bs=/[&|^<>"'` ]/;function _s(t){let e;try{e=new URL(t)}catch{return!1}return e.protocol!=="http:"&&e.protocol!=="https:"||t!==e.href?!1:!bs.test(t)}i(_s,"isSpawnSafeUrl");function Rs(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(Rs,"browserOpenCommand");function ho(t,e,n){if(!vs(e,n)){Ce.debug("Not opening a browser: this host has no desktop to open one on",{platform:n});return}if(!_s(t)){Ce.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=Rs(t,n);if(r===null){Ce.debug("Not opening a browser: no opener is defined for this platform",{platform:n});return}try{let o=Es(r.command,[...r.args],{detached:!0,stdio:"ignore"});o.on("error",a=>{Ce.debug("Could not start the browser; the approval URL was printed instead",{platform:n,command:r.command,err:a.message})}),o.unref()}catch(o){Ce.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(ho,"openVerificationUrl");var Ss=30,ks=5;function go(t){return{intervalSec:t.pollIntervalSec,deadlineMs:t.timeoutSec===null?t.expiresAtMs:Math.min(t.expiresAtMs,t.nowMs+t.timeoutSec*1e3)}}i(go,"initialPollSchedule");function kt(t,e){if(e.kind==="pending")return{state:t,delayMs:t.intervalSec*1e3};if(e.kind==="slow_down"){let r=t.intervalSec+ks,o=e.retryAfterSec!==null&&e.retryAfterSec>r?e.retryAfterSec:r,a=Math.min(o,Ss);return{state:{intervalSec:a,deadlineMs:t.deadlineMs},delayMs:a*1e3}}let n=fe(e.attempt,e.rng);return{state:t,delayMs:Math.max(t.intervalSec*1e3,n)}}i(kt,"nextPollDelayMs");function fo(t,e){return e>=t.deadlineMs}i(fo,"isDeadlinePassed");function yo(t,e,n){return Math.max(0,Math.min(e,t.deadlineMs-n))}i(yo,"clampDelayToDeadline");var Re=u("device-enrollment"),xs=24,Is=2e3,en=0,_e=1,Eo=130,Os="This machine is already enrolled. Start the daemon with: progon-agent start",Ps="Enrollment was denied in the browser. Nothing was created on this machine.",Ns="Cancelled. Nothing was saved on this machine.",Cs="progon-agent: interrupted again \u2014 exiting immediately. The enrollment request was not withdrawn; it expires on its own. Nothing was saved on this machine.";function wo(t){return`Enrollment request expired. Run: progon-agent enroll --server ${t}`}i(wo,"expiredLine");function Ds(t,e,n){return`This machine is already enrolled against ${t}, not ${e}. An agent credential is only valid at the deployment that issued it, so nothing was requested from ${e}.
33
35
  To enroll this machine for ${e} as well, give the second agent its own state directory: PROGON_RUNNER_STATE_DIR=<dir> progon-agent enroll --server ${e} \u2014 and give 'progon-agent start' the same variable, since that directory is where the second credential and its server live.
34
- To move this machine to ${e} instead, remove the state file in ${n} first, then run: progon-agent enroll --server ${e}`}o(bs,"otherDeploymentLine");function ks(t,e){return`Timed out after ${t}s waiting for approval. The request is still open \u2014 approve at: ${e}`}o(ks,"timedOutLine");function Ts(t){return`Enrollment could not be completed: the request was already used and no credential reached this machine. Run: progon-agent enroll --server ${t}`}o(Ts,"alreadyCompletedLine");function As(t){return`Enrollment request is no longer valid. Run: progon-agent enroll --server ${t}`}o(As,"noLongerValidLine");async function yo(t){let e=t.env??process.env;t.serverUrl!==void 0&&(process.env.PROGON_SERVER_URL=t.serverUrl);let n=re(),r=fe(),i=e.PROGON_AGENT_ENROLL_CODE;if(i!==void 0&&i!=="")return Os(n,r,t.fetchImpl,t.rng);let a=G(n.stateDir);if(a!==null)return je(a.serverUrl,n.serverUrl)?(process.stdout.write(`${vs}
35
- `),Xt):(process.stdout.write(`${bs(a.serverUrl,n.serverUrl,n.stateDir)}
36
- `),Ee);let s=ys(ws).toString("base64url"),l=new vt(t.fetchImpl===void 0?{serverUrl:n.serverUrl,machine:r}:{serverUrl:n.serverUrl,machine:r,fetchImpl:t.fetchImpl}),d=await l.create(Cs(s));return Ps(d),t.openBrowser&&uo(d.verificationUrl,e,process.platform),Is({client:l,config:n,created:d,deviceSecret:s,timeoutSec:t.timeoutSec,rng:t.rng})}o(yo,"runDeviceEnrollment");async function Is(t){let{client:e,config:n,created:r,deviceSecret:i,timeoutSec:a,rng:s}=t,l=Date.parse(r.expiresAt),d=mo({pollIntervalSec:r.pollIntervalSec,expiresAtMs:l,timeoutSec:a,nowMs:Date.now()}),m=d.intervalSec*1e3,f=0,h={signal:null},p=new AbortController,b=o(R=>{h.signal!==null&&(process.stderr.write(`${Rs}
37
- `),process.exit(fo)),h.signal=R,p.abort()},"onSignal");process.on("SIGINT",b),process.on("SIGTERM",b);try{for(;;){if(await pt(ho(d,m,Date.now()),p.signal),h.signal!==null)return await xs(e,i,h.signal);if(po(d,Date.now()))return a!==null&&d.deadlineMs<l?process.stdout.write(`${ks(a,r.verificationUrl)}
38
- `):process.stdout.write(`${go(n.serverUrl)}
39
- `),Ee;let R;try{R=await e.poll(i)}catch(k){if(k instanceof le)return process.stdout.write(`${_s}
40
- `),Ee;if(k instanceof de)return process.stdout.write(`${go(n.serverUrl)}
41
- `),Ee;if(k instanceof ce)return ve.warn("The enrollment request was already completed on the server; no credential reached this machine and nothing was saved",{requestId:r.requestId,errorCode:k.errorCode,status:k.status}),process.stdout.write(`${Ts(n.serverUrl)}
42
- `),Ee;if(k instanceof ue)return ve.warn("The server no longer recognises this enrollment request",{requestId:r.requestId,errorCode:k.errorCode,status:k.status}),process.stdout.write(`${As(n.serverUrl)}
43
- `),Ee;if(k instanceof se){let _e=St(d,{kind:"slow_down",retryAfterSec:k.retryAfterSec});d=_e.state,m=_e.delayMs,ve.warn("The server asked this machine to poll more slowly",{intervalSec:d.intervalSec,retryAfterSec:k.retryAfterSec});continue}if(k instanceof M||k instanceof v&&k.status>=500){let _e=St(d,{kind:"transport_error",attempt:f,rng:s});f+=1,d=_e.state,m=_e.delayMs,ve.warn("The enrollment poll failed; retrying until the request expires",{attempt:f,delayMs:m,err:k.message});continue}throw k}if(R.kind==="enrolled")return ne(n.stateDir,{agentId:R.credential.agentId,agentToken:R.credential.agentToken,protocolVersion:R.credential.protocolVersion,serverUrl:n.serverUrl,tokenRotatedAt:null}),process.stdout.write(`Enrolled into ${R.approval.companyName} (approved by ${R.approval.approvedByEmail}). Start the daemon: progon-agent start
44
- `),Xt;f=0;let Ne=St(d,{kind:"pending"});d=Ne.state,m=Ne.delayMs}}finally{process.off("SIGINT",b),process.off("SIGTERM",b)}}o(Is,"waitForApproval");async function xs(t,e,n){try{await mt({operation:"device enrollment cancel",timeoutMs:Es,work:o(()=>t.cancel(e),"work")})}catch(r){ve.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(`${Ss}
45
- `),fo}o(xs,"cancelRequest");async function Os(t,e,n,r){let i=await ge({config:t,machine:e,fetchImpl:n,rng:r});return ct(i,t),ve.info("This machine is enrolled \u2014 start the daemon with: progon-agent start",{agentId:i.agentId,hostname:e.hostname,stateDir:t.stateDir}),Xt}o(Os,"redeemLegacyEnrollmentCode");function Ps(t){process.stdout.write(`Enrollment requested for this machine.
36
+ To move this machine to ${e} instead, remove the state file in ${n} first, then run: progon-agent enroll --server ${e}`}i(Ds,"otherDeploymentLine");function Ls(t,e){return`Timed out after ${t}s waiting for approval. The request is still open \u2014 approve at: ${e}`}i(Ls,"timedOutLine");function Gs(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(Gs,"alreadyCompletedLine");function Ms(t){return`Enrollment request is no longer valid. Run: progon-agent enroll --server ${t}`}i(Ms,"noLongerValidLine");async function vo(t){let e=t.env??process.env;t.serverUrl!==void 0&&(process.env.PROGON_SERVER_URL=t.serverUrl);let n=ae(),r=Ee(),o=e.PROGON_AGENT_ENROLL_CODE;if(o!==void 0&&o!=="")return Fs(n,r,t.fetchImpl,t.rng);let a=M(n.stateDir);if(a!==null)return Ve(a.serverUrl,n.serverUrl)?(process.stdout.write(`${Os}
37
+ `),en):(process.stdout.write(`${Ds(a.serverUrl,n.serverUrl,n.stateDir)}
38
+ `),_e);let s=As(xs).toString("base64url"),l=new Rt(t.fetchImpl===void 0?{serverUrl:n.serverUrl,machine:r}:{serverUrl:n.serverUrl,machine:r,fetchImpl:t.fetchImpl}),d=await l.create(qs(s));return js(d),t.openBrowser&&ho(d.verificationUrl,e,process.platform),Us({client:l,config:n,created:d,deviceSecret:s,timeoutSec:t.timeoutSec,rng:t.rng})}i(vo,"runDeviceEnrollment");async function Us(t){let{client:e,config:n,created:r,deviceSecret:o,timeoutSec:a,rng:s}=t,l=Date.parse(r.expiresAt),d=go({pollIntervalSec:r.pollIntervalSec,expiresAtMs:l,timeoutSec:a,nowMs:Date.now()}),m=d.intervalSec*1e3,y=0,g={signal:null},h=new AbortController,k=i(S=>{g.signal!==null&&(process.stderr.write(`${Cs}
39
+ `),process.exit(Eo)),g.signal=S,h.abort()},"onSignal");process.on("SIGINT",k),process.on("SIGTERM",k);try{for(;;){if(await ft(yo(d,m,Date.now()),h.signal),g.signal!==null)return await $s(e,o,g.signal);if(fo(d,Date.now()))return a!==null&&d.deadlineMs<l?process.stdout.write(`${Ls(a,r.verificationUrl)}
40
+ `):process.stdout.write(`${wo(n.serverUrl)}
41
+ `),_e;let S;try{S=await e.poll(o)}catch(T){if(T instanceof ue)return process.stdout.write(`${Ps}
42
+ `),_e;if(T instanceof pe)return process.stdout.write(`${wo(n.serverUrl)}
43
+ `),_e;if(T instanceof me)return Re.warn("The enrollment request was already completed on the server; no credential reached this machine and nothing was saved",{requestId:r.requestId,errorCode:T.errorCode,status:T.status}),process.stdout.write(`${Gs(n.serverUrl)}
44
+ `),_e;if(T instanceof he)return Re.warn("The server no longer recognises this enrollment request",{requestId:r.requestId,errorCode:T.errorCode,status:T.status}),process.stdout.write(`${Ms(n.serverUrl)}
45
+ `),_e;if(T instanceof ce){let Se=kt(d,{kind:"slow_down",retryAfterSec:T.retryAfterSec});d=Se.state,m=Se.delayMs,Re.warn("The server asked this machine to poll more slowly",{intervalSec:d.intervalSec,retryAfterSec:T.retryAfterSec});continue}if(T instanceof U||T instanceof b&&T.status>=500){let Se=kt(d,{kind:"transport_error",attempt:y,rng:s});y+=1,d=Se.state,m=Se.delayMs,Re.warn("The enrollment poll failed; retrying until the request expires",{attempt:y,delayMs:m,err:T.message});continue}throw T}if(S.kind==="enrolled")return ie(n.stateDir,{agentId:S.credential.agentId,agentToken:S.credential.agentToken,protocolVersion:S.credential.protocolVersion,serverUrl:n.serverUrl,tokenRotatedAt:null}),process.stdout.write(`Enrolled into ${S.approval.companyName} (approved by ${S.approval.approvedByEmail}). Start the daemon: progon-agent start
46
+ `),en;y=0;let De=kt(d,{kind:"pending"});d=De.state,m=De.delayMs}}finally{process.off("SIGINT",k),process.off("SIGTERM",k)}}i(Us,"waitForApproval");async function $s(t,e,n){try{await gt({operation:"device enrollment cancel",timeoutMs:Is,work:i(()=>t.cancel(e),"work")})}catch(r){Re.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(`${Ns}
47
+ `),Eo}i($s,"cancelRequest");async function Fs(t,e,n,r){let o=await we({config:t,machine:e,fetchImpl:n,rng:r});return mt(o,t),Re.info("This machine is enrolled \u2014 start the daemon with: progon-agent start",{agentId:o.agentId,hostname:e.hostname,stateDir:t.stateDir}),en}i(Fs,"redeemLegacyEnrollmentCode");function js(t){process.stdout.write(`Enrollment requested for this machine.
46
48
  Confirmation code: ${t.userCode}
47
49
  Approve at: ${t.verificationUrl}
48
- Waiting for approval (expires in ${Ns(t.expiresAt)})...
49
- `)}o(Ps,"printRequestOpened");function Ns(t){let e=Date.parse(t)-Date.now();return`${Math.ceil(e/6e4)}m`}o(Ns,"describeExpiry");function Cs(t){return fs("sha256").update(t,"utf8").digest("hex")}o(Cs,"sha256Hex");var Rt=u("cli"),wo=`progon-agent \u2014 the Progon local agent (CONTRACT-la \xA78)
50
+ Waiting for approval (expires in ${Bs(t.expiresAt)})...
51
+ `)}i(js,"printRequestOpened");function Bs(t){let e=Date.parse(t)-Date.now();return`${Math.ceil(e/6e4)}m`}i(Bs,"describeExpiry");function qs(t){return Ts("sha256").update(t,"utf8").digest("hex")}i(qs,"sha256Hex");var Tt=u("cli"),bo=`progon-agent \u2014 the Progon local agent (CONTRACT-la \xA78)
50
52
 
51
53
  Usage:
52
54
  progon-agent enroll <code> [--server <url>] Redeem a one-shot enrollment code (\xA75.1) and
53
55
  persist this machine's agent credential.
56
+ --server is optional on an installed package.
54
57
  progon-agent enroll [--server <url>] Enroll WITHOUT a code: open a request, and a
55
58
  [--no-open] [--timeout s] person approves this machine in their browser
56
59
  under their own Progon session. The command
@@ -78,11 +81,16 @@ Which server the commands talk to, highest precedence first:
78
81
  1. --server <url> -> 'enroll' only; sets PROGON_SERVER_URL for that one command.
79
82
  2. PROGON_SERVER_URL -> from the environment.
80
83
  3. the enrolled deployment -> the server this machine's state file records. This is why
81
- 'start' needs no environment after 'enroll': the URL was
82
- persisted with the credential. It is NOT read when
83
- PROGON_AGENT_TOKEN is set (that token names no deployment,
84
- and it is also the path for recovering from a broken state
85
- file), so there the variable is required.
84
+ 'start' needs nothing after 'enroll': the URL was persisted
85
+ with the credential. It is NOT read when PROGON_AGENT_TOKEN
86
+ is set \u2014 that token names no deployment, and it is also the
87
+ path for recovering from a broken state file.
88
+ 4. the deployment this package -> extension-bundle.json's appUrl. An installed progon-agent is
89
+ was built for built for ONE Progon and carries its address (the bundled
90
+ extension is compiled against it), so on a clean machine
91
+ 'progon-agent enroll && progon-agent start' needs no
92
+ arguments. A source checkout has no such file and must be
93
+ given --server or PROGON_SERVER_URL.
86
94
  When PROGON_SERVER_URL IS set it must still match the enrollment \u2014 a pgat_ token is
87
95
  meaningless at another deployment, and 'start' refuses rather than authenticate blind.
88
96
 
@@ -94,9 +102,9 @@ with Ctrl-C \u2014 the first Ctrl-C withdraws the pending request before exiting
94
102
  exits at once and leaves the request to expire on its own.
95
103
 
96
104
  Environment (see CONTRACT-la \xA78 for the full list):
97
- PROGON_SERVER_URL base URL of the Progon backend. Required until this machine is
98
- enrolled, and required alongside PROGON_AGENT_TOKEN; otherwise
99
- see the server precedence above.
105
+ PROGON_SERVER_URL base URL of the Progon backend. Optional on an installed
106
+ package \u2014 see the server precedence above; required only where
107
+ neither an enrollment nor a bundled deployment exists.
100
108
  PROGON_AGENT_EXTENSION_DIST optional \u2014 absolute path of an already agent-mode qa-extension
101
109
  dist, overriding the one bundled in this package (dev/E2E).
102
110
  Required by 'start' ONLY on the PROGON_AGENT_TOKEN path: that
@@ -105,9 +113,10 @@ Environment (see CONTRACT-la \xA78 for the full list):
105
113
  name one (\xA71 D-C, \xA715 A30.1).
106
114
  PROGON_AGENT_TOKEN optional \u2014 an existing credential, takes precedence over the
107
115
  state file and over enrollment.
108
- PROGON_AGENT_HEADFUL optional \u2014 show the browser on this machine's desktop.`;function Gs(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"?Us(n):{kind:"usage",reason:`unknown command '${e}'`}}o(Gs,"parseCliArgs");function Ms(t){return t.startsWith("-")&&t.length<32}o(Ms,"isOptionInCodeSlot");function Us(t){let[e,...n]=t;if(e===void 0||Ms(e))return $s(t);if(n.length===0)return{kind:"enroll",code:e,serverUrl:void 0};let[r,i,...a]=n;return r!=="--server"?{kind:"usage",reason:`unknown option '${String(r)}' for 'enroll'`}:i===void 0?{kind:"usage",reason:"'--server' needs a URL"}:a.length>0?{kind:"usage",reason:"unexpected arguments after '--server'"}:{kind:"enroll",code:e,serverUrl:i}}o(Us,"parseEnroll");var Eo=1,vo=3600;function $s(t){let e,n=!0,r=null;for(let i=0;i<t.length;i+=1){let a=t[i];if(a==="--no-open"){n=!1;continue}if(a==="--server"){let s=t[i+1];if(s===void 0)return{kind:"usage",reason:"'--server' needs a URL"};e=s,i+=1;continue}if(a==="--timeout"){let s=t[i+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 l=Number(s);if(l<Eo||l>vo)return{kind:"usage",reason:`'--timeout' must be between ${Eo} and ${vo} seconds, got '${s}'`};r=l,i+=1;continue}return{kind:"usage",reason:`unknown option '${String(a)}' for 'enroll'`}}return{kind:"enroll-device",serverUrl:e,openBrowser:n,timeoutSec:r}}o($s,"parseEnrollDevice");async function Fs(t){let e=Gs(t);switch(e.kind){case"usage":return e.reason===null?(process.stdout.write(`${wo}
116
+ PROGON_AGENT_HEADFUL optional \u2014 show the browser on this machine's desktop.`;function ko(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"?Ks(n):{kind:"usage",reason:`unknown command '${e}'`}}i(ko,"parseCliArgs");function Js(t){return t.startsWith("-")&&t.length<32}i(Js,"isOptionInCodeSlot");function Ks(t){let[e,...n]=t;if(e===void 0||Js(e))return Ws(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(Ks,"parseEnroll");var _o=1,Ro=3600;function Ws(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 l=Number(s);if(l<_o||l>Ro)return{kind:"usage",reason:`'--timeout' must be between ${_o} and ${Ro} seconds, got '${s}'`};r=l,o+=1;continue}return{kind:"usage",reason:`unknown option '${String(a)}' for 'enroll'`}}return{kind:"enroll-device",serverUrl:e,openBrowser:n,timeoutSec:r}}i(Ws,"parseEnrollDevice");async function Ys(t){let e=ko(t);switch(e.kind){case"usage":return e.reason===null?(process.stdout.write(`${bo}
109
117
  `),0):(process.stderr.write(`progon-agent: ${e.reason}
110
118
 
111
- ${wo}
112
- `),2);case"enroll":return qs(e.code,e.serverUrl);case"enroll-device":return yo({serverUrl:e.serverUrl,openBrowser:e.openBrowser,timeoutSec:e.timeoutSec});case"install-browser":return js();case"start":return Bs()}}o(Fs,"runAgentCli");async function js(){return await Ge({stdio:"inherit"}),0}o(js,"installBrowser");async function qs(t,e){process.env.PROGON_AGENT_ENROLL_CODE=t,e!==void 0&&(process.env.PROGON_SERVER_URL=e);let n=re(),r=fe(),i=await ge({config:n,machine:r});return ct(i,n),Rt.info("This machine is enrolled \u2014 start the daemon with: progon-agent start",{agentId:i.agentId,hostname:r.hostname,stateDir:n.stateDir}),0}o(qs,"enrollThisMachine");async function Bs(){Kn(),Rt.info("progon-agent starting");let t=await io();return Wn(async n=>{await t.shutdown(n)}),await t.run()==="revoked"?(Rt.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):(Rt.info("progon-agent stopped"),0)}o(Bs,"startDaemon");var _o=process.argv[1];_o!==void 0&&import.meta.url===Ls(Ds(_o)).href&&Fs(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)})+`
113
- `),process.exit(1)});export{Gs as parseCliArgs,Fs as runAgentCli};
119
+ ${bo}
120
+ `),2);case"enroll":return zs(e.code,e.serverUrl);case"enroll-device":return vo({serverUrl:e.serverUrl,openBrowser:e.openBrowser,timeoutSec:e.timeoutSec});case"install-browser":return Xs();case"start":return Zs()}}i(Ys,"runAgentCli");async function Xs(){return await Ue({stdio:"inherit"}),0}i(Xs,"installBrowser");async function zs(t,e){process.env.PROGON_AGENT_ENROLL_CODE=t,e!==void 0&&(process.env.PROGON_SERVER_URL=e);let n=ae(),r=Ee(),o=await we({config:n,machine:r});return mt(o,n),Tt.info("This machine is enrolled \u2014 start the daemon with: progon-agent start",{agentId:o.agentId,hostname:r.hostname,stateDir:n.stateDir}),0}i(zs,"enrollThisMachine");async function Zs(){Qn(),Tt.info("progon-agent starting");let t=await lo();return er(async n=>{await t.shutdown(n)}),await t.run()==="revoked"?(Tt.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. The wipe removed the state file, so an installed package now takes the deployment it was built for; on a source checkout add --server <url>."),1):(Tt.info("progon-agent stopped"),0)}i(Zs,"startDaemon");function Qs(t,e){let n=G(t instanceof Error?t.message:String(t));if((e.kind==="enroll"||e.kind==="enroll-device")&&t instanceof p)return`${n}
121
+ `;let o=t instanceof Error?t.stack:void 0;return JSON.stringify({level:"fatal",module:"cli",msg:"progon-agent failed",err:n,stack:o===void 0?void 0:G(o)})+`
122
+ `}i(Qs,"formatCliFailure");var So=process.argv[1];if(So!==void 0&&import.meta.url===Hs(Vs(So)).href){let t=process.argv.slice(2);Ys(t).then(e=>{process.exit(e)}).catch(e=>{process.stderr.write(Qs(e,ko(t))),process.exit(1)})}export{Qs as formatCliFailure,ko as parseCliArgs,Ys as runAgentCli};
@@ -2,5 +2,5 @@
2
2
  "extensionVersion": "1.5.0",
3
3
  "extensionCommit": "80ba89632c63c6c45699f255217ef4e57fcddf81",
4
4
  "appUrl": "https://app.progon.io",
5
- "bundledAt": "2026-09-09T14:41:31.868Z"
5
+ "bundledAt": "2026-09-09T15:07:07.336Z"
6
6
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "progon-agent",
3
- "version": "1.1.2",
3
+ "version": "1.1.3",
4
4
  "description": "Progon local agent — runs Progon scenarios on your machine in its own Chromium with the Progon extension.",
5
5
  "type": "module",
6
6
  "license": "SEE LICENSE IN LICENSE",