progon-agent 1.1.0 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +75 -24
- package/dist/supervisor/cli.js +64 -41
- package/extension-bundle.json +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -102,6 +102,9 @@ machine, install included:
|
|
|
102
102
|
npm i -g progon-agent && progon-agent enroll <code> --server "https://your-progon-host" && 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.
|
|
107
|
+
|
|
105
108
|
On Windows, run this in PowerShell 7 or cmd — Windows PowerShell 5.1 does not support `&&`;
|
|
106
109
|
there, run the commands one at a time.
|
|
107
110
|
|
|
@@ -138,9 +141,10 @@ Enrollment binds this machine to one agent record in your Progon company and giv
|
|
|
138
141
|
progon-agent enroll <code> --server "https://your-progon-host"
|
|
139
142
|
```
|
|
140
143
|
|
|
141
|
-
`--server` is how `PROGON_SERVER_URL` gets set for this command; it
|
|
142
|
-
|
|
143
|
-
|
|
144
|
+
`--server` is how `PROGON_SERVER_URL` gets set for this command; omit it only if that variable is
|
|
145
|
+
already exported, or if this machine is already enrolled and you mean the deployment it is enrolled
|
|
146
|
+
against. The command redeems the code, persists the credential — the server URL with it — and exits:
|
|
147
|
+
it does not start the daemon, does not download Chromium and does not need the extension dist.
|
|
144
148
|
|
|
145
149
|
### Enroll without a code (browser approval)
|
|
146
150
|
|
|
@@ -190,9 +194,10 @@ itself with ever reaches the terminal, which is what makes this flow safe to run
|
|
|
190
194
|
whose transcript you do not control. The confirmation code is useless to anyone without your own
|
|
191
195
|
web session.
|
|
192
196
|
|
|
193
|
-
Exit codes: `0` enrolled
|
|
194
|
-
expired, `--timeout` exhausted, already completed from another machine, no
|
|
195
|
-
|
|
197
|
+
Exit codes: `0` enrolled, or already enrolled **against this same server**; `1` the enrollment did
|
|
198
|
+
not happen — denied, expired, `--timeout` exhausted, already completed from another machine, no
|
|
199
|
+
longer valid, this machine is already enrolled against a **different** server, or the network was
|
|
200
|
+
still failing when the deadline passed; `2` the command line was wrong; `130` interrupted
|
|
196
201
|
with Ctrl-C — the first Ctrl-C withdraws the pending request before exiting, a second one exits at
|
|
197
202
|
once and leaves the request to expire on its own.
|
|
198
203
|
|
|
@@ -227,14 +232,51 @@ Precedence, highest first:
|
|
|
227
232
|
Two consequences worth knowing:
|
|
228
233
|
|
|
229
234
|
- **The server URL must match the enrollment.** On the state-file path the daemon refuses to start
|
|
230
|
-
if `PROGON_SERVER_URL`
|
|
231
|
-
token is meaningless at another deployment, and authenticating blind would
|
|
232
|
-
401 backoff.
|
|
235
|
+
if `PROGON_SERVER_URL` is set to something other than the URL the credential was enrolled
|
|
236
|
+
against — a `pgat_` token is meaningless at another deployment, and authenticating blind would
|
|
237
|
+
show up as an endless 401 backoff.
|
|
233
238
|
- **`PROGON_AGENT_TOKEN` alone is not enough to run.** An env token carries no `agentId`, and the
|
|
234
239
|
extension's `agent-manifest.json` must name one, so that path additionally requires
|
|
235
240
|
`PROGON_AGENT_EXTENSION_DIST` pointing at an already agent-mode dist. For ordinary operation,
|
|
236
241
|
enroll instead.
|
|
237
242
|
|
|
243
|
+
### Which server the daemon uses
|
|
244
|
+
|
|
245
|
+
Precedence, highest first:
|
|
246
|
+
|
|
247
|
+
1. **`--server <url>`** on the `enroll` command — it sets `PROGON_SERVER_URL` for that one process.
|
|
248
|
+
2. **`PROGON_SERVER_URL`** in the environment.
|
|
249
|
+
3. **The enrolled deployment** — the `serverUrl` this machine's state file records. This is why
|
|
250
|
+
`progon-agent start` needs no environment after `enroll`: the URL was persisted together with
|
|
251
|
+
the credential it belongs to.
|
|
252
|
+
|
|
253
|
+
Two rules complete it:
|
|
254
|
+
|
|
255
|
+
- **Set means checked, not preferred.** When `PROGON_SERVER_URL` is set it must still match the
|
|
256
|
+
enrollment; `start` refuses on a mismatch rather than authenticating blind. Unsetting it is a
|
|
257
|
+
valid way to go back to the enrolled server.
|
|
258
|
+
- **`PROGON_AGENT_TOKEN` requires it.** That token names no deployment, and it is also the path
|
|
259
|
+
for recovering from a state file that cannot be read — so on that path the state file is not
|
|
260
|
+
consulted for the server either, and `PROGON_SERVER_URL` is required.
|
|
261
|
+
|
|
262
|
+
On a machine that is not enrolled and has no `PROGON_SERVER_URL`, every command that needs a server
|
|
263
|
+
says so and names both remedies. `progon-agent install-browser` is the exception that needs neither:
|
|
264
|
+
it reads no configuration at all.
|
|
265
|
+
|
|
266
|
+
### Enrolling one machine into two deployments
|
|
267
|
+
|
|
268
|
+
The credential and the server URL live together in one state directory, so a second enrollment gets
|
|
269
|
+
a second directory:
|
|
270
|
+
|
|
271
|
+
```bash
|
|
272
|
+
PROGON_RUNNER_STATE_DIR=~/.progon-agent-staging progon-agent enroll --server "https://staging.example"
|
|
273
|
+
PROGON_RUNNER_STATE_DIR=~/.progon-agent-staging progon-agent start
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
Running `enroll` for a different deployment **without** a separate state directory is refused: the
|
|
277
|
+
command reports which deployment this machine is already enrolled against, exits `1`, and removes
|
|
278
|
+
nothing — a credential is only ever deleted by you.
|
|
279
|
+
|
|
238
280
|
---
|
|
239
281
|
|
|
240
282
|
## 4. Run
|
|
@@ -243,7 +285,9 @@ Two consequences worth knowing:
|
|
|
243
285
|
progon-agent start
|
|
244
286
|
```
|
|
245
287
|
|
|
246
|
-
Requires
|
|
288
|
+
Requires an enrolled machine, and nothing else: the server comes from the state file the
|
|
289
|
+
enrollment wrote, so no environment variable is needed (set `PROGON_SERVER_URL` and it must match
|
|
290
|
+
that enrollment). The daemon boots (config → identity →
|
|
247
291
|
extension dist → Chromium → gateway), then reconciles the backend's desired state and executes the
|
|
248
292
|
runs it is given, until you stop it.
|
|
249
293
|
|
|
@@ -286,18 +330,18 @@ A `401` is _not_ revocation: it backs off and retries, and never wipes anything.
|
|
|
286
330
|
|
|
287
331
|
### Runtime
|
|
288
332
|
|
|
289
|
-
| Variable | Required
|
|
290
|
-
| ----------------------------------- |
|
|
291
|
-
| `PROGON_SERVER_URL` |
|
|
292
|
-
| `PROGON_AGENT_TOKEN` | no
|
|
293
|
-
| `PROGON_AGENT_ENROLL_CODE` | no
|
|
294
|
-
| `PROGON_RUNNER_STATE_DIR` | no
|
|
295
|
-
| `PROGON_AGENT_EXTENSION_DIST` | no
|
|
296
|
-
| `PROGON_AGENT_HEADFUL` | no
|
|
297
|
-
| `PROGON_AGENT_ALLOW_INSECURE_HTTPS` | no
|
|
298
|
-
| `PROGON_AGENT_EXTRA_CA_CERTS` | no
|
|
299
|
-
| `PROGON_LOG_LEVEL` | no
|
|
300
|
-
| `NODE_ENV` | no
|
|
333
|
+
| Variable | Required | Meaning |
|
|
334
|
+
| ----------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
335
|
+
| `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). |
|
|
336
|
+
| `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. |
|
|
337
|
+
| `PROGON_AGENT_ENROLL_CODE` | no | One-shot enrollment code, the env form of `progon-agent enroll <code>`. Must be at least 32 characters. |
|
|
338
|
+
| `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. |
|
|
339
|
+
| `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. |
|
|
340
|
+
| `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. |
|
|
341
|
+
| `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). |
|
|
342
|
+
| `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. |
|
|
343
|
+
| `PROGON_LOG_LEVEL` | no | pino log level. Default: `info` when `NODE_ENV=production`, `debug` otherwise. |
|
|
344
|
+
| `NODE_ENV` | no | Default `production`. Anything else additionally switches logging to human-readable `pino-pretty` output. |
|
|
301
345
|
|
|
302
346
|
### Inherited by the Chromium installer and launch
|
|
303
347
|
|
|
@@ -357,8 +401,15 @@ npm i -g progon-agent@latest
|
|
|
357
401
|
```
|
|
358
402
|
|
|
359
403
|
**`start` fails saying the credential was enrolled against a different server.** `PROGON_SERVER_URL`
|
|
360
|
-
|
|
361
|
-
new
|
|
404
|
+
is set to something the enrollment does not match. Point it back, unset it — an enrolled machine
|
|
405
|
+
reads the server from its own state file — or remove the state file and enroll against the new
|
|
406
|
+
deployment.
|
|
407
|
+
|
|
408
|
+
**`start` fails saying this machine is not enrolled and `PROGON_SERVER_URL` is not set.** Nothing
|
|
409
|
+
on this machine names a deployment: there is no state file in the state directory and no
|
|
410
|
+
environment variable. Enroll it (`progon-agent enroll --server "https://your-progon-host"`), or
|
|
411
|
+
export `PROGON_SERVER_URL`. If you enrolled with `PROGON_RUNNER_STATE_DIR` set, `start` needs the
|
|
412
|
+
same variable — that is where the credential is.
|
|
362
413
|
|
|
363
414
|
**The daemon exits 1 mid-run reporting a revocation.** The agent was revoked server-side and its
|
|
364
415
|
local credential has been wiped. Mint a new code and re-enroll — see
|
package/dist/supervisor/cli.js
CHANGED
|
@@ -1,39 +1,49 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`);function
|
|
4
|
-
`),process.kill(process.pid,h)},"handler");
|
|
5
|
-
${
|
|
6
|
-
${
|
|
7
|
-
`);if(
|
|
8
|
-
`))wn(s,e)}),t.on("end",()=>{let r=n;n="",wn(r,e)})}i(yn,"forwardLinesToLogger");function wn(t,e){let n=t.replace(/\r/g,"").trim();n!==""&&Tt.info("Chromium provisioning output",{stream:e,line:n})}i(wn,"logLine");import{homedir as pi}from"node:os";import{isAbsolute as xn,join as Ge}from"node:path";import{Agent as zo,EnvHttpProxyAgent as Zo}from"undici";var En=u("gateway-proxy"),Qo=["http_proxy","HTTP_PROXY"],ei=["https_proxy","HTTPS_PROXY"],ti=["no_proxy","NO_PROXY"];function ni(t){return t.http!==void 0||t.https!==void 0}i(ni,"gatewayIsProxied");var ri=/^[A-Za-z][A-Za-z0-9+.-]*:\/\//,oi=/:\d+$/,ii=/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)?[^/?#]*@/;function ai(t){let e=ii.exec(t);if(e===null)return t;let n=e[1];return`${n===void 0?"":n}***@${t.slice(e[0].length)}`}i(ai,"withoutProxyCredentials");function te(t,e,n){return new Error(`[config] ${t} does not name a proxy this agent can use: ${n}. Got: ${JSON.stringify(ai(e))}. Accepted: an absolute "http://host:port" (or "https://host:port"), or the scheme-less curl form "host:port", which is read as "http://host:port". The agent-gateway transport speaks HTTP proxying only \u2014 a SOCKS proxy cannot carry it. Unset ${t} to connect to the server directly. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`)}i(te,"refuseProxyValue");function _n(t,e){for(let n of e){let r=t[n];if(r!==void 0)return r===""?void 0:{variable:n,raw:r}}}i(_n,"readProxyVariable");function si(t){for(let e of ti){let n=t[e];if(n!==void 0)return n}}i(si,"readNoProxy");function bn(t,e){if(ri.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(!oi.test(r))throw te(t,e,'it carries no scheme, so it is read as the curl "host:port" form, and it names no port');let o=`http://${e}`,a;try{a=new URL(o)}catch{throw te(t,e,'it is neither a URL nor a "host:port" pair')}if(a.hostname==="")throw te(t,e,"it names no host");return{variable:t,url:o,schemeCompleted:!0}}i(bn,"parseProxyValue");function At(t){let e=_n(t,Qo),n=_n(t,ei);return{http:e===void 0?void 0:bn(e.variable,e.raw),https:n===void 0?void 0:bn(n.variable,n.raw),noProxy:si(t)}}i(At,"resolveGatewayProxyConfig");function vn(t,e,n){if(!ni(t))return new zo(e);En.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&&En.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 Zo(o)}i(vn,"createProxyAwareDispatcher");function Sn(t){At(t)}i(Sn,"validateGatewayProxyEnv");import{readFileSync as li,statSync as di}from"node:fs";import{isAbsolute as ci}from"node:path";import{rootCertificates as kn}from"node:tls";var ui=u("gateway-tls-trust"),Le="PROGON_AGENT_EXTRA_CA_CERTS";function De(t,e,n){let r=`[config] ${Le} 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 ${Le} to trust only the public roots.`;return n===void 0?new Error(r):new Error(r,{cause:n})}i(De,"refuseExtraCaValue");function Rn(t){let e=t[Le];if(e===void 0||e==="")return;if(!ci(e))throw De(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=di(e)}catch(o){throw De(e,"it cannot be read",o)}if(!n.isFile())throw De(e,"it is not a file");let r;try{r=li(e,"utf8")}catch(o){throw De(e,"its contents could not be read",o)}return{variable:Le,path:e,pem:r}}i(Rn,"resolveExtraCaTrust");function Tn(t){let e=Rn(t);if(e!==void 0)return ui.info("Trusting an extra certificate authority for the agent's own connections",{variable:e.variable,path:e.path,publicRootCount:kn.length}),[...kn,e.pem]}i(Tn,"readTrustedCaBundle");function An(t){Rn(t)}i(An,"validateExtraCaTrustEnv");var mi=new Set(["localhost","127.0.0.1","::1","[::1]"]);function It(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:"&&mi.has(e.hostname)))throw new Error(`[config] PROGON_SERVER_URL must use the https:// scheme (encrypted HTTP). http:// is only allowed for loopback hosts (localhost, 127.0.0.1, [::1]). Got scheme: ${JSON.stringify(e.protocol)} with host: ${JSON.stringify(e.hostname)}. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`);if(e.host==="")throw new Error(`[config] PROGON_SERVER_URL must include a non-empty host. Got: ${JSON.stringify(t)}. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`);if(e.username!==""||e.password!=="")throw new Error("[config] PROGON_SERVER_URL must not contain embedded credentials (userinfo). Use the PROGON_AGENT_TOKEN env var for authentication instead. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.");if(e.search!==""||e.hash!=="")throw new Error(`[config] PROGON_SERVER_URL must be a base URL with no query string and no fragment \u2014 the agent-gateway routes are appended to it, and a query or a fragment would swallow them instead of preceding them. Got query ${JSON.stringify(e.search)} and fragment ${JSON.stringify(e.hash)}. Use scheme + host + optional path prefix only (https://host, https://host/prefix). See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`)}i(It,"validateServerUrl");function xt(t){if(!Q.test(t))throw new Error("[config] Agent token must match the pgat_ wire format (CONTRACT-la \xA75.1). Got a token that does not match this format. Ensure PROGON_AGENT_TOKEN was copied from the server correctly.")}i(xt,"validateRunnerToken");function On(t){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t))throw new Error(`[config] agentId must be a valid UUID (issued by the server at enroll). Got: ${JSON.stringify(t)}. The state file may be corrupted \u2014 remove it and re-enroll.`)}i(On,"validateRunnerMachineId");function Pn(t){if(t!==1)throw new Error(`[config] Protocol version mismatch: state file records version ${t} but this daemon requires version ${1}. Remove the state file and re-enroll with the correct daemon version.`)}i(Pn,"validateProtocolVersion");function hi(t){let e=process.env[t];if(e===void 0||e==="")throw new Error(`[config] Required environment variable ${t} is not set. See docs/working/local-agent-v1/CONTRACT-la.md \xA78 for the full env key list.`);return e}i(hi,"getRequired");function Me(t){let e=process.env[t];return e!==void 0&&e!==""?e:void 0}i(Me,"getOptional");function In(t,e){let n=process.env[t];if(n===void 0||n==="")return e;let r=n.trim().toLowerCase();if(r==="true"||r==="1")return!0;if(r==="false"||r==="0")return!1;throw new Error(`[config] Environment variable ${t} must be one of true/false/1/0, got: ${JSON.stringify(n)}. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`)}i(In,"getOptionalBool");var $e="progon-agent";function gi(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 Ge(n,"Library","Application Support",$e);case"linux":{let r=e.XDG_STATE_HOME;if(r===void 0||r==="")return Ge(n,".local","state",$e);if(!xn(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 Ge(r,$e)}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 Ge(r,$e)}default:throw new Error(`[config] No default state directory is defined for platform ${JSON.stringify(t)} (supported: darwin, linux, win32 \u2014 CONTRACT-la \xA75.1, \xA710.3). Set PROGON_RUNNER_STATE_DIR explicitly.`)}}i(gi,"resolveDefaultStateDir");function ne(){let t=hi("PROGON_SERVER_URL");It(t),Sn(process.env),An(process.env);let e=process.env.PROGON_AGENT_TOKEN;if(e==="")throw new Error("[config] PROGON_AGENT_TOKEN is set but empty. To use the persisted state-file token, unset this variable entirely. To rotate the token, set it to the new pgat_ token. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.");let n=e;n!==void 0&&xt(n);let r=Me("PROGON_AGENT_EXTENSION_DIST");if(r!==void 0&&!xn(r))throw new Error(`[config] PROGON_AGENT_EXTENSION_DIST must be an absolute path, got: ${JSON.stringify(r)}. See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`);let o=Me("PROGON_AGENT_ENROLL_CODE");if(o!==void 0&&o.length<32)throw new Error(`[config] PROGON_AGENT_ENROLL_CODE is shorter than the ${32} characters an enrollment code has (got ${o.length}). Copy the whole code from the agent's enrollment dialog. See docs/working/local-agent-v1/CONTRACT-la.md \xA75.1.`);return{serverUrl:t,initialToken:n,stateDir:Me("PROGON_RUNNER_STATE_DIR")??gi(process.platform,process.env,pi()),extensionDistOverride:r,headfulOverride:In("PROGON_AGENT_HEADFUL",!1),allowInsecureHttps:In("PROGON_AGENT_ALLOW_INSECURE_HTTPS",!1),enrollmentCode:o,nodeEnv:Me("NODE_ENV")??"production"}}i(ne,"loadConfig");function Se(t,e,n){process.stderr.write(JSON.stringify({level:t,module:"process-guards",msg:e,...n})+`
|
|
9
|
-
|
|
2
|
+
var _o=Object.defineProperty;var o=(t,e)=>_o(t,"name",{value:e,configurable:!0});import{realpathSync as Ca}from"node:fs";import{pathToFileURL as Da}from"node:url";import{z as zt}from"zod";var So=/^[a-z_]{1,32}@\d{1,3}$/,Zt=zt.array(zt.string().regex(So)).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 bo=w.object({scenarioId:w.uuid(),scenarioName:w.string().min(1)}).strict(),nn=8192,ko=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(bo).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:ko.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 To=["queued","launching","in_progress","completed","failed","cancelled"],za=Re.enum(To);var Ao=["queued","launching","in_progress"],sn=Re.enum(Ao);var an=["claim_timeout","launch_timeout","launch_error","browser_gone","agent_lost","max_duration","killed"],Za=Re.enum(an),Io=["launch_error","browser_gone","max_duration"],ln=Re.enum(Io);var xo=[...an,"stalled","capability_mismatch","subject_rejected"],Qa=Re.enum(xo);var Oo=c.enum(["darwin","linux","win32"]),Po=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:Oo,arch:Po,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(),al=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:sn}).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(),ll=c.discriminatedUnion("kind",[kt,Tt,At]),No={playback:!0,make_auto:!0,atlas_crawl:!0},dl=Object.keys(No),cl=c.object({agentJobId:c.uuid(),updatedAt:c.iso.datetime()}).strict(),Co=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:Co}).strict()]),mn=c.object({cancelRequested:c.boolean(),killRequested:c.boolean()}).strict(),Do=2147483646,Lo=c.object({stepId:c.uuid(),stepIndex:c.number().int().min(0).max(Do),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(),ul=c.object({events:c.array(Lo).min(1).max(50)}).strict(),ml=c.object({updated:c.number().int().min(0),control:mn}).strict(),pl=c.object({phase:c.enum(["running","paused"])}).strict(),hl=c.object({control:mn}).strict(),gl=c.object({reason:ln,message:c.string().max(500).optional()}).strict(),pn=c.object({status:c.enum(["failed","already_terminal"])}).strict();var _l=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 Go(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(Go,"checkPlaybackClaimProjectAgreement");var Mo=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(Go),gn=g.object({accessToken:g.string().min(1),refreshToken:g.string().min(1)}).strict(),Uo=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),$o=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([Mo,Uo,$o]);import{spawn as Wo}from"node:child_process";import{existsSync as Yo}from"node:fs";import{createRequire as Xo}from"node:module";import{dirname as En,join as zo}from"node:path";import Vo from"pino";var Fo=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,qo=/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,Bo=["token","secret","password","authorization","api_key","api-key","apikey"],Ho=new RegExp(`([?&](?:${Bo.join("|")})=)([^&\\s]+)`,"gi"),Le="[REDACTED]";function yn(t){let e=t.replace(qo,Le);return e=e.replace(jo,Le),e=e.replace(Ho,`$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))Fo.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 Jo(){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(Jo,"resolveLogLevel");function Ko(){if(process.env.NODE_ENV!=="production")return{target:"pino-pretty",options:{translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname"}}}o(Ko,"buildTransport");var wn=Vo({name:"qa-runner",level:Jo(),transport:Ko(),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 Ll=xt(wn);var Ot=u("browser-provision"),Zo=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 Qo(){let t=Xo(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(!Yo(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(Qo,"resolveInstallCommand");async function Ge(t){let e=t.commandOverride===void 0?Qo():t.commandOverride,n=t.deadlineMs===void 0?Zo:t.deadlineMs,r=t.stdio==="pipe"?[...e.args,"--no-progress"]:[...e.args],i=`${e.execPath} ${e.cliPath} ${r.join(" ")}`,s=Date.now();Ot.info("Provisioning Chromium",{cliPath:e.cliPath,args:r,deadlineMs:n});let a=Wo(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}=a;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,a.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(()=>{a.kill("SIGKILL"),f(),process.stderr.write(JSON.stringify({level:"warn",module:"browser-provision",msg:"Chromium provisioning aborted by signal: the installer was killed, and the next start downloads again",signal:h,installerPid:a.pid})+`
|
|
4
|
+
`),process.kill(process.pid,h)},"handler");m.set(h,p),process.on(h,p)}try{await new Promise((h,p)=>{a.once("error",b=>{p(new j(`[browser-provision] Could not start the Playwright installer (${i}): ${b.message}`,{cause:b}))}),a.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()-s})}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 s=n.slice(0,i);n=n.slice(i+1);for(let a of s.split(`
|
|
8
|
+
`))Sn(a,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 Oi}from"node:os";import{isAbsolute as Bn,join as qe}from"node:path";var ei=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:"&&ei.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 ti,EnvHttpProxyAgent as ni}from"undici";var Rn=u("gateway-proxy"),ri=["http_proxy","HTTP_PROXY"],oi=["https_proxy","HTTPS_PROXY"],ii=["no_proxy","NO_PROXY"];function si(t){return t.http!==void 0||t.https!==void 0}o(si,"gatewayIsProxied");var ai=/^[A-Za-z][A-Za-z0-9+.-]*:\/\//,li=/:\d+$/,di=/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)?[^/?#]*@/;function ci(t){let e=di.exec(t);if(e===null)return t;let n=e[1];return`${n===void 0?"":n}***@${t.slice(e[0].length)}`}o(ci,"withoutProxyCredentials");function te(t,e,n){return new Error(`[config] ${t} does not name a proxy this agent can use: ${n}. Got: ${JSON.stringify(ci(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 ui(t){for(let e of ii){let n=t[e];if(n!==void 0)return n}}o(ui,"readNoProxy");function kn(t,e){if(ai.test(e)){let a;try{a=new URL(e)}catch{throw te(t,e,"it carries a scheme but is not a URL that parses")}if(a.protocol!=="http:"&&a.protocol!=="https:")throw te(t,e,`its scheme is ${JSON.stringify(a.protocol)}, not http: or https:`);if(a.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(!li.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}`,s;try{s=new URL(i)}catch{throw te(t,e,'it is neither a URL nor a "host:port" pair')}if(s.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,ri),n=bn(t,oi);return{http:e===void 0?void 0:kn(e.variable,e.raw),https:n===void 0?void 0:kn(n.variable,n.raw),noProxy:ui(t)}}o(Ct,"resolveGatewayProxyConfig");function Tn(t,e,n){if(!si(t))return new ti(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 s of[t.http,t.https])s!==void 0&&s.schemeCompleted&&r.push(s.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 ni(i)}o(Tn,"createProxyAwareDispatcher");function An(t){Ct(t)}o(An,"validateGatewayProxyEnv");import{readFileSync as mi,statSync as pi}from"node:fs";import{isAbsolute as hi}from"node:path";import{rootCertificates as In}from"node:tls";var gi=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(!hi(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=pi(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=mi(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 gi.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 Ii}from"node:fs";import{readFileSync as fi,writeFileSync as yi,renameSync as wi,mkdirSync as Ei,existsSync as vi,chmodSync as _i,fchmodSync as Si,openSync as Nn,fsyncSync as Cn,closeSync as Dn,unlinkSync as Ri}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(!vi(e))return $e.debug("No state file found \u2014 first start",{filePath:e}),null;let n;try{n=fi(e,"utf-8")}catch(s){throw new Error(`[state-file] Failed to read state file at ${e}: ${String(s)}. If the file is corrupted, remove it and re-register with PROGON_RUNNER_TOKEN set.`)}let r;try{r=JSON.parse(n)}catch(s){throw new Error(`[state-file] State file at ${e} contains invalid JSON: ${String(s)}. Remove the file and re-register with PROGON_RUNNER_TOKEN set.`)}let i=Ti(r,e);return $e.info("State file loaded",{agentId:i.agentId,protocolVersion:i.protocolVersion}),i}o(Gn,"readState");function Mn(t,e){Ei(t,{recursive:!0,mode:448}),_i(t,448);let n=Fe(t),r=Dt(t),i=JSON.stringify(e,null,2);try{let s=Nn(r,"w",384);try{Si(s,384),yi(s,i,{encoding:"utf-8"}),Cn(s)}finally{Dn(s)}wi(r,n),ki(t)}catch(s){throw bi(r),new Error(`[state-file] Failed to write state file at ${n}: ${String(s)}. Check permissions on stateDir ${t}.`)}$e.info("State file written",{agentId:e.agentId,filePath:n})}o(Mn,"writeState");function bi(t){try{Ri(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(bi,"removeStateTmp");function ki(t){let e=Nn(t,"r");try{Cn(e)}finally{Dn(e)}}o(ki,"fsyncDirectory");function Ti(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 s=n.protocolVersion;if(typeof s!="number"||!Number.isInteger(s))throw new Error(`[state-file] State file ${e} is missing or has invalid 'protocolVersion' (expected integer).`);Nt(s);let a=n.serverUrl;if(typeof a!="string"||a==="")throw new Error(`[state-file] State file ${e} is missing or has invalid 'serverUrl' (expected non-empty string).`);try{be(a)}catch(l){throw new Error(`[state-file] State file ${e} has an invalid 'serverUrl': ${String(l)}`)}return{agentId:r,agentToken:i,protocolVersion:s,serverUrl:a,tokenRotatedAt:Ai(n,e)}}o(Ti,"validateState");function Ai(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(Ai,"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 Ii(t),!0}catch(n){if(xi(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 xi(t){return t.code==="ENOENT"}o(xi,"isFileNotFound");function je(t,e){return new URL(t).href===new URL(e).href}o(je,"isSameDeployment");function jn(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.
|
|
9
|
+
The enrolled server in ${r} is deliberately NOT read on this path: PROGON_AGENT_TOKEN is the rotation and recovery mechanism, and it must not start depending on the very state file an operator sets it to recover from.
|
|
10
|
+
Set PROGON_SERVER_URL to the deployment this token belongs to, or unset PROGON_AGENT_TOKEN to run on the credential this machine enrolled with.
|
|
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
|
+
Enroll this machine \u2014 'progon-agent enroll --server <url>', 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 without any environment at all.
|
|
13
|
+
Or, to point an already-credentialled process at a deployment, set PROGON_SERVER_URL.
|
|
14
|
+
See docs/working/local-agent-v1/CONTRACT-la.md \xA78.`);return{url:i.serverUrl,source:"state_file"}}o(jn,"resolveServerUrl");function Te(t){let e=process.env[t];return e!==void 0&&e!==""?e:void 0}o(Te,"getOptional");function qn(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(qn,"getOptionalBool");var Be="progon-agent";function Pi(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(!Bn(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(Pi,"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")??Pi(process.platform,process.env,Oi()),r=jn({envUrl:Te("PROGON_SERVER_URL"),envTokenPresent:e!==void 0,stateDir:n}),i=Te("PROGON_AGENT_EXTENSION_DIST");if(i!==void 0&&!Bn(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 s=Te("PROGON_AGENT_ENROLL_CODE");if(s!==void 0&&s.length<32)throw new Error(`[config] PROGON_AGENT_ENROLL_CODE is shorter than the ${32} characters an enrollment code has (got ${s.length}). Copy the whole code from the agent's enrollment dialog. See docs/working/local-agent-v1/CONTRACT-la.md \xA75.1.`);return{serverUrl:r.url,serverUrlSource:r.source,initialToken:e,stateDir:n,extensionDistOverride:i,headfulOverride:qn("PROGON_AGENT_HEADFUL",!1),allowInsecureHttps:qn("PROGON_AGENT_ALLOW_INSECURE_HTTPS",!1),enrollmentCode:s,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})+`
|
|
15
|
+
`)}o(Ae,"writeLine");function Vn(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(Vn,"describeError");function Hn(t,e,n){Ae("fatal",`Unhandled ${t} \u2014 terminating the daemon`,{event:t,...Vn(e),...n})}o(Hn,"writeFatalLine");function Jn(){process.on("uncaughtException",(t,e)=>{Hn("uncaughtException",t,{origin:e}),process.exit(1)}),process.on("unhandledRejection",t=>{Hn("unhandledRejection",t,{}),process.exit(1)})}o(Jn,"installProcessGuards");function Kn(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,...Vn(i)}),process.exit(1)}Ae("info","Shutdown complete",{signal:r}),process.exit(0)})()},"handle");process.on("SIGTERM",n),process.on("SIGINT",n)}o(Kn,"installShutdownHandlers");import{chmodSync as Gi,cpSync as Mi,mkdirSync as Ui,readdirSync as $i,renameSync as Fi,rmSync as Gt,statSync as Xn,writeFileSync as ji}from"node:fs";import{dirname as qi,join as oe}from"node:path";import{fileURLToPath as Bi}from"node:url";import{statSync as Ni}from"node:fs";import{dirname as Ci,join as Di}from"node:path";var Wn="package.json";function Yn(t){let e=t;for(;;){if(Li(e))return e;let n=Ci(e);if(n===e)throw new Error(`[package-root] No ${Wn} 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(Yn,"findPackageRoot");function Li(t){try{return Ni(Di(t,Wn)),!0}catch(e){if(typeof e=="object"&&e!==null){let n=e.code;if(n==="ENOENT"||n==="ENOTDIR")return!1}throw e}}o(Li,"holdsPackageManifest");var He=u("extension-dist"),Hi="extension-dist",Qn="extension-dist",er=`${Qn}.tmp-`,Mt="agent-manifest.json",zn="manifest.json";function Vi(){return Yn(qi(Bi(import.meta.url)))}o(Vi,"packageRoot");function Ji(){return Ki(oe(Vi(),Hi))}o(Ji,"resolveBundledExtensionSource");function Ki(t){let e;try{e=Xn(t)}catch(r){throw Zn(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{Xn(n)}catch(r){throw Zn(r)?new Error(Lt(t,`it holds no ${zn}`),{cause:r}):r}return t}o(Ki,"assertBundledExtensionSource");function Zn(t){if(typeof t!="object"||t===null)return!1;let e=t.code;return e==="ENOENT"||e==="ENOTDIR"}o(Zn,"isAbsentPathError");function Lt(t,e){return`[extension-dist] No extension dist is bundled in this package (${t}): ${e}.
|
|
10
16
|
This package was built WITHOUT the bundling step. Run 'npm run bundle:extension' in the agent package (it copies a built qa-extension dist in; set PROGON_EXTENSION_DIST_SRC to point at that dist if it is not the sibling checkout), then reinstall or restart the daemon.
|
|
11
|
-
For a dev or E2E stand you can instead set PROGON_AGENT_EXTENSION_DIST to an already agent-mode dist, which bypasses the bundled copy entirely (CONTRACT-la \xA78).`}
|
|
12
|
-
`,"utf8")}
|
|
13
|
-
Either enroll the agent ('progon-agent enroll <code>'), which persists the identity the server issued, or set PROGON_AGENT_EXTENSION_DIST to a dist that is already in agent mode (dev/E2E path, \xA78).`);return Ni({stateDir:t.stateDir,agentId:t.agentId})}i(Bn,"resolveExtensionDist");import{fetch as Mi}from"undici";var v=class extends Error{static{i(this,"GatewayError")}operation;constructor(e,n,r){super(n,{cause:r}),this.name=new.target.name,this.operation=e}},G=class extends v{static{i(this,"GatewayTransportError")}constructor(e,n,r){super(e,`[gateway] ${e} failed before a response was received: ${n}`,r)}},_=class extends v{static{i(this,"GatewayHttpError")}status;errorCode;params;constructor(e,n,r,o,a){super(e,`[gateway] ${e} refused with HTTP ${n}: ${a}`),this.status=n,this.errorCode=r,this.params=o}},oe=class extends _{static{i(this,"GatewayUnauthorizedError")}},b=class extends _{static{i(this,"TokenSupersededError")}},y=class extends v{static{i(this,"TerminalSignalError")}signal;constructor(e,n,r){super(e,`[gateway] agent revoked (${n}) during ${e}: ${r}`),this.signal=n}},Fe=class extends _{static{i(this,"EnrollmentCodeRejectedError")}},ke=class extends _{static{i(this,"ProtocolVersionMismatchError")}},ie=class extends _{static{i(this,"RunNotClaimableError")}},W=class extends _{static{i(this,"RunNotFoundError")}},M=class extends v{static{i(this,"GatewayResponseSchemaError")}constructor(e,n,r){super(e,`[gateway] ${e} returned a body that violates the contract: ${n}`,r)}};var Hn=u("gateway-http");async function Y(t){let e={accept:"application/json"};t.agentToken!==null&&(e.authorization=`Bearer ${t.agentToken}`),t.body!==null&&(e["content-type"]="application/json"),Hn.debug("Gateway request",{operation:t.operation,method:t.method,url:t.url.toString()});let n;try{n=await t.fetchImpl(t.url,{method:t.method,headers:e,body:t.body===null?void 0:JSON.stringify(t.body),signal:t.signal})}catch(o){throw new G(t.operation,Jn(o),o)}let r;try{r=await n.text()}catch(o){throw new G(t.operation,Jn(o),o)}if(!n.ok){let o=Li(n.status,r);throw Hn.debug("Gateway request refused",{operation:t.operation,status:o.status,errorCode:o.errorCode}),t.mapHttpError(o)}try{return JSON.parse(r)}catch(o){throw new M(t.operation,`the ${n.status} response body is not valid JSON`,o)}}i(Y,"executeGatewayRequest");function P(t,e){if(e.success)return e.data;throw new M(t,Gi(e.error),e.error)}i(P,"parseGatewayBody");function Li(t,e){let n;try{n=JSON.parse(e)}catch{return{status:t,errorCode:null,params:null,message:Ct}}if(typeof n!="object"||n===null||Array.isArray(n))return{status:t,errorCode:null,params:null,message:Ct};let r=n,o=r.error_code,a=r.params,s=r.message;return{status:t,errorCode:typeof o=="string"?o:null,params:typeof a=="object"&&a!==null&&!Array.isArray(a)?a:null,message:typeof s=="string"?L(s):Ct}}i(Li,"readErrorEnvelope");var Ct="the response body carried no Progon error envelope";function Jn(t){return L(t instanceof Error?t.message:String(t))}i(Jn,"describeCause");function Gi(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(Gi,"summarizeSchemaViolation");var ae=class extends _{static{i(this,"EnrollmentSlowDownError")}retryAfterSec;constructor(e,n,r,o,a,s){super(e,n,r,o,a),this.retryAfterSec=s}},se=class extends _{static{i(this,"EnrollmentAccessDeniedError")}},le=class extends _{static{i(this,"EnrollmentRequestExpiredError")}},de=class extends _{static{i(this,"EnrollmentAlreadyCompletedError")}},ce=class extends _{static{i(this,"EnrollmentRequestInvalidError")}};function Vn(t){return t.status===401&&t.errorCode==="agent_enroll.invalid_code"?x(Fe,"enroll",t):t.status===409&&t.errorCode==="agent_enroll.protocol_version"?x(ke,"enroll",t):C("enroll",t)}i(Vn,"mapEnrollError");function Kn(t){return t.status===409&&t.errorCode==="agent_enroll.protocol_version"?x(ke,"enrollment_request_create",t):C("enrollment_request_create",t)}i(Kn,"mapEnrollmentRequestCreateError");function Wn(t){if(t.status===429&&t.errorCode==="agent_enroll.slow_down"){let e=t.params===null?void 0:t.params.retryAfterSeconds,n=typeof e=="number"&&Number.isFinite(e)&&e>0?e:null;return new ae("enrollment_request_poll",t.status,t.errorCode,t.params,t.message,n)}return t.status===403&&t.errorCode==="agent_enroll.access_denied"?x(se,"enrollment_request_poll",t):t.status===410&&t.errorCode==="agent_enroll.expired"?x(le,"enrollment_request_poll",t):t.status===410&&t.errorCode==="agent_enroll.already_completed"?x(de,"enrollment_request_poll",t):t.status===401&&t.errorCode==="agent_enroll.invalid_request"?x(ce,"enrollment_request_poll",t):C("enrollment_request_poll",t)}i(Wn,"mapEnrollmentRequestPollError");function Yn(t){return C("enrollment_request_cancel",t)}i(Yn,"mapEnrollmentRequestCancelError");function Xn(t){return ue("poll_desired_state",t,()=>C("poll_desired_state",t))}i(Xn,"mapPollDesiredStateError");function zn(t){return ue("claim",t,()=>t.status===409&&t.errorCode==="run.not_claimable"?x(ie,"claim",t):t.status===404?x(W,"claim",t):C("claim",t))}i(zn,"mapClaimError");function Zn(t){return ue("fail",t,()=>t.status===404?x(W,"fail",t):C("fail",t))}i(Zn,"mapFailError");function Qn(t){return ue("token_status",t,()=>C("token_status",t))}i(Qn,"mapTokenStatusError");function er(t){return ue("token_rotate",t,()=>C("token_rotate",t))}i(er,"mapTokenRotateError");function tr(t){return ue("declare_capabilities",t,()=>C("declare_capabilities",t))}i(tr,"mapDeclareCapabilitiesError");function ue(t,e,n){return e.status===403&&e.errorCode==="agents.revoked"?new y(t,"http_403_agents_revoked",e.message):e.status===401&&e.errorCode==="agents.token_superseded"?x(b,t,e):e.status===401?x(oe,t,e):n()}i(ue,"bearerRoute");function x(t,e,n){return new t(e,n.status,n.errorCode,n.params,n.message)}i(x,"named");function C(t,e){return x(_,t,e)}i(C,"generic");var je=[...Yt,Xt,zt];import{z as X}from"zod";var nr=X.object({rotationDue:X.boolean(),tokenRotatedAt:X.string().nullable(),anchorAt:X.string(),intervalDays:X.number().int()}),rr=X.object({agentToken:X.string().regex(Q)});var qe=u("gateway-client"),$i="/api/agent-gateway";function N(t,e){return new URL(`${t.replace(/\/+$/,"")}${$i}${e}`)}i(N,"buildGatewayUrl");var or=3e5,ar=1e4,ir={headersTimeout:or,bodyTimeout:or,connect:{timeout:ar}};function Ui(){let t=Tn(process.env);return vn(At(process.env),t===void 0?ir:{...ir,connect:{timeout:ar,ca:t}},t)}i(Ui,"buildGatewayDispatcher");var Dt,Je=i((t,e)=>{if(Dt===void 0){let n=Ui();Dt=i((r,o)=>Mi(r,{...o,dispatcher:n}),"defaultGatewayFetch")}return Dt(t,e)},"pinnedGatewayFetch"),Be=class{static{i(this,"GatewayEnrollmentClient")}serverUrl;machine;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.machine=e.machine,this.fetchImpl=e.fetchImpl??Je}async enroll(e){let n={...this.machine,enrollmentCode:e,protocolVersion:1},r=await Y({operation:"enroll",method:"POST",url:N(this.serverUrl,"/enroll"),agentToken:null,body:n,signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:Vn}),o=P("enroll",Pe.safeParse(r));return qe.info("Agent enrolled",{agentId:o.agentId,pollWaitSec:o.pollWaitSec,protocolVersion:o.protocolVersion}),o}},He=class{static{i(this,"GatewayClient")}serverUrl;agentToken;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.agentToken=e.agentToken,this.fetchImpl=e.fetchImpl??Je}async authenticatedRequest(e){return Y({operation:e.operation,method:e.method,url:e.url,agentToken:this.agentToken,body:e.body,signal:e.signal,fetchImpl:this.fetchImpl,mapHttpError:e.mapHttpError})}async pollDesiredState(e){let n=N(this.serverUrl,"/state");e?.waitSec!==void 0&&n.searchParams.set("waitSec",String(e.waitSec));let r=await this.authenticatedRequest({operation:"poll_desired_state",method:"GET",url:n,body:null,signal:e?.signal,mapHttpError:Xn}),o=P("poll_desired_state",an.safeParse(r));if(o.agent.revoked)throw new y("poll_desired_state","desired_state_snapshot","the desired-state snapshot reports this agent as revoked");return o}async claimRun(e){let n=await this.authenticatedRequest({operation:"claim",method:"POST",url:N(this.serverUrl,`/runs/${encodeURIComponent(e)}/claim`),body:{capabilities:je},signal:void 0,mapHttpError:zn});return P("claim",pn.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:Zn}),o=P("fail",dn.safeParse(r));return qe.info("Reported run failure to the gateway",{runId:e,reason:n.reason,status:o.status}),o}async getTokenRotationStatus(e){let n=await this.authenticatedRequest({operation:"token_status",method:"GET",url:N(this.serverUrl,"/token"),body:null,signal:e?.signal,mapHttpError:Qn});return P("token_status",nr.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:er});return P("token_rotate",rr.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:tr}),qe.info("Capabilities declared",{capabilities:je})}useAgentToken(e){this.agentToken=e,qe.info("Adopted a rotated agent token for all subsequent gateway requests")}};var Fi=u("debug-env-guard"),ji=["pw:protocol","pw:api"];function qi(t){return t.replace(/[\\^$.|?+()[\]{}]/g,"\\$&")}i(qi,"escapeRegExp");function sr(t){if(t.startsWith("-"))return!1;let e=`^${t.split("*").map(qi).join(".*?")}$`,n=new RegExp(e);return ji.some(r=>n.test(r))}i(sr,"enablesPlaywright");function Bi(){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=>sr(o));if(n.length===0)return[];let r=e.filter(o=>!sr(o));return r.length===0?delete process.env.DEBUG:process.env.DEBUG=r.join(","),Fi.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(Bi,"sanitizePlaywrightDebugEnv");Bi();import{statSync as dr}from"node:fs";import{isAbsolute as Ji,join as Vi}from"node:path";import{createRequire as Hi}from"node:module";var $=Hi(import.meta.url)("playwright-core"),Ve=$.chromium,tc=$.firefox,nc=$.webkit,rc=$.selectors,oc=$.devices,ic=$.errors,ac=$.request,sc=$._electron,lc=$._android;var Ke="chromium";var lr="instances",We="instance.json";async function cr(t){return Ve.launchPersistentContext(t.userDataDir,{headless:!t.headful,channel:Ke,ignoreHTTPSErrors:t.allowInsecureHttps,args:[`--disable-extensions-except=${t.extensionDist}`,`--load-extension=${t.extensionDist}`,"--no-first-run","--no-default-browser-check"]})}i(cr,"launchExtensionContext");function Ki(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(Ki,"requireBrowser");function ur(t){return Ki(t).version()}i(ur,"readChromeVersion");async function pr(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(pr,"raceClose");function mr(t){if(!Ji(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=dr(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=Vi(t,"manifest.json");try{dr(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(mr,"assertUsableExtensionDist");var Wi=u("worker-evaluate"),Lt=class extends Error{static{i(this,"EvaluateDeadlineError")}operation;timeoutMs;constructor(e,n){super(`[runtime] ${e}: the extension service worker did not answer worker.evaluate within ${n}ms \u2014 the worker is wedged or gone`),this.name="EvaluateDeadlineError",this.operation=e,this.timeoutMs=n}};async function j(t){let e=t.evaluate(),n=!1;e.catch(a=>{n&&Wi.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 Lt(t.operation,t.timeoutMs))},t.timeoutMs)});try{return await Promise.race([e,o])}finally{r!==void 0&&clearTimeout(r)}}i(j,"evaluateWithDeadline");var hr="accessToken",gr="refreshToken";async function yr(t,e){await j({operation:"write the run session into chrome.storage.local",timeoutMs:1e4,evaluate:i(()=>t.evaluate(([r,o,a,s])=>new Promise(l=>chrome.storage.local.set({[r]:a,[o]:s},()=>l())),[hr,gr,e.accessToken,e.refreshToken]),"evaluate")});let n=await j({operation:"read the run session back out of chrome.storage.local",timeoutMs:1e4,evaluate:i(()=>t.evaluate(([r,o])=>new Promise(a=>chrome.storage.local.get([r,o],s=>{let l=s[r],c=s[o];a({accessTokenLength:typeof l=="string"?l.length:null,refreshTokenLength:typeof c=="string"?c.length:null})})),[hr,gr]),"evaluate")});if(n.accessTokenLength!==e.accessToken.length||n.refreshTokenLength!==e.refreshToken.length)throw new Error(`run-session read-back mismatch: chrome.storage.local holds accessToken(len=${String(n.accessTokenLength)}), refreshToken(len=${String(n.refreshTokenLength)}) but ${e.accessToken.length}/${e.refreshToken.length} were written`);return n}i(yr,"seedRunSession");function fr(t){return JSON.stringify(Object.keys(t).sort().map(e=>[e,t[e]]))}i(fr,"canonicalise");async function wr(t,e){await j({operation:`write the command envelope to chrome.storage.local['${be}']`,timeoutMs:1e4,evaluate:i(()=>t.evaluate(([a,s])=>new Promise(l=>chrome.storage.local.set({[a]:s},()=>l())),[be,e]),"evaluate")});let n=await j({operation:"read the command envelope back out of chrome.storage.local",timeoutMs:1e4,evaluate:i(()=>t.evaluate(a=>new Promise(s=>chrome.storage.local.get([a],l=>{let c=l[a];s(c===void 0?null:c)})),be),"evaluate")});if(typeof n!="object"||n===null)throw new Error(`command envelope read-back returned ${JSON.stringify(n)} \u2014 chrome.storage.local['${be}'] does not hold the envelope`);let r=fr({...e}),o=fr(n);if(r!==o)throw new Error(`command envelope read-back mismatch: wrote ${r}, read ${o}`)}i(wr,"seedCommandEnvelope");async function Xi(t,e,n){let r=await j({operation:`read chrome.storage.local['${Oe}']`,timeoutMs:n,evaluate:i(()=>t.evaluate(a=>new Promise(s=>chrome.storage.local.get([a],l=>{let c=l[a];s(c===void 0?null:c)})),Oe),"evaluate")});if(r===null)return{kind:"absent"};let o=sn.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(Xi,"pollCommandAck");async function Er(t,e,n){let r=Date.now()+n,o="no ack was written";for(;;){let a=r-Date.now();if(a<=0)throw new Error(`no command ack for run ${e} within ${n}ms \u2014 ${o}. chrome.storage.local['${Oe}'] is the only success signal (CONTRACT-la \xA75.4).`);let s=t.serviceWorkers()[0];if(s===void 0)o="the context exposed no service worker while polling (evicted, restarting)";else{let l;try{l=await Xi(s,e,a)}catch(c){o=`the last poll failed: ${c instanceof Error?c.message:String(c)}`,l={kind:"invalid",detail:o}}if(l.kind==="ack")return l.ack;l.kind!=="absent"&&(o=l.detail)}await new Promise(l=>setTimeout(l,250))}}i(Er,"waitForCommandAck");import Xe from"node:os";import{createRequire as zi}from"node:module";var _r=zi(import.meta.url);function Zi(){let t=_r.resolve("playwright-core/package.json"),e=_r(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(Zi,"readPlaywrightCoreVersion");function br(t){return{node:process.version,platform:`${Xe.platform()} ${Xe.release()} ${Xe.arch()}`,cpus:Xe.cpus().length,playwrightCore:Zi(),chromiumExecutable:Ve.executablePath(),channel:Ke,extensionDist:t}}i(br,"buildEnvFingerprint");import{mkdirSync as Ir,readdirSync as ma,readFileSync as ha,renameSync as ga,rmSync as Mt,writeFileSync as fa}from"node:fs";import{join as Re}from"node:path";var q=class extends Error{static{i(this,"RuntimeLaunchError")}runId;stage;failReason="launch_error";constructor(e,n,r,o){super(`[runtime] launch failed at stage ${n} for run ${e}: ${r}`,{cause:o}),this.name="RuntimeLaunchError",this.runId=e,this.stage=n}};function vr(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(vr,"deepestCauseMessage");var B=class extends Error{static{i(this,"InstanceAlreadyRegisteredError")}runId;userDataDir;constructor(e,n,r){super(`[runtime] refusing to launch run ${e}: instance directory already exists at ${n}. Either this run is already live, or a previous daemon left it behind (the startup sweep clears leftovers \u2014 CONTRACT-la \xA715 A3, gate G-3).`,{cause:r}),this.name="InstanceAlreadyRegisteredError",this.runId=e,this.userDataDir=n}},ze=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 ea}from"node:child_process";import{promisify as ta}from"node:util";import{setTimeout as Tr}from"node:timers/promises";var Ze=ta(ea),Qe={timeout:5e3};function Ar(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(Ar,"asExecFailure");function na(t){let e=[];for(let n of t.split(`
|
|
14
|
-
`)){let r=n.trim();if(r==="")continue;let
|
|
15
|
-
`)){let s
|
|
16
|
-
`)){let r=n.trim().split(/\s+/);if(r.length<3)continue;let[o,a,s]=r,l=Number(o),c=Number(a),p=Number(s);!Number.isInteger(l)||!Number.isInteger(c)||!Number.isInteger(p)||e.push({pid:l,ppid:c,pgid:p})}return e}i(kr,"readProcessTable");function da(t,e){let n=new Map;for(let c of t){let p=n.get(c.ppid);p===void 0?n.set(c.ppid,[c.pid]):p.push(c.pid)}let r=new Set(e),o=[...e];for(let c=o.pop();c!==void 0;c=o.pop()){let p=n.get(c);if(p!==void 0)for(let f of p)r.has(f)||(r.add(f),o.push(f))}let a=t.find(c=>c.pid===process.pid),s=a===void 0?null:a.pgid,l=new Set;for(let c of t)r.has(c.pid)&&(c.pgid<=0||s!==null&&c.pgid===s||l.add(c.pgid));return r.delete(process.pid),{members:[...r],groups:[...l]}}i(da,"expandTree");function ca(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(ca,"sigkill");async function et(t){return process.platform==="win32"?pa(t):ua(t)}i(et,"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 kr(),{members:r,groups:o}=da(n,e),a=[];for(let c of r)ca(c)==="signalled"&&a.push(c);for(let c of o)try{process.kill(-c,"SIGKILL")}catch(p){if(typeof p!="object"||p===null||p.code!=="ESRCH")throw p}await Tr(500);let s=await kr(),l=new Set(s.map(c=>c.pid));return{platform:process.platform,userDataDir:t,discoveredPids:e,signalledPids:a,survivorPids:r.filter(c=>l.has(c))}}i(ua,"killProcessTreePosix");async function pa(t){let e=await Sr(t),n=[];for(let o of e)try{await Ze("taskkill.exe",["/T","/F","/PID",String(o)],Qe),n.push(o)}catch(a){let s=Ar(a);if(s===null||s.code!==128)throw a}await Tr(500);let r=await Sr(t);return{platform:"win32",userDataDir:t,discoveredPids:e,signalledPids:n,survivorPids:r}}i(pa,"killProcessTreeWin32");var z=u("instance-registry");function tt(t){return typeof t=="string"&&t!==""}i(tt,"isNonEmptyString");function ya(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(!tt(n.runId))throw new Error(`[instance-registry] ${e} has a missing or empty runId.`);if(!tt(n.userDataDir))throw new Error(`[instance-registry] ${e} has a missing or empty userDataDir.`);if(!tt(n.startedAt)||!tt(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(ya,"parseInstanceRecord");function wa(t,e){let n=`${t}.tmp`;fa(n,JSON.stringify(e,null,2),{encoding:"utf8",mode:384}),ga(n,t)}i(wa,"writeMarkerAtomically");var nt=class{static{i(this,"InstanceRegistry")}#e;constructor(e){this.#e=Re(e,lr)}get instancesRoot(){return this.#e}userDataDirFor(e){return Re(this.#e,e)}reserve(e,n){Ir(this.#e,{recursive:!0,mode:448});let r=this.userDataDirFor(e);try{Ir(r,{recursive:!1,mode:448})}catch(a){throw typeof a=="object"&&a!==null&&a.code==="EEXIST"?new B(e,r,a):a}let o=new Date().toISOString();try{wa(Re(r,We),{v:1,runId:e,agentPid:process.pid,userDataDir:r,startedAt:o,deadlineAt:n})}catch(a){try{Mt(r,{recursive:!0,force:!0})}catch(s){z.error("Failed to roll back the instance directory after a failed reservation",{runId:e,userDataDir:r,err:s instanceof Error?s.message:String(s)})}throw a}return z.info("Instance reserved",{runId:e,userDataDir:r,deadlineAt:n}),{runId:e,userDataDir:r,startedAt:o,deadlineAt:n}}read(e){return this.#n(Re(this.userDataDirFor(e),We))}release(e){let n=this.userDataDirFor(e);Mt(n,{recursive:!0,force:!0}),z.info("Instance released",{runId:e,userDataDir:n})}listRunIds(){let e;try{e=ma(this.#e,{withFileTypes:!0})}catch(n){if(typeof n=="object"&&n!==null&&n.code==="ENOENT")return[];throw n}return e.filter(n=>n.isDirectory()).map(n=>n.name)}async sweepOrphans(){let e=new Date().toISOString(),n=[];for(let r of this.listRunIds())n.push(await this.#t(r));return n.length>0?z.warn("Startup sweep found leftover browser instances",{instancesRoot:this.#e,count:n.length,outcomes:n}):z.info("Startup sweep found no leftover browser instances",{instancesRoot:this.#e}),{scannedAt:e,instancesRoot:this.#e,outcomes:n}}async#t(e){let n=this.userDataDirFor(e),r=Re(n,We),o=null,a;try{o=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 et(n);return z.warn("Leftover browser instance swept",{runId:e,userDataDir:n,marker:a,kill:s}),Mt(n,{recursive:!0,force:!0}),{runId:e,userDataDir:n,marker:a,record:o,kill:s,removed:!0}}#n(e){let n=ha(e,"utf8");return ya(JSON.parse(n),e)}};async function xr(t){let e=new Date().toISOString(),r=t.serviceWorkers()[0];if(r===void 0)return{ok:!1,observedAt:e,reason:"service_worker_absent",detail:"the browser context exposes no service worker \u2014 the extension is not running"};try{let o=await j({operation:`read chrome.storage.session['tabStates'] and ['${_t}']`,timeoutMs:1e4,evaluate:i(()=>r.evaluate(async a=>{let s=await new Promise(h=>chrome.storage.session.get(["tabStates",a],h)),l=s.tabStates,c=typeof l!="object"||l===null?[]:Object.entries(l).map(([h,m])=>{let k=typeof m=="object"&&m!==null?m.playback:null;if(typeof k!="object"||k===null)return{tabId:h,playback:null};let S=k;return{tabId:h,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}}}),p=s[a],f=typeof p!="object"||p===null?null:(()=>{let h=p;return{agentJobId:typeof h.agentJobId=="string"?h.agentJobId:null,updatedAt:typeof h.updatedAt=="string"?h.updatedAt:null}})();return{tabs:c,agentJob:f}},_t),"evaluate")});return{ok:!0,observedAt:e,tabs:o.tabs,agentJob:o.agentJob}}catch(o){return{ok:!1,observedAt:e,reason:"evaluate_failed",detail:o instanceof Error?o.message:String(o)}}}i(xr,"probePlaybackSession");async function Or(t,e){let r=t.serviceWorkers()[0];return r!==void 0?r:t.waitForEvent("serviceworker",{timeout:e})}i(Or,"waitForServiceWorker");async function Pr(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(Pr,"readRuntimeId");function rt(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(rt,"remainingBudgetMs");async function Cr(t){let e=Date.now(),n=e+45e3,r=n-5e3,o=await Or(t,Math.min(5e3,rt(r,"the service-worker target wait")));try{let a=await Pr(o,rt(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 Or(t,Math.min(5e3,rt(n,"the retry service-worker target wait"))),c=await Pr(l,rt(n,"the retry readiness evaluate"));return{worker:l,extensionId:c,serviceWorkerUrl:l.url(),attempts:2,readyAfterMs:Date.now()-e}}catch(l){let c=a instanceof Error?a.message:String(a),p=l instanceof Error?l.message:String(l);throw new Error(`extension readiness probe failed on both exp5 lanes. Direct attempt: ${c}. Page-open retry: ${p}.`,{cause:l})}finally{await s.close()}}}i(Cr,"probeExtensionReadiness");var E=u("playwright-execution-runtime"),Ft=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}},ot=class{static{i(this,"PlaywrightExecutionRuntime")}#e;#t;#n;#r;#a;#s;#o=null;#i=null;#u=!1;#l=null;#c=null;constructor(e){mr(e.extensionDist),this.#e=e.extensionDist,this.#t=e.headfulOverride,this.#n=e.allowInsecureHttps,this.#r=e.onInstanceLost,this.#a=new nt(e.stateDir),this.#s=br(e.extensionDist),E.info("Execution runtime constructed",{stateDir:e.stateDir,instancesRoot:this.#a.instancesRoot,headfulOverride:e.headfulOverride,allowInsecureHttps:e.allowInsecureHttps,envFingerprint:this.#s})}getActiveInstance(){let e=this.#o;return e===null?null:{runId:e.runId,userDataDir:e.userDataDir,headful:e.headful,extensionId:e.extensionId,chromeVersion:e.chromeVersion,startedAt:e.startedAt,deadlineAt:e.deadlineAt}}async sweepOrphanInstances(){return this.#a.sweepOrphans()}async probePlaybackSession(){let e=this.#o;return e===null?{ok:!1,observedAt:new Date().toISOString(),reason:"service_worker_absent",detail:"the runtime owns no browser instance"}:xr(e.context)}async startRun(e){let n=this.#o;if(n!==null)throw new ze(e.runId,n.runId);let r=Date.now(),o=new Date(r+e.maxRunDurationSec*1e3).toISOString(),a=await H(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);E.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 c=null;try{let p=await H(e.runId,"browser_launch",()=>cr({userDataDir:a.userDataDir,extensionDist:this.#e,headful:l,allowInsecureHttps:this.#n}));c=p,s.context=p,this.#p(s);let f=await H(e.runId,"browser_version",()=>ur(p)),h=await H(e.runId,"readiness_probe",()=>Cr(p));await this.#h(e,h.worker),await H(e.runId,"entry_navigation",()=>ba(p,e)),await this.#d(e,p);let m={runId:e.runId,context:c,userDataDir:a.userDataDir,headful:l,extensionId:h.extensionId,chromeVersion:f,startedAt:a.startedAt,deadlineAt:o};this.#p(s),this.#g(m),this.#o=m,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(p){throw this.#i===s&&(this.#i=null),await this.#f({runId:e.runId,context:c,userDataDir:a.userDataDir,timeoutMs:2e4,trigger:s.disposeRequested?"dispose_during_launch":"launch_failure"}),p}finally{this.#i===s&&(this.#i=null)}}async cancelRun(e){await this.disposeRun(e)}async disposeRun(e,n=2e4){let r=this.#l;if(r!==null&&r.runId===e)return E.info("Dispose requested for a lost instance \u2014 joining the teardown already running",{runId:e}),r.promise;let o=this.#i;if(o!==null&&o.runId===e)return o.disposeRequested=!0,E.warn("Dispose requested for a run that is still launching \u2014 aborting the launch",{runId:e,userDataDir:o.userDataDir,contextPresent:o.context!==null}),this.#f({runId:e,context:o.context,userDataDir:o.userDataDir,timeoutMs:n,trigger:"dispose_during_launch"});let a=this.#o;return a===null||a.runId!==e?this.#w(e):(this.#o=null,this.#f({runId:e,context:a.context,userDataDir:a.userDataDir,timeoutMs:n,trigger:"dispose"}))}#m(e){return e.headful||this.#t}async#h(e,n){let r=await H(e.runId,"token_seed",()=>yr(n,e.extensionSession));E.info("Run session seeded into the browser profile",{runId:e.runId,accessTokenLength:r.accessTokenLength,refreshTokenLength:r.refreshTokenLength}),await H(e.runId,"command_seed",()=>wr(n,e.command)),E.info("Command envelope seeded",{runId:e.runId,command:e.command})}async#d(e,n){let r=await H(e.runId,"command_ack",()=>Er(n,e.runId,15e3));if(r.outcome==="rejected")throw new q(e.runId,"command_ack",`the extension refused the command envelope: ${r.reason}`);E.info("Command envelope dispatched by the extension",{runId:e.runId})}#p(e){if(e.disposeRequested)throw new Ft(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=>{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:o};E.error("Browser instance disappeared without a dispose",{...s}),this.#r(s)},"report");e.context.on("close",()=>n("context_closed"));let r=e.context.browser();r!==null&&r.on("disconnected",()=>n("browser_disconnected"))}#w(e){let n=this.#c;if(n===null||n.runId!==e)return E.info("Dispose requested for a run this runtime does not own \u2014 no-op",{requestedRunId:e,activeRunId:this.#o===null?null:this.#o.runId,disposeOutcome:"closed"}),{runId:e,outcome:"closed",kill:null,instanceReleased:!1,durationMs:0};if(n.result.instanceReleased)return E.info("Dispose repeated for a run already torn down \u2014 replaying its outcome",{runId:e,disposeOutcome:n.result.outcome,instanceReleased:!0}),n.result;if(!n.killConfirmed)throw E.error("Dispose repeated for a run whose force-kill was never confirmed \u2014 the instance directory stays for the startup sweep",{runId:e,disposeOutcome:n.result.outcome,kill:n.result.kill,instanceReleased:!1}),new Error(`[runtime] the instance directory for run ${e} is deliberately retained: the force-kill of its process tree was never confirmed, and this runtime does not retry it. The startup sweep (CONTRACT-la \xA715 A3 rule 2) is the next eraser.`);let r=Date.now();E.warn("Dispose repeated for a run whose instance directory survived \u2014 retrying",{runId:e,disposeOutcome:n.result.outcome}),this.#a.release(e);let o={...n.result,instanceReleased:!0,durationMs:Date.now()-r};return this.#c={runId:e,result:o,killConfirmed:!0},E.info("Instance released on a repeated dispose",{runId:e,disposeOutcome:o.outcome,instanceReleased:!0,durationMs:o.durationMs}),o}async#f(e){let n=Date.now();this.#u=!0;let r="closed",o=null,a=null;try{if(e.context!==null){let m=await pr(e.context,e.timeoutMs);m.settled==="closed"?r="closed":m.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:m.error instanceof Error?m.error.message:String(m.error)}))}if(r!=="closed"||e.trigger==="instance_lost"||e.trigger==="dispose_during_launch")try{o=await et(e.userDataDir)}catch(m){a=m,E.error("Force-kill of the run process tree failed",{runId:e.runId,userDataDir:e.userDataDir,trigger:e.trigger,disposeOutcome:r,err:m instanceof Error?m.message:String(m)})}let l=a===null&&(o===null||o.survivorPids.length===0),c=null,p=!1;if(l)try{this.#a.release(e.runId),p=!0}catch(m){c=m,E.error("Failed to remove the instance directory after teardown",{runId:e.runId,userDataDir:e.userDataDir,err:m instanceof Error?m.message:String(m)})}else E.error("Instance directory KEPT \u2014 the force-kill is unconfirmed and the startup sweep must still be able to find this tree",{runId:e.runId,userDataDir:e.userDataDir,disposeOutcome:r,killFailed:a!==null,survivorPids:o===null?null:o.survivorPids});let f={runId:e.runId,outcome:r,kill:o,instanceReleased:p,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||c!==null?E.error("Instance disposed with a failed cleanup step",h):E.info("Instance disposed",h),c!==null)throw c;if(a!==null)throw a;if(o!==null&&o.survivorPids.length>0)throw new Error(`[runtime] force-kill for run ${e.runId} left ${o.survivorPids.length} process(es) alive after the settle delay (${o.survivorPids.join(", ")}). The instance directory ${e.userDataDir} is kept so the startup sweep can re-discover them (CONTRACT-la \xA715 A3 rule 2).`);return f}finally{this.#u=!1}}};async function H(t,e,n){try{return await n()}catch(r){throw r instanceof q||r instanceof B?r:new q(t,e,r instanceof Error?r.message:String(r),r)}}i(H,"stage");async function ba(t,e){let n=t.pages()[0];await(n===void 0?await t.newPage():n).goto(e.entryUrl,{waitUntil:"load"})}i(ba,"navigateToEntry");import{setTimeout as Ma}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)}i(pe,"computeBackoffDelayMs");function me(t){let e=va(t.error);return e!==null?{retry:!1,reason:e}:{retry:!0,delayMs:pe(t.attempt,t.rng)}}i(me,"decideGatewayRetry");function va(t){if(t instanceof y)return"terminal_signal";if(t instanceof M)return"contract_breach";if(t instanceof b)return"semantic_refusal";if(t.operation==="claim"||t.operation==="token_rotate")return"one_shot_operation";if(t instanceof G||t instanceof oe)return null;if(t instanceof _)return t.status===429?"rate_limited":t.status>=500?null:"semantic_refusal";throw new Error(`[backoff-policy] No retry row for ${t.name} on operation '${t.operation}'. A new GatewayError subclass was added without extending the decision table in src/gateway/backoff-policy.ts.`)}i(va,"classifyFailure");import{unlinkSync as La}from"node:fs";import{readFileSync as Sa,writeFileSync as ka,renameSync as Ra,mkdirSync as Ta,existsSync as Aa,chmodSync as Ia,fchmodSync as xa,openSync as Dr,fsyncSync as Lr,closeSync as Gr,unlinkSync as Oa}from"node:fs";import{join as Mr}from"node:path";var it=u("state-file");function at(t){return Mr(t,"runner-state.json")}i(at,"stateFilePath");function jt(t){return Mr(t,"runner-state.json.tmp")}i(jt,"stateTmpPath");function $r(t){let e=at(t);if(!Aa(e))return it.debug("No state file found \u2014 first start",{filePath:e}),null;let n;try{n=Sa(e,"utf-8")}catch(a){throw new Error(`[state-file] Failed to read state file at ${e}: ${String(a)}. If the file is corrupted, remove it and re-register with PROGON_RUNNER_TOKEN set.`)}let r;try{r=JSON.parse(n)}catch(a){throw new Error(`[state-file] State file at ${e} contains invalid JSON: ${String(a)}. Remove the file and re-register with PROGON_RUNNER_TOKEN set.`)}let o=Ca(r,e);return it.info("State file loaded",{agentId:o.agentId,protocolVersion:o.protocolVersion}),o}i($r,"readState");function Ur(t,e){Ta(t,{recursive:!0,mode:448}),Ia(t,448);let n=at(t),r=jt(t),o=JSON.stringify(e,null,2);try{let a=Dr(r,"w",384);try{xa(a,384),ka(a,o,{encoding:"utf-8"}),Lr(a)}finally{Gr(a)}Ra(r,n),Na(t)}catch(a){throw Pa(r),new Error(`[state-file] Failed to write state file at ${n}: ${String(a)}. Check permissions on stateDir ${t}.`)}it.info("State file written",{agentId:e.agentId,filePath:n})}i(Ur,"writeState");function Pa(t){try{Oa(t)}catch(e){if(e.code==="ENOENT")return;it.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(Pa,"removeStateTmp");function Na(t){let e=Dr(t,"r");try{Lr(e)}finally{Gr(e)}}i(Na,"fsyncDirectory");function Ca(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).`);On(r);let o=n.agentToken;if(typeof o!="string"||o==="")throw new Error(`[state-file] State file ${e} is missing or has invalid 'agentToken' (expected non-empty string).`);xt(o);let a=n.protocolVersion;if(typeof a!="number"||!Number.isInteger(a))throw new Error(`[state-file] State file ${e} is missing or has invalid 'protocolVersion' (expected integer).`);Pn(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{It(s)}catch(l){throw new Error(`[state-file] State file ${e} has an invalid 'serverUrl': ${String(l)}`)}return{agentId:r,agentToken:o,protocolVersion:a,serverUrl:s,tokenRotatedAt:Da(n,e)}}i(Ca,"validateState");function Da(t,e){let n=t.tokenRotatedAt;if(n==null)return null;if(typeof n!="string"||n==="")throw new Error(`[state-file] State file ${e} has an invalid 'tokenRotatedAt' (expected a non-empty ISO string, null, or the key to be absent on a file written before agent token rotation shipped).`);return n}i(Da,"readTokenRotatedAt");var Fr=u("token-store");function Z(t){return $r(t)}i(Z,"loadAgentIdentity");function he(t,e){Ur(t,e)}i(he,"saveAgentIdentity");function qr(t){let e=at(t),n=jt(t),r=jr(n,"temporary state file"),o=jr(e,"identity");if(!o&&!r){Fr.info("Agent identity wipe: no state file to remove",{filePath:e,tmpPath:n});return}Fr.warn("Agent identity wiped \u2014 this agent was revoked and must be re-enrolled",{filePath:e,tmpPath:n,removedState:o,removedTmp:r})}i(qr,"wipeAgentIdentity");function jr(t,e){try{return La(t),!0}catch(n){if(Ga(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(jr,"removeCredentialFile");function Ga(t){return t.code==="ENOENT"}i(Ga,"isFileNotFound");var J=u("supervisor-identity");async function ge(t){let{config:e}=t;if(e.initialToken!==void 0)return $a(e,e.initialToken);let n=Z(e.stateDir);if(n!==null)return qa(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 Fa(t,e.enrollmentCode);throw new Error(`[progon-agent] This machine has no agent identity, so the daemon cannot start.
|
|
17
|
+
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 Wi(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??Ji(),i=oe(e,Qn),s=oe(e,`${er}${process.pid}`);return Ui(e,{recursive:!0,mode:448}),Xi(e),Gt(s,{recursive:!0,force:!0}),Mi(r,s,{recursive:!0}),Gi(s,448),Yi(s,n),Gt(i,{recursive:!0,force:!0}),Fi(s,i),He.info("Agent-mode extension dist prepared",{extensionDist:i,sourceDir:r,agentId:n,protocolVersion:1}),i}o(Wi,"prepareAgentExtensionDist");function Yi(t,e){let n={agentMode:!0,agentId:e,protocolVersion:1};ji(oe(t,Mt),JSON.stringify(n,null,2)+`
|
|
18
|
+
`,"utf8")}o(Yi,"writeAgentManifest");function Xi(t){let e;try{e=$i(t,{withFileTypes:!0})}catch(n){if(typeof n=="object"&&n!==null&&n.code==="ENOENT")return;throw n}for(let n of e){if(!n.name.startsWith(er))continue;let r=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(Xi,"removeLeftoverStagingDirs");function tr(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).
|
|
19
|
+
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 Wi({stateDir:t.stateDir,agentId:t.agentId})}o(tr,"resolveExtensionDist");import{fetch as Qi}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,s){super(e,`[gateway] ${e} refused with HTTP ${n}: ${s}`),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")}},se=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 nr=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"),nr.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,rr(i),i)}let r;try{r=await n.text()}catch(i){throw new M(t.operation,rr(i),i)}if(!n.ok){let i=zi(n.status,r);throw nr.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,Zi(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,s=r.params,a=r.message;return{status:t,errorCode:typeof i=="string"?i:null,params:typeof s=="object"&&s!==null&&!Array.isArray(s)?s:null,message:typeof a=="string"?L(a):Ut}}o(zi,"readErrorEnvelope");var Ut="the response body carried no Progon error envelope";function rr(t){return L(t instanceof Error?t.message:String(t))}o(rr,"describeCause");function Zi(t){let e=t.issues;if(!Array.isArray(e)||e.length===0)return"the response body failed schema validation (the validator reported no issue list)";let n=e.map(r=>{let i=r.path;return!Array.isArray(i)||i.length===0?"<root>":i.map(s=>String(s)).join(".")});return`${e.length} schema violation(s) at: ${n.join(", ")}`}o(Zi,"summarizeSchemaViolation");var ae=class extends v{static{o(this,"EnrollmentSlowDownError")}retryAfterSec;constructor(e,n,r,i,s,a){super(e,n,r,i,s),this.retryAfterSec=a}},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 or(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(or,"mapEnrollError");function ir(t){return t.status===409&&t.errorCode==="agent_enroll.protocol_version"?x(Ie,"enrollment_request_create",t):C("enrollment_request_create",t)}o(ir,"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 ae("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 ar(t){return C("enrollment_request_cancel",t)}o(ar,"mapEnrollmentRequestCancelError");function lr(t){return me("poll_desired_state",t,()=>C("poll_desired_state",t))}o(lr,"mapPollDesiredStateError");function dr(t){return me("claim",t,()=>t.status===409&&t.errorCode==="run.not_claimable"?x(se,"claim",t):t.status===404?x(Y,"claim",t):C("claim",t))}o(dr,"mapClaimError");function cr(t){return me("fail",t,()=>t.status===404?x(Y,"fail",t):C("fail",t))}o(cr,"mapFailError");function ur(t){return me("token_status",t,()=>C("token_status",t))}o(ur,"mapTokenStatusError");function mr(t){return me("token_rotate",t,()=>C("token_rotate",t))}o(mr,"mapTokenRotateError");function pr(t){return me("declare_capabilities",t,()=>C("declare_capabilities",t))}o(pr,"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 hr=z.object({rotationDue:z.boolean(),tokenRotatedAt:z.string().nullable(),anchorAt:z.string(),intervalDays:z.number().int()}),gr=z.object({agentToken:z.string().regex(Q)});var Ke=u("gateway-client"),es="/api/agent-gateway";function N(t,e){return new URL(`${t.replace(/\/+$/,"")}${es}${e}`)}o(N,"buildGatewayUrl");var fr=3e5,wr=1e4,yr={headersTimeout:fr,bodyTimeout:fr,connect:{timeout:wr}};function ts(){let t=On(process.env);return Tn(Ct(process.env),t===void 0?yr:{...yr,connect:{timeout:wr,ca:t}},t)}o(ts,"buildGatewayDispatcher");var $t,Xe=o((t,e)=>{if($t===void 0){let n=ts();$t=o((r,i)=>Qi(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:or}),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:lr}),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:dr});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:cr}),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:ur});return P("token_status",hr.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:mr});return P("token_rotate",gr.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:pr}),Ke.info("Capabilities declared",{capabilities:Je})}useAgentToken(e){this.agentToken=e,Ke.info("Adopted a rotated agent token for all subsequent gateway requests")}};var ns=u("debug-env-guard"),rs=["pw:protocol","pw:api"];function os(t){return t.replace(/[\\^$.|?+()[\]{}]/g,"\\$&")}o(os,"escapeRegExp");function Er(t){if(t.startsWith("-"))return!1;let e=`^${t.split("*").map(os).join(".*?")}$`,n=new RegExp(e);return rs.some(r=>n.test(r))}o(Er,"enablesPlaywright");function is(){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=>Er(i));if(n.length===0)return[];let r=e.filter(i=>!Er(i));return r.length===0?delete process.env.DEBUG:process.env.DEBUG=r.join(","),ns.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(is,"sanitizePlaywrightDebugEnv");is();import{statSync as _r}from"node:fs";import{isAbsolute as as,join as ls}from"node:path";import{createRequire as ss}from"node:module";var $=ss(import.meta.url)("playwright-core"),ze=$.chromium,kc=$.firefox,Tc=$.webkit,Ac=$.selectors,Ic=$.devices,xc=$.errors,Oc=$.request,Pc=$._electron,Nc=$._android;var Ze="chromium";var vr="instances",Qe="instance.json";async function Sr(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(Sr,"launchExtensionContext");function ds(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(ds,"requireBrowser");function Rr(t){return ds(t).version()}o(Rr,"readChromeVersion");async function br(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(br,"raceClose");function kr(t){if(!as(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=_r(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=ls(t,"manifest.json");try{_r(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(kr,"assertUsableExtensionDist");var cs=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(s=>{n&&cs.warn("An abandoned worker.evaluate rejected after its deadline had passed",{operation:t.operation,timeoutMs:t.timeoutMs,err:s instanceof Error?s.message:String(s)})});let r,i=new Promise((s,a)=>{r=setTimeout(()=>{n=!0,a(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 Tr="accessToken",Ar="refreshToken";async function xr(t,e){await q({operation:"write the run session into chrome.storage.local",timeoutMs:1e4,evaluate:o(()=>t.evaluate(([r,i,s,a])=>new Promise(l=>chrome.storage.local.set({[r]:s,[i]:a},()=>l())),[Tr,Ar,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(s=>chrome.storage.local.get([r,i],a=>{let l=a[r],d=a[i];s({accessTokenLength:typeof l=="string"?l.length:null,refreshTokenLength:typeof d=="string"?d.length:null})})),[Tr,Ar]),"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(xr,"seedRunSession");function Ir(t){return JSON.stringify(Object.keys(t).sort().map(e=>[e,t[e]]))}o(Ir,"canonicalise");async function Or(t,e){await q({operation:`write the command envelope to chrome.storage.local['${Se}']`,timeoutMs:1e4,evaluate:o(()=>t.evaluate(([s,a])=>new Promise(l=>chrome.storage.local.set({[s]:a},()=>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(s=>new Promise(a=>chrome.storage.local.get([s],l=>{let d=l[s];a(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=Ir({...e}),i=Ir(n);if(r!==i)throw new Error(`command envelope read-back mismatch: wrote ${r}, read ${i}`)}o(Or,"seedCommandEnvelope");async function ms(t,e,n){let r=await q({operation:`read chrome.storage.local['${Ce}']`,timeoutMs:n,evaluate:o(()=>t.evaluate(s=>new Promise(a=>chrome.storage.local.get([s],l=>{let d=l[s];a(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(ms,"pollCommandAck");async function Pr(t,e,n){let r=Date.now()+n,i="no ack was written";for(;;){let s=r-Date.now();if(s<=0)throw new Error(`no command ack for run ${e} within ${n}ms \u2014 ${i}. chrome.storage.local['${Ce}'] is the only success signal (CONTRACT-la \xA75.4).`);let a=t.serviceWorkers()[0];if(a===void 0)i="the context exposed no service worker while polling (evicted, restarting)";else{let l;try{l=await ms(a,e,s)}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(Pr,"waitForCommandAck");import tt from"node:os";import{createRequire as ps}from"node:module";var Nr=ps(import.meta.url);function hs(){let t=Nr.resolve("playwright-core/package.json"),e=Nr(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(hs,"readPlaywrightCoreVersion");function Cr(t){return{node:process.version,platform:`${tt.platform()} ${tt.release()} ${tt.arch()}`,cpus:tt.cpus().length,playwrightCore:hs(),chromiumExecutable:ze.executablePath(),channel:Ze,extensionDist:t}}o(Cr,"buildEnvFingerprint");import{mkdirSync as Fr,readdirSync as xs,readFileSync as Os,renameSync as Ps,rmSync as qt,writeFileSync as Ns}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 Dr(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(Dr,"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 fs}from"node:child_process";import{promisify as ys}from"node:util";import{setTimeout as Ur}from"node:timers/promises";var rt=ys(fs),ot={timeout:5e3};function $r(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($r,"asExecFailure");function ws(t){let e=[];for(let n of t.split(`
|
|
20
|
+
`)){let r=n.trim();if(r==="")continue;let i=Number(r);!Number.isInteger(i)||i===process.pid||e.push(i)}return e}o(ws,"parsePidLines");var jt="--user-data-dir=",Es=new Set([" "," ",'"',"'"]),vs=new Set([" "," ",'"',"'"]);function _s(t){return t.replace(/[\\^$.|?*+()[\]{}]/g,"\\$&")}o(_s,"escapeEre");function Ss(t){return`(^|[[:space:]'"])${_s(`${jt}${t}`)}([[:space:]'"]|$)`}o(Ss,"buildAnchorPattern");function Rs(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 s=i===0?void 0:n[i-1],a=n[i+r.length],l=s===void 0||Es.has(s),d=a===void 0||vs.has(a);if(l&&d)return!0}return!1}o(Rs,"matchesAnchor");async function bs(t){try{let{stdout:e}=await rt("pgrep",["-f",Ss(t)],ot);return ws(e)}catch(e){let n=$r(e);if(n!==null&&n.code===1&&n.stdout.trim()==="")return[];throw e}}o(bs,"discoverPosix");async function Lr(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 s of r.split(`
|
|
21
|
+
`)){let a=s.indexOf(" ");if(a===-1)continue;let l=Number(s.slice(0,a).trim()),d=s.slice(a+1);!Number.isInteger(l)||l===process.pid||Rs(d,t)&&i.push(l)}return i}o(Lr,"discoverWin32");async function Gr(){let{stdout:t}=await rt("ps",["-A","-o","pid=,ppid=,pgid="],ot),e=[];for(let n of t.split(`
|
|
22
|
+
`)){let r=n.trim().split(/\s+/);if(r.length<3)continue;let[i,s,a]=r,l=Number(i),d=Number(s),m=Number(a);!Number.isInteger(l)||!Number.isInteger(d)||!Number.isInteger(m)||e.push({pid:l,ppid:d,pgid:m})}return e}o(Gr,"readProcessTable");function ks(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 s=t.find(d=>d.pid===process.pid),a=s===void 0?null:s.pgid,l=new Set;for(let d of t)r.has(d.pid)&&(d.pgid<=0||a!==null&&d.pgid===a||l.add(d.pgid));return r.delete(process.pid),{members:[...r],groups:[...l]}}o(ks,"expandTree");function Ts(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(Ts,"sigkill");async function it(t){return process.platform==="win32"?Is(t):As(t)}o(it,"killProcessTree");async function As(t){let e=await bs(t);if(e.length===0)return{platform:process.platform,userDataDir:t,discoveredPids:[],signalledPids:[],survivorPids:[]};let n=await Gr(),{members:r,groups:i}=ks(n,e),s=[];for(let d of r)Ts(d)==="signalled"&&s.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 Ur(500);let a=await Gr(),l=new Set(a.map(d=>d.pid));return{platform:process.platform,userDataDir:t,discoveredPids:e,signalledPids:s,survivorPids:r.filter(d=>l.has(d))}}o(As,"killProcessTreePosix");async function Is(t){let e=await Lr(t),n=[];for(let i of e)try{await rt("taskkill.exe",["/T","/F","/PID",String(i)],ot),n.push(i)}catch(s){let a=$r(s);if(a===null||a.code!==128)throw s}await Ur(500);let r=await Lr(t);return{platform:"win32",userDataDir:t,discoveredPids:e,signalledPids:n,survivorPids:r}}o(Is,"killProcessTreeWin32");var Z=u("instance-registry");function st(t){return typeof t=="string"&&t!==""}o(st,"isNonEmptyString");function Cs(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(!st(n.runId))throw new Error(`[instance-registry] ${e} has a missing or empty runId.`);if(!st(n.userDataDir))throw new Error(`[instance-registry] ${e} has a missing or empty userDataDir.`);if(!st(n.startedAt)||!st(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(Cs,"parseInstanceRecord");function Ds(t,e){let n=`${t}.tmp`;Ns(n,JSON.stringify(e,null,2),{encoding:"utf8",mode:384}),Ps(n,t)}o(Ds,"writeMarkerAtomically");var at=class{static{o(this,"InstanceRegistry")}#e;constructor(e){this.#e=xe(e,vr)}get instancesRoot(){return this.#e}userDataDirFor(e){return xe(this.#e,e)}reserve(e,n){Fr(this.#e,{recursive:!0,mode:448});let r=this.userDataDirFor(e);try{Fr(r,{recursive:!1,mode:448})}catch(s){throw typeof s=="object"&&s!==null&&s.code==="EEXIST"?new H(e,r,s):s}let i=new Date().toISOString();try{Ds(xe(r,Qe),{v:1,runId:e,agentPid:process.pid,userDataDir:r,startedAt:i,deadlineAt:n})}catch(s){try{qt(r,{recursive:!0,force:!0})}catch(a){Z.error("Failed to roll back the instance directory after a failed reservation",{runId:e,userDataDir:r,err:a instanceof Error?a.message:String(a)})}throw s}return 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=xs(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,s;try{i=this.#n(r),s="valid"}catch(l){s=(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:s,err:l instanceof Error?l.message:String(l)})}let a=await it(n);return Z.warn("Leftover browser instance swept",{runId:e,userDataDir:n,marker:s,kill:a}),qt(n,{recursive:!0,force:!0}),{runId:e,userDataDir:n,marker:s,record:i,kill:a,removed:!0}}#n(e){let n=Os(e,"utf8");return Cs(JSON.parse(n),e)}};async function jr(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 s=>{let a=await new Promise(h=>chrome.storage.session.get(["tabStates",s],h)),l=a.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=a[s],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(jr,"probePlaybackSession");async function qr(t,e){let r=t.serviceWorkers()[0];return r!==void 0?r:t.waitForEvent("serviceworker",{timeout:e})}o(qr,"waitForServiceWorker");async function Br(t,e){let n,r=new Promise((i,s)=>{n=setTimeout(()=>s(new Error(`chrome.runtime.id did not resolve within ${e}ms \u2014 the extension's service worker is not executing`)),e)});try{let i=await Promise.race([t.evaluate(()=>chrome.runtime.id),r]);if(typeof i!="string"||i==="")throw new Error(`chrome.runtime.id returned ${JSON.stringify(i)} \u2014 expected a non-empty extension id`);return i}finally{n!==void 0&&clearTimeout(n)}}o(Br,"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 Vr(t){let e=Date.now(),n=e+45e3,r=n-5e3,i=await qr(t,Math.min(5e3,lt(r,"the service-worker target wait")));try{let s=await Br(i,lt(r,"the first readiness evaluate"));return{worker:i,extensionId:s,serviceWorkerUrl:i.url(),attempts:1,readyAfterMs:Date.now()-e}}catch(s){let a=await t.newPage();try{let l=await qr(t,Math.min(5e3,lt(n,"the retry service-worker target wait"))),d=await Br(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=s instanceof Error?s.message:String(s),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 a.close()}}}o(Vr,"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;#s;#a;#o=null;#i=null;#u=!1;#l=null;#c=null;constructor(e){kr(e.extensionDist),this.#e=e.extensionDist,this.#t=e.headfulOverride,this.#n=e.allowInsecureHttps,this.#r=e.onInstanceLost,this.#s=new at(e.stateDir),this.#a=Cr(e.extensionDist),E.info("Execution runtime constructed",{stateDir:e.stateDir,instancesRoot:this.#s.instancesRoot,headfulOverride:e.headfulOverride,allowInsecureHttps:e.allowInsecureHttps,envFingerprint:this.#a})}getActiveInstance(){let e=this.#o;return e===null?null:{runId:e.runId,userDataDir:e.userDataDir,headful:e.headful,extensionId:e.extensionId,chromeVersion:e.chromeVersion,startedAt:e.startedAt,deadlineAt:e.deadlineAt}}async sweepOrphanInstances(){return this.#s.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"}:jr(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(),s=await V(e.runId,"instance_reserve",()=>this.#s.reserve(e.runId,i));this.#c?.runId===e.runId&&(this.#c=null);let a={runId:e.runId,userDataDir:s.userDataDir,context:null,disposeRequested:!1};this.#i=a;let l=this.#p(e);E.info("Launching browser for run",{runId:e.runId,headful:l,requestHeadful:e.headful,headfulOverride:this.#t,userDataDir:s.userDataDir,maxRunDurationSec:e.maxRunDurationSec,deadlineAt:i,envFingerprint:this.#a});let d=null;try{let m=await V(e.runId,"browser_launch",()=>Sr({userDataDir:s.userDataDir,extensionDist:this.#e,headful:l,allowInsecureHttps:this.#n}));d=m,a.context=m,this.#m(a);let f=await V(e.runId,"browser_version",()=>Rr(m)),h=await V(e.runId,"readiness_probe",()=>Vr(m));await this.#h(e,h.worker),await V(e.runId,"entry_navigation",()=>Ms(m,e)),await this.#d(e,m);let p={runId:e.runId,context:d,userDataDir:s.userDataDir,headful:l,extensionId:h.extensionId,chromeVersion:f,startedAt:s.startedAt,deadlineAt:i};this.#m(a),this.#g(p),this.#o=p,this.#i===a&&(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===a&&(this.#i=null),await this.#f({runId:e.runId,context:d,userDataDir:s.userDataDir,timeoutMs:2e4,trigger:a.disposeRequested?"dispose_during_launch":"launch_failure"}),m}finally{this.#i===a&&(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 s=this.#o;return s===null||s.runId!==e?this.#w(e):(this.#o=null,this.#f({runId:e,context:s.context,userDataDir:s.userDataDir,timeoutMs:n,trigger:"dispose"}))}#p(e){return e.headful||this.#t}async#h(e,n){let r=await V(e.runId,"token_seed",()=>xr(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",()=>Or(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",()=>Pr(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 s=this.#f({runId:e.runId,context:e.context,userDataDir:e.userDataDir,timeoutMs:2e4,trigger:"instance_lost"});this.#l={runId:e.runId,promise:s},s.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===s&&(this.#l=null)});let a={runId:e.runId,at:new Date().toISOString(),source:i};E.error("Browser instance disappeared without a dispose",{...a}),this.#r(a)},"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.#s.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,s=null;try{if(e.context!==null){let p=await br(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){s=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=s===null&&(i===null||i.survivorPids.length===0),d=null,m=!1;if(l)try{this.#s.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:s!==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:s!==null,instanceReleased:f.instanceReleased,durationMs:f.durationMs};if(s!==null||d!==null?E.error("Instance disposed with a failed cleanup step",h):E.info("Instance disposed",h),d!==null)throw d;if(s!==null)throw s;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 Ms(t,e){let n=t.pages()[0];await(n===void 0?await t.newPage():n).goto(e.entryUrl,{waitUntil:"load"})}o(Ms,"navigateToEntry");import{setTimeout as $s}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=Us(t.error);return e!==null?{retry:!1,reason:e}:{retry:!0,delayMs:pe(t.attempt,t.rng)}}o(he,"decideGatewayRetry");function Us(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(Us,"classifyFailure");var J=u("supervisor-identity");async function ge(t){let{config:e}=t;if(e.initialToken!==void 0)return Fs(e,e.initialToken);let n=G(e.stateDir);if(n!==null)return Hs(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 qs(t,e.enrollmentCode);throw new Error(`[progon-agent] This machine has no agent identity, so the daemon cannot start.
|
|
17
23
|
There is no state file in ${e.stateDir} and neither PROGON_AGENT_TOKEN nor PROGON_AGENT_ENROLL_CODE is set.
|
|
18
|
-
To enroll: create the agent in Progon (Settings \u2192 Agents), mint its enrollment code, then start the daemon once with PROGON_AGENT_ENROLL_CODE=<code>. The code is one-shot and expires in 15 minutes (CONTRACT-la \xA75.1); the minted pgat_ token is persisted to the state file, so later starts need neither variable.`)}
|
|
19
|
-
Mint a fresh code in Progon (Settings \u2192 Agents) once the server is reachable, then run 'progon-agent enroll <code>' again.`,{cause:
|
|
20
|
-
Either point PROGON_SERVER_URL back at the enrolled server, or enroll this machine against the new one (remove the state file and start once with PROGON_AGENT_ENROLL_CODE=<code>).`)}i(qa,"assertServerMatchesEnrollment");import{createRequire as Ba}from"node:module";import{hostname as Ha}from"node:os";var Hr=["darwin","linux","win32"],Jr=["x64","arm64"];function Ja(t){return Hr.includes(t)}i(Ja,"isSupportedPlatform");function Va(t){return Jr.includes(t)}i(Va,"isSupportedArch");function Ka(){let e=Ba(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(Ka,"readAgentVersion");function fe(){let t=process.platform;if(!Ja(t))throw new Error(`[supervisor] Unsupported platform ${JSON.stringify(t)}. The local agent runs on ${Hr.join(", ")} (CONTRACT-la \xA75.1, \xA710.3).`);let e=process.arch;if(!Va(e))throw new Error(`[supervisor] Unsupported CPU architecture ${JSON.stringify(e)}. The local agent runs on ${Jr.join(", ")} (CONTRACT-la \xA75.1).`);let n=Ha();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:Ka()}}i(fe,"describeAgentMachine");var Vr=i(()=>{},"noop"),st=class{static{i(this,"ActionQueue")}#e=Promise.resolve();run(e){let n=this.#e.then(e,e);return this.#e=n.then(Vr,Vr),n}};var Kr=u("supervisor-deadline"),Te=class extends Error{static{i(this,"DeadlineExceededError")}operation;timeoutMs;constructor(e,n){super(`[supervisor] ${e} did not settle within ${n}ms`),this.name="DeadlineExceededError",this.operation=e,this.timeoutMs=n}};async function lt(t){let e=t.work(),n=!1;e.then(()=>{n&&Kr.warn("Abandoned work settled successfully after its deadline had passed",{operation:t.operation,timeoutMs:t.timeoutMs})},a=>{n&&Kr.warn("Abandoned work rejected after its deadline had passed",{operation:t.operation,timeoutMs:t.timeoutMs,err:a instanceof Error?a.message:String(a)})});let r,o=new Promise((a,s)=>{r=setTimeout(()=>{n=!0,s(new Te(t.operation,t.timeoutMs))},t.timeoutMs)});try{return await Promise.race([e,o])}finally{r!==void 0&&clearTimeout(r)}}i(lt,"withDeadline");function dt(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(dt,"sleep");var V=u("fail-reporter"),ct=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){V.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&&V.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,V.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&&(V.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});V.info("Fail verdict delivered",{runId:e.runId,reason:e.reason,status:n.status,attempts:e.attempt+1}),this.#t=null}catch(n){if(n instanceof y)throw n;if(n instanceof b)throw V.error("Fail verdict abandoned \u2014 the gateway no longer accepts this credential as current",{runId:e.runId,reason:e.reason,err:n.message}),this.#t=null,n;if(!(n instanceof v))throw n;let r=me({attempt:e.attempt,error:n});if(!r.retry){V.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},V.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 ut=120,Wr=ut*1e3,qt=3e4,ye=3,Bt=45*1e3,Ht="agent shutdown";var U=u("launch-run");async function zr(t){let e=await Ya(t);return e.kind!=="claimed"?e:za(t,e.payload)}i(zr,"claimAndLaunch");async function Ya(t){try{let e=await t.client.claimRun(t.runId);return U.info("Run claimed",Xa(e)),{kind:"claimed",payload:e}}catch(e){if(e instanceof y)throw e;if(e instanceof b)throw U.error("Claim refused as superseded \u2014 not launching, leaving it to the sweep",{runId:t.runId,err:e.message}),e;if(e instanceof ie||e instanceof W)return U.info("Claim refused \u2014 the desired-state snapshot was stale, not launching",{runId:t.runId,err:e.message}),{kind:"claim_refused"};if(!(e instanceof v))throw e;return U.error("Claim produced no usable answer \u2014 not launching, leaving it to the sweep",{runId:t.runId,err:e.message}),{kind:"claim_unavailable"}}}i(Ya,"claimRun");function Xa(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(Xa,"describeClaim");async function za(t,e){try{await lt({operation:`startRun(${e.runId})`,timeoutMs:Wr,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",...Qa(t.runId,r)}}let n=t.runtime.getActiveInstance();return n===null||n.runId!==e.runId?(U.error("The launched instance was already gone when the supervisor read it back",{runId:e.runId,activeRunId:n===null?null:n.runId}),{kind:"instance_lost_immediately",runId:e.runId}):{kind:"launched",instance:n}}i(za,"launchClaimedRun");var Yr=500,Xr="\u2026";function Za(t){return t.length<=Yr?t:t.slice(0,Yr-Xr.length)+Xr}i(Za,"fitFailMessageToWire");function Qa(t,e){return e instanceof q?(U.error("Launch failed",{runId:t,stage:e.stage,failReason:e.failReason,err:e.message}),{reason:e.failReason,message:Za(`stage ${e.stage}: ${vr(e)}`)}):e instanceof Te?(U.error("Launch exceeded the agent-side launch deadline \u2014 disposing and failing",{runId:t,launchTimeoutSec:ut,err:e.message}),{reason:"launch_error",message:`launch did not complete within ${ut}s`}):e instanceof B?(U.error("Launch refused by the instance fence \u2014 the run cannot be started here",{runId:t,userDataDir:e.userDataDir,err:e.message}),{reason:"launch_error",message:"a leftover instance directory blocks this run"}):(U.error("Launch failed with an unexpected error class",{runId:t,errName:e instanceof Error?e.name:typeof e,err:e instanceof Error?e.message:String(e)}),{reason:"launch_error",message:"launch failed with an unexpected error"})}i(Qa,"describeLaunchFailure");var we=u("run-monitor");function es(t,e){let n=Date.now();return e.ok?e.tabs.some(o=>o.playback!==null&&o.playback.runId===t)?{healthy:!0}:ts(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 (${ns(e.tabs)}; ${rs(e.agentJob,n)})`}:{healthy:!1,reason:e.reason,detail:e.detail}}i(es,"judgeProbe");function ts(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<=Bt}i(ts,"isJobPulseStanding");function ns(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(ns,"describeTabs");function rs(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(Bt)}ms)`}i(rs,"describeJobMarker");var pt=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());we.info("Monitoring launched run",{runId:this.#e.runId,deadlineAt:this.#e.deadlineAt,deadlineInMs:e,probeIntervalMs:qt,probeStrikeLimit:ye}),this.#n=setInterval(()=>{this.#o()},qt),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=es(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 os(t){let e=i(()=>{},"markSettled"),n=new Promise(r=>{e=r});return{runId:t,cancelledBy:null,settled:n,markSettled:e}}i(os,"createPendingLaunch");var mt=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)),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 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){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.#p(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=os(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 zr({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){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 pt({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";D.error("The server publishes a run this agent is not carrying \u2014 reporting it",{runId:e,phase:n,sweptAtStartup:r,reason:o}),await this.#n.report({runId:e,reason:o,message:r?"a leftover browser instance for this run was killed by the agent startup sweep":"this agent holds no browser instance for the run"})}async#g(e,n,r,o){await this.dispose(e,o),await this.#n.report({runId:e,reason:n,message:r})}};var Zr={revoked:"agent_revoked",reenroll_required:"agent_superseded",credential_unusable:"agent_superseded",fatal:"shutdown",stopped:"shutdown"};var A=u("token-rotation"),Qr=1440*60*1e3,ht=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 A.error("The agent token in PROGON_AGENT_TOKEN has been superseded and the server no longer accepts it. This daemon owns no copy of it and will not touch the state directory: set PROGON_AGENT_TOKEN to a current token and restart, or unset it and enroll this machine so the daemon can rotate on its own."),"alive";try{return await this.#e.getTokenRotationStatus({signal:e}),"alive"}catch(n){if(n instanceof b)return"reenroll_required";if(n instanceof y)throw n;if(n instanceof v)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.#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 b)return A.error("This agent token has been superseded and no longer authenticates \u2014 the token family is dead and this machine must be enrolled again"),{kind:"outcome",outcome:{kind:"reenroll_required"}};if(n instanceof y)throw n;if(n instanceof v)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 o;try{o=(await this.#e.rotateToken()).agentToken}catch(s){if(s instanceof y)throw s;if(s instanceof b)return await this.#c(r);if(s instanceof v)return A.warn("The rotation request produced no usable answer \u2014 probing what the server actually committed",{operation:s.operation,err:s.message}),await this.#m(n);throw s}this.#d({...e,agentToken:o,tokenRotatedAt:null},"rotated agent token"),this.#e.useAgentToken(o);let a=await this.#h();return a.kind==="reenroll_required"?a:(a.kind==="observed"&&this.#d({...e,agentToken:o,tokenRotatedAt:a.tokenRotatedAt},"rotation marker of the new agent token"),A.info("Agent token rotated"),{kind:"rotated"})}async#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#m(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 he(this.#t,e),!0}catch(r){return A.error(`The ${n} could not be written to the state directory. This process keeps using the credential it holds, but a restart would fall back to the token on disk, which the server will refuse once its rotation grace window closes. Fix the permissions on the state directory BEFORE restarting the daemon; if it has already been restarted, enroll this machine again.`,{stateDir:this.#t,err:r instanceof Error?r.message:String(r)}),!1}}#p(){let e;try{e=Z(this.#t)}catch(n){return{kind:"unreadable",err:n instanceof Error?n.message:String(n)}}return e===null?{kind:"absent"}:{kind:"identity",identity:e}}#g(e){return e.kind==="unreadable"?(A.error("The agent identity in the state directory cannot be read, so the credential this daemon is running on can neither be rotated nor replaced. The daemon keeps working on the token it holds in memory and will look again on the next scheduled check \u2014 restore the state directory from a backup, or enroll this machine again before restarting the daemon.",{stateDir:this.#t,identitySource:this.#n,err:e.err}),{kind:"identity_unavailable"}):(A.error("The agent identity is no longer in the state directory, so the credential this daemon is running on can neither be rotated nor replaced. The daemon keeps working on the token it holds in memory and will look again on the next scheduled check \u2014 restore the state directory, or enroll this machine again before restarting the daemon.",{stateDir:this.#t,identitySource:this.#n}),{kind:"identity_unavailable"})}};var I=u("run-supervisor"),Jt=i(()=>Promise.resolve(),"noVerdictOwed"),gt=class{static{i(this,"RunSupervisor")}#e;#t;#n;#r=new st;#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 ct(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 mt({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.#x();if(e!==null)return e;for(this.#k(),await this.#w();!this.#u;){let n=this.#c;if(n!==null)return await this.#_(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 y)return await this.#_(r),"revoked";if(r instanceof b&&await this.#R(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 y||e instanceof b||!(e instanceof v))throw e;I.error("Could not declare capabilities \u2014 job kinds this build supports will not be published to this agent until the next start; playback is unaffected",{err:e.message})}}async shutdown(e){let n=this.#g;if(n!==null)return I.info("A shutdown is already in progress \u2014 joining it",{cause:e}),n;let r=this.#f(e);return this.#g=r,r}async#f(e){I.info("Shutting down",{cause:e}),await this.#y(e==="fatal"?"fatal":"stopped",n=>this.#S(n))}async#y(e,n){this.#u=!0,this.#o?.abort(),this.#l.abort();let r=Zr[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#S(e){let{activeRunId:n,launchingRunId:r}=e;if(n!==null){await this.#v(()=>this.#t.report({runId:n,reason:"browser_gone",message:Ht}));return}if(r!==null){await this.#v(()=>this.#t.report({runId:r,reason:"browser_gone",message:Ht}));return}await this.#v(()=>this.#t.retryPending())}async#x(){try{if((await this.#d.runCycle(this.#l.signal)).kind!=="reenroll_required")return null}catch(e){if(e instanceof y)return await this.#_(e),"revoked";throw e}return await this.#b(),"reenroll_required"}#k(){if(this.#u||this.#l.signal.aborted)return;let e=setTimeout(()=>{this.#p=null,this.#O().finally(()=>{this.#k()})},Qr);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.#I(e)}}#P(){this.#p!==null&&(clearTimeout(this.#p),this.#p=null)}async#R(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(),qr(this.#a)}async#_(e){I.error("This agent has been revoked \u2014 disposing, wiping the credential and stopping",{signal:e.signal}),await this.#y("revoked",Jt),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",Jt)}async#C(){await this.#y("fatal",e=>this.#S(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",Jt),await this.#E()}async#D(e){if(!(e instanceof v))throw e;let n=this.#L(e);return n.kind==="exit"?n.exit:(this.#i+=1,await dt(n.delayMs,this.#l.signal),null)}#L(e){if(e instanceof b){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=me({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 b){try{await this.#R(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#v(e){try{await e()}catch(n){if(n instanceof b){I.error("This agent token is no longer accepted as current, so the run could not be reported. The credential on disk is left alone \u2014 the next start diagnoses it and will say whether this machine has to be enrolled again.",{operation:n.operation});return}if(n instanceof y){await this.#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 eo=u("supervisor-boot");async function to(){let t=ne();eo.info("Config loaded",{serverUrlOrigin:new URL(t.serverUrl).origin,stateDir:t.stateDir,headfulOverride:t.headfulOverride,allowInsecureHttps:t.allowInsecureHttps});let e=fe(),n=await ge({config:t,machine:e});eo.info("Agent identity resolved",{source:n.source,agentId:n.agentId,hostname:e.hostname,platform:e.platform,arch:e.arch,agentVersion:e.agentVersion});let r=Bn({overridePath:t.extensionDistOverride,stateDir:t.stateDir,agentId:n.agentId});await Ce({stdio:"pipe"});let o=new He({serverUrl:t.serverUrl,agentToken:n.agentToken}),a=new ht({client:o,stateDir:t.stateDir,identitySource:n.source});return new gt({client:o,stateDir:t.stateDir,pollWaitSec:n.pollWaitSec,tokenRotation:a,createRuntime:i(s=>new ot({stateDir:t.stateDir,extensionDist:r,headfulOverride:t.headfulOverride,allowInsecureHttps:t.allowInsecureHttps,onInstanceLost:s}),"createRuntime")})}i(to,"bootRunSupervisor");import{createHash as ms,randomBytes as hs}from"node:crypto";import{z as T}from"zod";var no=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()}),ro=T.object({status:T.literal("authorization_pending"),expiresAt:T.iso.datetime({offset:!0}),pollIntervalSec:T.number().int().positive()}),is=T.object({companyName:T.string(),approvedByEmail:T.string(),approvedAt:T.string()}),oo=T.object({credential:Pe,approval:is});var io=u("gateway-enrollment-request"),ft=class{static{i(this,"GatewayEnrollmentRequestClient")}serverUrl;machine;fetchImpl;constructor(e){this.serverUrl=e.serverUrl,this.machine=e.machine,this.fetchImpl=e.fetchImpl??Je}async create(e){let n=await Y({operation:"enrollment_request_create",method:"POST",url:N(this.serverUrl,"/enrollment-requests"),agentToken:null,body:{deviceSecretHash:e,protocolVersion:1,...this.machine},signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:Kn}),r=P("enrollment_request_create",no.safeParse(n));return io.info("Enrollment request opened",{requestId:r.requestId,mode:r.mode,pollIntervalSec:r.pollIntervalSec,expiresAt:r.expiresAt}),r}async poll(e){let n=await Y({operation:"enrollment_request_poll",method:"POST",url:N(this.serverUrl,"/enrollment-requests/poll"),agentToken:null,body:{deviceSecret:e},signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:Wn}),r=typeof n=="object"&&n!==null?n:null;if(r!==null&&"credential"in r){let o=P("enrollment_request_poll",oo.safeParse(n));return io.info("Enrollment request approved",{agentId:o.credential.agentId}),{kind:"enrolled",credential:o.credential,approval:o.approval}}if(r!==null&&"status"in r){let o=P("enrollment_request_poll",ro.safeParse(n));return{kind:"pending",expiresAt:o.expiresAt,pollIntervalSec:o.pollIntervalSec}}throw new M("enrollment_request_poll","the 2xx body is neither the authorization_pending answer nor the success envelope CONTRACT-phase-c \xA74.1 M2 defines")}async cancel(e){await Y({operation:"enrollment_request_cancel",method:"POST",url:N(this.serverUrl,"/enrollment-requests/cancel"),agentToken:null,body:{deviceSecret:e},signal:void 0,fetchImpl:this.fetchImpl,mapHttpError:Yn})}};import{spawn as as}from"node:child_process";var Ae=u("browser-open");function yt(t){return t!==void 0&&t!==""}i(yt,"isSet");function ss(t,e){return!(yt(t.SSH_CONNECTION)||yt(t.SSH_TTY)||e==="linux"&&!yt(t.DISPLAY)&&!yt(t.WAYLAND_DISPLAY))}i(ss,"shouldAttemptBrowserOpen");var ls=/[&|^<>"'` ]/;function ds(t){let e;try{e=new URL(t)}catch{return!1}return e.protocol!=="http:"&&e.protocol!=="https:"||t!==e.href?!1:!ls.test(t)}i(ds,"isSpawnSafeUrl");function cs(t,e){switch(e){case"darwin":return{command:"open",args:[t]};case"linux":return{command:"xdg-open",args:[t]};case"win32":return{command:"cmd",args:["/d","/s","/c","start","",t]};default:return null}}i(cs,"browserOpenCommand");function ao(t,e,n){if(!ss(e,n)){Ae.debug("Not opening a browser: this host has no desktop to open one on",{platform:n});return}if(!ds(t)){Ae.warn('Not opening a browser: the verification URL the server returned is not safe to hand to a spawned process. Follow the "Approve at:" link printed above instead',{platform:n});return}let r=cs(t,n);if(r===null){Ae.debug("Not opening a browser: no opener is defined for this platform",{platform:n});return}try{let o=as(r.command,[...r.args],{detached:!0,stdio:"ignore"});o.on("error",a=>{Ae.debug("Could not start the browser; the approval URL was printed instead",{platform:n,command:r.command,err:a.message})}),o.unref()}catch(o){Ae.debug("Could not start the browser; the approval URL was printed instead",{platform:n,command:r.command,err:o instanceof Error?o.message:String(o)})}}i(ao,"openVerificationUrl");var us=30,ps=5;function so(t){return{intervalSec:t.pollIntervalSec,deadlineMs:t.timeoutSec===null?t.expiresAtMs:Math.min(t.expiresAtMs,t.nowMs+t.timeoutSec*1e3)}}i(so,"initialPollSchedule");function wt(t,e){if(e.kind==="pending")return{state:t,delayMs:t.intervalSec*1e3};if(e.kind==="slow_down"){let r=t.intervalSec+ps,o=e.retryAfterSec!==null&&e.retryAfterSec>r?e.retryAfterSec:r,a=Math.min(o,us);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)}}i(wt,"nextPollDelayMs");function lo(t,e){return e>=t.deadlineMs}i(lo,"isDeadlinePassed");function co(t,e,n){return Math.max(0,Math.min(e,t.deadlineMs-n))}i(co,"clampDelayToDeadline");var Ee=u("device-enrollment"),gs=24,fs=2e3,Vt=0,Ie=1,po=130,ys="This machine is already enrolled. Start the daemon with: progon-agent start",ws="Enrollment was denied in the browser. Nothing was created on this machine.",Es="Cancelled. Nothing was saved on this machine.",_s="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 uo(t){return`Enrollment request expired. Run: progon-agent enroll --server ${t}`}i(uo,"expiredLine");function bs(t,e){return`Timed out after ${t}s waiting for approval. The request is still open \u2014 approve at: ${e}`}i(bs,"timedOutLine");function vs(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(vs,"alreadyCompletedLine");function Ss(t){return`Enrollment request is no longer valid. Run: progon-agent enroll --server ${t}`}i(Ss,"noLongerValidLine");async function mo(t){let e=t.env??process.env;t.serverUrl!==void 0&&(process.env.PROGON_SERVER_URL=t.serverUrl);let n=ne(),r=fe(),o=e.PROGON_AGENT_ENROLL_CODE;if(o!==void 0&&o!=="")return Ts(n,r,t.fetchImpl,t.rng);if(Z(n.stateDir)!==null)return process.stdout.write(`${ys}
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
`):process.stdout.write(`${uo(n.serverUrl)}
|
|
24
|
-
|
|
25
|
-
`),
|
|
26
|
-
`),
|
|
27
|
-
`),
|
|
28
|
-
`),
|
|
29
|
-
`)
|
|
30
|
-
`),
|
|
31
|
-
|
|
32
|
-
|
|
24
|
+
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 Fs(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:js(t.stateDir)}),{agentToken:e,agentId:null,pollWaitSec:void 0,source:"env_token"}}o(Fs,"identityFromEnvToken");function js(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(js,"describeStateFile");async function qs(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}),s=await Bs(i,e,t.rng);return ne(n.stateDir,{agentId:s.agentId,agentToken:s.agentToken,protocolVersion:s.protocolVersion,serverUrl:n.serverUrl,tokenRotatedAt:null}),J.info("Agent identity persisted \u2014 PROGON_AGENT_ENROLL_CODE is no longer needed",{agentId:s.agentId,stateDir:n.stateDir}),{agentToken:s.agentToken,agentId:s.agentId,pollWaitSec:s.pollWaitSec,source:"enrollment"}}o(qs,"enrollThisMachine");var Jr=900*1e3;async function Bs(t,e,n){let r=Date.now()+Jr;for(let i=0;;i+=1)try{return await t.enroll(e)}catch(s){if(!(s instanceof S))throw s;let a=he({attempt:i,error:s,rng:n});if(!a.retry)throw J.warn("Enrollment refused definitively \u2014 not retrying",{attempt:i,reason:a.reason,err:s.message}),s;if(Date.now()+a.delayMs>=r)throw new Error(`[progon-agent] Enrollment kept failing for the ${Jr/6e4} minutes an enrollment code stays valid (CONTRACT-la \xA75.1), so this code can no longer be redeemed. Last failure: ${s.message}
|
|
25
|
+
Mint a fresh code in Progon (Settings \u2192 Agents) once the server is reachable, then run 'progon-agent enroll <code>' again.`,{cause:s});J.warn("Enrollment attempt failed \u2014 backing off and retrying",{attempt:i,retryInMs:a.delayMs,err:s.message}),await $s(a.delayMs)}}o(Bs,"enrollWithRetry");function ct(t,e){if(t.source!=="enrollment")throw new Error(`[progon-agent] The enrollment code was not redeemed: this machine already has a credential (source: ${t.source}), which takes precedence.
|
|
26
|
+
To enroll this machine as a SECOND agent \u2014 for another deployment, or as another agent record \u2014 give it its own state directory and run the same 'progon-agent enroll' command again: PROGON_RUNNER_STATE_DIR=<dir> progon-agent enroll ...
|
|
27
|
+
To REPLACE the credential this machine already holds, unset PROGON_AGENT_TOKEN and remove the state file in ${e}, then run the same command again.
|
|
28
|
+
The code itself was not spent and stays valid until it expires.`)}o(ct,"assertEnrollmentCodeWasRedeemed");function Hs(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.
|
|
29
|
+
Either point PROGON_SERVER_URL back at the enrolled server \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 the new one (remove the state file and start once with PROGON_AGENT_ENROLL_CODE=<code>).`)}o(Hs,"assertServerMatchesEnrollment");import{createRequire as Vs}from"node:module";import{hostname as Js}from"node:os";var Kr=["darwin","linux","win32"],Wr=["x64","arm64"];function Ks(t){return Kr.includes(t)}o(Ks,"isSupportedPlatform");function Ws(t){return Wr.includes(t)}o(Ws,"isSupportedArch");function Ys(){let e=Vs(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(Ys,"readAgentVersion");function fe(){let t=process.platform;if(!Ks(t))throw new Error(`[supervisor] Unsupported platform ${JSON.stringify(t)}. The local agent runs on ${Kr.join(", ")} (CONTRACT-la \xA75.1, \xA710.3).`);let e=process.arch;if(!Ws(e))throw new Error(`[supervisor] Unsupported CPU architecture ${JSON.stringify(e)}. The local agent runs on ${Wr.join(", ")} (CONTRACT-la \xA75.1).`);let n=Js();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:Ys()}}o(fe,"describeAgentMachine");var Yr=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(Yr,Yr),n}};var Xr=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&&Xr.warn("Abandoned work settled successfully after its deadline had passed",{operation:t.operation,timeoutMs:t.timeoutMs})},s=>{n&&Xr.warn("Abandoned work rejected after its deadline had passed",{operation:t.operation,timeoutMs:t.timeoutMs,err:s instanceof Error?s.message:String(s)})});let r,i=new Promise((s,a)=>{r=setTimeout(()=>{n=!0,a(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 eo(t){let e=await zs(t);return e.kind!=="claimed"?e:Qs(t,e.payload)}o(eo,"claimAndLaunch");async function zs(t){try{let e=await t.client.claimRun(t.runId);return F.info("Run claimed",Zs(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 se||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(zs,"claimRun");function Zs(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(Zs,"describeClaim");async function Qs(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",...ta(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(Qs,"launchClaimedRun");var Zr=500,Qr="\u2026";function ea(t){return t.length<=Zr?t:t.slice(0,Zr-Qr.length)+Qr}o(ea,"fitFailMessageToWire");function ta(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:ea(`stage ${e.stage}: ${Dr(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(ta,"describeLaunchFailure");var we=u("run-monitor");function na(t,e){let n=Date.now();return e.ok?e.tabs.some(i=>i.playback!==null&&i.playback.runId===t)?{healthy:!0}:ra(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 (${oa(e.tabs)}; ${ia(e.agentJob,n)})`}:{healthy:!1,reason:e.reason,detail:e.detail}}o(na,"judgeProbe");function ra(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(ra,"isJobPulseStanding");function oa(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(oa,"describeTabs");function ia(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(ia,"describeJobMarker");var ft=class{static{o(this,"RunMonitor")}#e;#t;#n=null;#r=null;#s=0;#a=!1;constructor(e){this.#e=e;let n=Date.parse(e.deadlineAt);if(Number.isNaN(n))throw new Error(`[run-monitor] run ${e.runId} has an unparseable deadlineAt ${JSON.stringify(e.deadlineAt)} \u2014 the run deadline (CONTRACT-la \xA715 A7) cannot be armed.`);this.#t=n}get runId(){return this.#e.runId}start(){let e=Math.max(0,this.#t-Date.now());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.#a||(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.#a=!0,this.#n!==null&&(clearInterval(this.#n),this.#n=null),this.#r!==null&&(clearTimeout(this.#r),this.#r=null)}async#o(){if(this.#a)return;let e=na(this.#e.runId,await this.#i());if(this.#a)return;if(e.healthy){this.#s>0&&we.info("Liveness probe recovered",{runId:this.#e.runId,clearedStrikes:this.#s}),this.#s=0;return}this.#s+=1;let n=`${e.reason}: ${e.detail}`;we.warn("Liveness probe failed",{runId:this.#e.runId,strike:this.#s,strikeLimit:ye,reason:e.reason,detail:e.detail}),!(this.#s<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 sa(t){let e=o(()=>{},"markSettled"),n=new Promise(r=>{e=r});return{runId:t,cancelledBy:null,settled:n,markSettled:e}}o(sa,"createPendingLaunch");var yt=class{static{o(this,"InstanceReconciler")}#e;#t;#n;#r;#s=new Set;#a=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.#s=new Set(e.outcomes.map(n=>n.runId)),D.info("Startup sweep finished",{instancesRoot:e.instancesRoot,leftoverCount:e.outcomes.length,sweptRunIds:[...this.#s]})}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.#a?.stop(),this.#a=null}#u(e){let n=sa(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 eo({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.#a=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.#a.start()}async#m(e,n){let r=this.#s.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 to={revoked:"agent_revoked",reenroll_required:"agent_superseded",credential_unusable:"agent_superseded",fatal:"shutdown",stopped:"shutdown"};var A=u("token-rotation"),no=1440*60*1e3,wt=class{static{o(this,"TokenRotationCoordinator")}#e;#t;#n;#r=null;#s=!1;#a=!1;constructor(e){this.#e=e.client,this.#t=e.stateDir,this.#n=e.identitySource}async runCycle(e){let n=this.#r;if(n!==null)return n;let r=this.#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.#s||(this.#s=!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.#a)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.#a=!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(a){if(a instanceof y)throw a;if(a instanceof _)return await this.#c(r);if(a instanceof S)return A.warn("The rotation request produced no usable answer \u2014 probing what the server actually committed",{operation:a.operation,err:a.message}),await this.#p(n);throw a}this.#d({...e,agentToken:i,tokenRotatedAt:null},"rotated agent token"),this.#e.useAgentToken(i);let s=await this.#h();return s.kind==="reenroll_required"?s:(s.kind==="observed"&&this.#d({...e,agentToken:i,tokenRotatedAt:s.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.#a=!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.#a=!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;#s;#a;#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.#s=e.stateDir,this.#a=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=to[e],i=await this.#n.cancelLaunchAndSettle(r);await this.#r.run(async()=>{this.#n.stopMonitor();let s=this.#n.activeRunId;s!==null&&await this.#n.dispose(s,r),await n({activeRunId:s,launchingRunId:i})}),await this.#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()})},no);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.#a,signal:e.signal})}finally{this.#o=null}}async#E(){await this.#d.settle(),Fn(this.#s)}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 ro=u("supervisor-boot");async function oo(){let t=re();ro.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});ro.info("Agent identity resolved",{source:n.source,agentId:n.agentId,hostname:e.hostname,platform:e.platform,arch:e.arch,agentVersion:e.agentVersion});let r=tr({overridePath:t.extensionDistOverride,stateDir:t.stateDir,agentId:n.agentId});await Ge({stdio:"pipe"});let i=new Ye({serverUrl:t.serverUrl,agentToken:n.agentToken}),s=new wt({client:i,stateDir:t.stateDir,identitySource:n.source});return new Et({client:i,stateDir:t.stateDir,pollWaitSec:n.pollWaitSec,tokenRotation:s,createRuntime:o(a=>new dt({stateDir:t.stateDir,extensionDist:r,headfulOverride:t.headfulOverride,allowInsecureHttps:t.allowInsecureHttps,onInstanceLost:a}),"createRuntime")})}o(oo,"bootRunSupervisor");import{createHash as ga,randomBytes as fa}from"node:crypto";import{z as T}from"zod";var io=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()}),aa=T.object({companyName:T.string(),approvedByEmail:T.string(),approvedAt:T.string()}),ao=T.object({credential:De,approval:aa});var lo=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:ir}),r=P("enrollment_request_create",io.safeParse(n));return lo.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",ao.safeParse(n));return lo.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:ar})}};import{spawn as la}from"node:child_process";var Pe=u("browser-open");function _t(t){return t!==void 0&&t!==""}o(_t,"isSet");function da(t,e){return!(_t(t.SSH_CONNECTION)||_t(t.SSH_TTY)||e==="linux"&&!_t(t.DISPLAY)&&!_t(t.WAYLAND_DISPLAY))}o(da,"shouldAttemptBrowserOpen");var ca=/[&|^<>"'` ]/;function ua(t){let e;try{e=new URL(t)}catch{return!1}return e.protocol!=="http:"&&e.protocol!=="https:"||t!==e.href?!1:!ca.test(t)}o(ua,"isSpawnSafeUrl");function ma(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(ma,"browserOpenCommand");function co(t,e,n){if(!da(e,n)){Pe.debug("Not opening a browser: this host has no desktop to open one on",{platform:n});return}if(!ua(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=ma(t,n);if(r===null){Pe.debug("Not opening a browser: no opener is defined for this platform",{platform:n});return}try{let i=la(r.command,[...r.args],{detached:!0,stdio:"ignore"});i.on("error",s=>{Pe.debug("Could not start the browser; the approval URL was printed instead",{platform:n,command:r.command,err:s.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(co,"openVerificationUrl");var pa=30,ha=5;function uo(t){return{intervalSec:t.pollIntervalSec,deadlineMs:t.timeoutSec===null?t.expiresAtMs:Math.min(t.expiresAtMs,t.nowMs+t.timeoutSec*1e3)}}o(uo,"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+ha,i=e.retryAfterSec!==null&&e.retryAfterSec>r?e.retryAfterSec:r,s=Math.min(i,pa);return{state:{intervalSec:s,deadlineMs:t.deadlineMs},delayMs:s*1e3}}let n=pe(e.attempt,e.rng);return{state:t,delayMs:Math.max(t.intervalSec*1e3,n)}}o(St,"nextPollDelayMs");function mo(t,e){return e>=t.deadlineMs}o(mo,"isDeadlinePassed");function po(t,e,n){return Math.max(0,Math.min(e,t.deadlineMs-n))}o(po,"clampDelayToDeadline");var ve=u("device-enrollment"),ya=24,wa=2e3,Xt=0,Ee=1,go=130,Ea="This machine is already enrolled. Start the daemon with: progon-agent start",va="Enrollment was denied in the browser. Nothing was created on this machine.",_a="Cancelled. Nothing was saved on this machine.",Sa="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 ho(t){return`Enrollment request expired. Run: progon-agent enroll --server ${t}`}o(ho,"expiredLine");function Ra(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}.
|
|
30
|
+
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}
|
|
31
|
+
To move this machine to ${e} instead, remove the state file in ${n} first, then run: progon-agent enroll --server ${e}`}o(Ra,"otherDeploymentLine");function ba(t,e){return`Timed out after ${t}s waiting for approval. The request is still open \u2014 approve at: ${e}`}o(ba,"timedOutLine");function ka(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(ka,"alreadyCompletedLine");function Ta(t){return`Enrollment request is no longer valid. Run: progon-agent enroll --server ${t}`}o(Ta,"noLongerValidLine");async function fo(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 xa(n,r,t.fetchImpl,t.rng);let s=G(n.stateDir);if(s!==null)return je(s.serverUrl,n.serverUrl)?(process.stdout.write(`${Ea}
|
|
32
|
+
`),Xt):(process.stdout.write(`${Ra(s.serverUrl,n.serverUrl,n.stateDir)}
|
|
33
|
+
`),Ee);let a=fa(ya).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(Na(a));return Oa(d),t.openBrowser&&co(d.verificationUrl,e,process.platform),Aa({client:l,config:n,created:d,deviceSecret:a,timeoutSec:t.timeoutSec,rng:t.rng})}o(fo,"runDeviceEnrollment");async function Aa(t){let{client:e,config:n,created:r,deviceSecret:i,timeoutSec:s,rng:a}=t,l=Date.parse(r.expiresAt),d=uo({pollIntervalSec:r.pollIntervalSec,expiresAtMs:l,timeoutSec:s,nowMs:Date.now()}),m=d.intervalSec*1e3,f=0,h={signal:null},p=new AbortController,b=o(R=>{h.signal!==null&&(process.stderr.write(`${Sa}
|
|
34
|
+
`),process.exit(go)),h.signal=R,p.abort()},"onSignal");process.on("SIGINT",b),process.on("SIGTERM",b);try{for(;;){if(await pt(po(d,m,Date.now()),p.signal),h.signal!==null)return await Ia(e,i,h.signal);if(mo(d,Date.now()))return s!==null&&d.deadlineMs<l?process.stdout.write(`${ba(s,r.verificationUrl)}
|
|
35
|
+
`):process.stdout.write(`${ho(n.serverUrl)}
|
|
36
|
+
`),Ee;let R;try{R=await e.poll(i)}catch(k){if(k instanceof le)return process.stdout.write(`${va}
|
|
37
|
+
`),Ee;if(k instanceof de)return process.stdout.write(`${ho(n.serverUrl)}
|
|
38
|
+
`),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(`${ka(n.serverUrl)}
|
|
39
|
+
`),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(`${Ta(n.serverUrl)}
|
|
40
|
+
`),Ee;if(k instanceof ae){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:a});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
|
|
41
|
+
`),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(Aa,"waitForApproval");async function Ia(t,e,n){try{await mt({operation:"device enrollment cancel",timeoutMs:wa,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(`${_a}
|
|
42
|
+
`),go}o(Ia,"cancelRequest");async function xa(t,e,n,r){let i=await ge({config:t,machine:e,fetchImpl:n,rng:r});return ct(i,t.stateDir),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(xa,"redeemLegacyEnrollmentCode");function Oa(t){process.stdout.write(`Enrollment requested for this machine.
|
|
33
43
|
Confirmation code: ${t.userCode}
|
|
34
44
|
Approve at: ${t.verificationUrl}
|
|
35
|
-
Waiting for approval (expires in ${
|
|
36
|
-
`)}
|
|
45
|
+
Waiting for approval (expires in ${Pa(t.expiresAt)})...
|
|
46
|
+
`)}o(Oa,"printRequestOpened");function Pa(t){let e=Date.parse(t)-Date.now();return`${Math.ceil(e/6e4)}m`}o(Pa,"describeExpiry");function Na(t){return ga("sha256").update(t,"utf8").digest("hex")}o(Na,"sha256Hex");var Rt=u("cli"),yo=`progon-agent \u2014 the Progon local agent (CONTRACT-la \xA78)
|
|
37
47
|
|
|
38
48
|
Usage:
|
|
39
49
|
progon-agent enroll <code> [--server <url>] Redeem a one-shot enrollment code (\xA75.1) and
|
|
@@ -61,14 +71,29 @@ Which credential 'enroll' uses, highest precedence first:
|
|
|
61
71
|
2. PROGON_AGENT_ENROLL_CODE -> the same path, with the code from the environment.
|
|
62
72
|
3. neither -> browser approval (the device flow above).
|
|
63
73
|
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
74
|
+
Which server the commands talk to, highest precedence first:
|
|
75
|
+
1. --server <url> -> sets PROGON_SERVER_URL for this command.
|
|
76
|
+
2. PROGON_SERVER_URL -> from the environment.
|
|
77
|
+
3. the enrolled deployment -> the server this machine's state file records. This is why
|
|
78
|
+
'start' needs no environment after 'enroll': the URL was
|
|
79
|
+
persisted with the credential. It is NOT read when
|
|
80
|
+
PROGON_AGENT_TOKEN is set (that token names no deployment,
|
|
81
|
+
and it is also the path for recovering from a broken state
|
|
82
|
+
file), so there the variable is required.
|
|
83
|
+
When PROGON_SERVER_URL IS set it must still match the enrollment \u2014 a pgat_ token is
|
|
84
|
+
meaningless at another deployment, and 'start' refuses rather than authenticate blind.
|
|
85
|
+
|
|
86
|
+
Exit codes: 0 enrolled, or already enrolled against this same server; 1 the enrollment did not
|
|
87
|
+
happen \u2014 denied, expired, --timeout exhausted, already completed from another machine, no longer
|
|
88
|
+
valid, this machine is already enrolled against a DIFFERENT server, or the network was still
|
|
89
|
+
failing when the deadline passed; 2 the command line was wrong; 130 interrupted
|
|
67
90
|
with Ctrl-C \u2014 the first Ctrl-C withdraws the pending request before exiting, a second one
|
|
68
91
|
exits at once and leaves the request to expire on its own.
|
|
69
92
|
|
|
70
93
|
Environment (see CONTRACT-la \xA78 for the full list):
|
|
71
|
-
PROGON_SERVER_URL
|
|
94
|
+
PROGON_SERVER_URL base URL of the Progon backend. Required until this machine is
|
|
95
|
+
enrolled, and required alongside PROGON_AGENT_TOKEN; otherwise
|
|
96
|
+
see the server precedence above.
|
|
72
97
|
PROGON_AGENT_EXTENSION_DIST optional \u2014 absolute path of an already agent-mode qa-extension
|
|
73
98
|
dist, overriding the one bundled in this package (dev/E2E).
|
|
74
99
|
Required by 'start' ONLY on the PROGON_AGENT_TOKEN path: that
|
|
@@ -77,11 +102,9 @@ Environment (see CONTRACT-la \xA78 for the full list):
|
|
|
77
102
|
name one (\xA71 D-C, \xA715 A30.1).
|
|
78
103
|
PROGON_AGENT_TOKEN optional \u2014 an existing credential, takes precedence over the
|
|
79
104
|
state file and over enrollment.
|
|
80
|
-
PROGON_AGENT_HEADFUL optional \u2014 show the browser on this machine's desktop.`;function
|
|
105
|
+
PROGON_AGENT_HEADFUL optional \u2014 show the browser on this machine's desktop.`;function La(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"?Ma(n):{kind:"usage",reason:`unknown command '${e}'`}}o(La,"parseCliArgs");function Ga(t){return t.startsWith("-")&&t.length<32}o(Ga,"isOptionInCodeSlot");function Ma(t){let[e,...n]=t;if(e===void 0||Ga(e))return Ua(t);if(n.length===0)return{kind:"enroll",code:e,serverUrl:void 0};let[r,i,...s]=n;return r!=="--server"?{kind:"usage",reason:`unknown option '${String(r)}' for 'enroll'`}:i===void 0?{kind:"usage",reason:"'--server' needs a URL"}:s.length>0?{kind:"usage",reason:"unexpected arguments after '--server'"}:{kind:"enroll",code:e,serverUrl:i}}o(Ma,"parseEnroll");var wo=1,Eo=3600;function Ua(t){let e,n=!0,r=null;for(let i=0;i<t.length;i+=1){let s=t[i];if(s==="--no-open"){n=!1;continue}if(s==="--server"){let a=t[i+1];if(a===void 0)return{kind:"usage",reason:"'--server' needs a URL"};e=a,i+=1;continue}if(s==="--timeout"){let a=t[i+1];if(a===void 0)return{kind:"usage",reason:"'--timeout' needs a number of seconds"};if(!/^[0-9]+$/.test(a))return{kind:"usage",reason:`'--timeout' takes a whole number of seconds, got '${a}'`};let l=Number(a);if(l<wo||l>Eo)return{kind:"usage",reason:`'--timeout' must be between ${wo} and ${Eo} seconds, got '${a}'`};r=l,i+=1;continue}return{kind:"usage",reason:`unknown option '${String(s)}' for 'enroll'`}}return{kind:"enroll-device",serverUrl:e,openBrowser:n,timeoutSec:r}}o(Ua,"parseEnrollDevice");async function $a(t){let e=La(t);switch(e.kind){case"usage":return e.reason===null?(process.stdout.write(`${yo}
|
|
81
106
|
`),0):(process.stderr.write(`progon-agent: ${e.reason}
|
|
82
107
|
|
|
83
|
-
${
|
|
84
|
-
`),2);case"enroll":return
|
|
85
|
-
|
|
86
|
-
The code itself was not spent and stays valid until it expires.`);return Et.info("This machine is enrolled \u2014 start the daemon with: progon-agent start",{agentId:o.agentId,hostname:r.hostname,stateDir:n.stateDir}),0}i($s,"enrollThisMachine");async function Us(){Dn(),Et.info("progon-agent starting");let t=await to();return Ln(async n=>{await t.shutdown(n)}),await t.run()==="revoked"?(Et.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):(Et.info("progon-agent stopped"),0)}i(Us,"startDaemon");var yo=process.argv[1];yo!==void 0&&import.meta.url===Ps(Os(yo)).href&&Gs(process.argv.slice(2)).then(t=>{process.exit(t)}).catch(t=>{let e=L(t instanceof Error?t.message:String(t)),n=t instanceof Error?t.stack:void 0;process.stderr.write(JSON.stringify({level:"fatal",module:"cli",msg:"progon-agent failed",err:e,stack:n===void 0?void 0:L(n)})+`
|
|
87
|
-
`),process.exit(1)});export{Ns as parseCliArgs,Gs as runAgentCli};
|
|
108
|
+
${yo}
|
|
109
|
+
`),2);case"enroll":return ja(e.code,e.serverUrl);case"enroll-device":return fo({serverUrl:e.serverUrl,openBrowser:e.openBrowser,timeoutSec:e.timeoutSec});case"install-browser":return Fa();case"start":return qa()}}o($a,"runAgentCli");async function Fa(){return await Ge({stdio:"inherit"}),0}o(Fa,"installBrowser");async function ja(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.stateDir),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(ja,"enrollThisMachine");async function qa(){Jn(),Rt.info("progon-agent starting");let t=await oo();return Kn(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(qa,"startDaemon");var vo=process.argv[1];vo!==void 0&&import.meta.url===Da(Ca(vo)).href&&$a(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)})+`
|
|
110
|
+
`),process.exit(1)});export{La as parseCliArgs,$a as runAgentCli};
|
package/extension-bundle.json
CHANGED
package/package.json
CHANGED