ax 0.7.5 → 0.8.0

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/.env.example CHANGED
@@ -3,9 +3,10 @@
3
3
  # ora.ai host and need none of these — `ax audit <url>` works with zero
4
4
  # configuration, and so does `ax webmcp-audit http://localhost:3000`.
5
5
 
6
- # Secret API key (looks like ora_sk_...). Required by `journey`, which exchanges
7
- # it for a short-lived bearer token. `webmcp-audit` sends it as a bearer token to
8
- # lift the anonymous ingest limits (10/min, 20 per 24h per IP); optional there.
6
+ # Secret API key (looks like ora_sk_...). Required by `journey` and by
7
+ # `audit --tunnel ora` (needs the tunnels:write + tunnels:connect scopes), which
8
+ # exchange it for a short-lived bearer token. `webmcp-audit` sends it as a bearer
9
+ # token to lift the anonymous ingest limits (10/min, 20 per 24h per IP); optional there.
9
10
  ORA_API_KEY=
10
11
 
11
12
  # Platform API base. Defaults to staging if unset.
@@ -16,8 +17,13 @@ ORA_PLATFORM_URL=https://api.agentfront.sh
16
17
  # one (e.g. http://localhost:3000).
17
18
  # ORA_API_URL=https://ora.ai
18
19
 
19
- # Tunnel command for auditing a local target (same as --tunnel-cmd):
20
- # a command that exposes the local server and prints its public https URL.
20
+ # Auditing a local target. `ora` opens ora's own tunnel (same as --tunnel ora;
21
+ # needs ORA_API_KEY above) - the tunnel is created, audited, and deleted.
22
+ # ORA_TUNNEL=ora
23
+
24
+ # ...or bring your own tunnel (same as --tunnel-cmd): a command that exposes the
25
+ # local server and prints its public https URL. Wins over ORA_TUNNEL when both are set.
26
+ # ORA_TUNNEL_CMD='ora tunnel 3000 --access public'
21
27
  # ORA_TUNNEL_CMD='ngrok http 3000 --log stdout'
22
28
 
23
29
  # ora-issued scan API key for `ax audit` (same as --api-key): exempts the
package/README.md CHANGED
@@ -35,7 +35,7 @@ Five commands:
35
35
  ## audit
36
36
 
37
37
  ```
38
- ax audit <url> [--min-score n] [--max-age s] [--force] [--tunnel-cmd c] [--api-key k] [--json] [--show-passing] [--show-skipped]
38
+ ax audit <url> [--min-score n] [--max-age s] [--force] [--tunnel ora] [--tunnel-cmd c] [--api-key k] [--json] [--show-passing] [--show-skipped]
39
39
  ```
40
40
 
41
41
  ```
@@ -65,7 +65,8 @@ ax audit <url> [--min-score n] [--max-age s] [--force] [--tunnel-cmd c] [--api-k
65
65
  | `--min-score <n>` | Exit `1` when the score is below `n` (0-100) — the CI gate |
66
66
  | `--max-age <s>` | Accept a cached result up to `s` seconds old (server default 6h, clamped to 1-24h) |
67
67
  | `--force` | Bypass the cache and rescan — spends the stricter 6/day force budget |
68
- | `--tunnel-cmd <c>` | Expose a local target through your own tunnel command and audit the public URL it prints (also read from `ORA_TUNNEL_CMD`) |
68
+ | `--tunnel ora` | Expose a local target through ora's own tunnel and audit it — needs `ORA_API_KEY` with the `tunnels:write` + `tunnels:connect` scopes (also read from `ORA_TUNNEL`) |
69
+ | `--tunnel-cmd <c>` | Bring your own tunnel: a command that exposes the local target and prints its public `https://` URL (also read from `ORA_TUNNEL_CMD`) |
69
70
  | `--api-key <k>` | ora-issued scan API key — lifts every scan rate limit (also read from `ORA_SCAN_API_KEY`) |
70
71
  | `--json` | The raw ora audit payload on stdout, exactly as the API served it |
71
72
  | `--show-passing` | List every passing check, not just the per-layer summary bar |
@@ -91,16 +92,27 @@ Exit codes are the contract:
91
92
 
92
93
  Budget notes: ora allows 30 scans + 6 `--force` scans per rolling 24h per IP (plus a 10/min burst limit). Results served from the freshness cache cost nothing, so a CI job that audits on every push stays well inside the budget — tune the window with `--max-age`, and reserve `--force` for verifying a fix you just deployed. High-volume callers can present an ora-issued scan API key (`--api-key` or `ORA_SCAN_API_KEY`), which exempts them from all of these limits; keys are issued manually by ora (no self-serve signup), and an unrecognized key silently falls back to the keyless limits rather than erroring. An auth-gated MCP target reports `mcpAuthRequired` and scores 0 as "could not evaluate"; `--min-score` deliberately skips the gate rather than failing on it.
93
94
 
94
- ### Auditing localhost (`--tunnel-cmd`)
95
+ ### Auditing localhost (`--tunnel ora`, `--tunnel-cmd`)
95
96
 
96
- A local dev server only exists on your machine, so ora can't reach it. The simplest option is to audit a publicly reachable deployment of the same code (e.g. a preview URL). To audit localhost itself, bring your own tunnel: pass `--tunnel-cmd` (or set `ORA_TUNNEL_CMD`) with a command that exposes the local server and prints its public `https://` URL. The CLI runs it, audits the URL it prints, and tears the tunnel down when done.
97
+ A local dev server only exists on your machine, so ora can't reach it. The simplest option is to audit a publicly reachable deployment of the same code (e.g. a preview URL). To audit localhost itself, run it through a tunnel. The result is stored as **ephemeral** either way: excluded from ora's rankings and leaderboard, served with `Cache-Control: no-store`, never indexed, and deleted after 7 days.
98
+
99
+ **ora's own tunnel.** With an ora platform key (`ora_sk_…`, scopes `tunnels:write` + `tunnels:connect`) in `ORA_API_KEY`, `ax` creates a tunnel, connects it, audits the public hostname, and deletes the tunnel when done — nothing to install, nothing left behind:
100
+
101
+ ```
102
+ ax audit localhost:3000 --tunnel ora
103
+ ```
104
+
105
+ The hostname is an unguessable UUID under `*.t.agentfront.sh` that stops answering the moment the audit finishes (or you press Ctrl-C). Today the tunnel is opened in `public` mode, because ora's scanner cannot yet present a per-tunnel credential; a `protected` mode the scanner can use is on the roadmap.
106
+
107
+ **Bring your own tunnel.** Pass `--tunnel-cmd` (or set `ORA_TUNNEL_CMD`) with any command that exposes the local server and prints its public `https://` URL. The CLI runs it, audits the URL it prints, and tears the tunnel down when done:
97
108
 
98
109
  ```
110
+ ax audit localhost:3000 --tunnel-cmd 'ora tunnel 3000 --access public' # ora's tunnel CLI (npm i -g @ora-ai/cli; ora login)
99
111
  ax audit localhost:3000 --tunnel-cmd 'ngrok http 3000 --log stdout'
100
112
  ```
101
113
 
102
- - **The CLI ships no tunnel vendor and never downloads executables at runtime** — any tunnel tool you already have works, as long as it prints its public URL to stdout or stderr.
103
- - The result is stored as **ephemeral**: excluded from ora's rankings and deleted after a few days.
114
+ - **The CLI ships no tunnel vendor and never downloads executables at runtime** — ora's own tunnel is first-party protocol code over Node's built-in WebSocket; any other tunnel tool you already have works through `--tunnel-cmd`, as long as it prints its public URL to stdout or stderr.
115
+ - With `ora tunnel`, `--access public` is required today: `protected` prints a tokenized link the scanner cannot use.
104
116
  - Off-site checks (registry listings, brand search) usually fail for a throwaway tunnel hostname — the report says so. Use tunnel audits to iterate on your on-site surface, not to compare scores.
105
117
  - Free tiers of some tunnel vendors serve an interstitial warning page to browser-like requests, which can distort what the scanner sees — prefer a vendor/plan that serves your origin directly.
106
118
 
@@ -351,10 +363,11 @@ A `.env` in the working directory is read on startup — copy `.env.example` and
351
363
  | Var | Used by | Default | Purpose |
352
364
  |---|---|---|---|
353
365
  | `ORA_API_URL` | audit, deep-journey, skill | `https://ora.ai` | Public API base (no auth) |
354
- | `ORA_PLATFORM_URL` | journey | `https://api.agentfront.sh` | Authenticated platform API base |
355
- | `ORA_TUNNEL_CMD` | audit | — (optional) | Tunnel command for a local target (same as `--tunnel-cmd`) |
366
+ | `ORA_PLATFORM_URL` | journey, audit `--tunnel ora` | `https://api.agentfront.sh` | Authenticated platform API base |
367
+ | `ORA_TUNNEL` | audit | — (optional) | `ora` opens ora's own tunnel for a local target (same as `--tunnel ora`) |
368
+ | `ORA_TUNNEL_CMD` | audit | — (optional) | Tunnel command for a local target (same as `--tunnel-cmd`); wins over `ORA_TUNNEL` |
356
369
  | `ORA_API_URL` | webmcp-audit | `https://ora.ai` | Also the ingest base for `webmcp-audit` |
357
- | `ORA_API_KEY` | journey, webmcp-audit | — (required for journey) | Secret key (`ora_sk_…`); journey exchanges it for a bearer token, webmcp-audit sends it to lift the ingest rate limits |
370
+ | `ORA_API_KEY` | journey, audit `--tunnel ora`, webmcp-audit | — (required for journey and `--tunnel ora`) | Secret key (`ora_sk_…`); journey and `--tunnel ora` exchange it for a bearer token (the tunnel needs the `tunnels:write` + `tunnels:connect` scopes), webmcp-audit sends it to lift the ingest rate limits |
358
371
  | `ORA_SCAN_API_KEY` | audit, deep-journey | — (optional) | ora-issued scan API key; lifts every scan rate limit (issued manually by ora). deep-journey accepts it as a partner-key fallback |
359
372
  | `ORA_PARTNER_API_KEY` | deep-journey | — (optional) | ora-issued partner API key; unlocks `--task` and the 1000/24h keyed allowance |
360
373
 
@@ -1,3 +1,5 @@
1
+ /** The platform API base: explicit override, else $ORA_PLATFORM_URL, else prod. */
2
+ export declare function platformBase(override?: string): string;
1
3
  export interface RunSummary {
2
4
  run_id: string;
3
5
  domain?: string;
@@ -132,6 +134,7 @@ export interface JourneyRun {
132
134
  /** The last trajectory snapshot seen — the definitive step list. */
133
135
  trajectory: JourneyStep[];
134
136
  }
137
+ export declare function exchangeKey(base: string, secret: string): Promise<string>;
135
138
  export declare function decodeEventBlock(block: string): {
136
139
  event: string;
137
140
  data: string;
@@ -424,7 +424,7 @@ export interface components {
424
424
  * @description The contract version this payload conforms to. SemVer: a major means a response-envelope break - a stable field removed, renamed, or changed in meaning, or the default response format flipping - and is safe to pin. Additive changes and check-catalog membership changes ship on a minor. See docs/api.md -> Contract and versioning.
425
425
  * @enum {string}
426
426
  */
427
- contractVersion: "1.24.0";
427
+ contractVersion: "1.25.0";
428
428
  /**
429
429
  * @description Present only when this body is a stored result served by the freshness gate instead of a fresh scan. Absent on a live scan.
430
430
  * @enum {boolean}
@@ -433,7 +433,7 @@ export interface components {
433
433
  /** @description Age of the served stored result in seconds (also sent as the Age response header). Present with servedFromCache. */
434
434
  resultAgeSeconds?: number;
435
435
  /**
436
- * @description Present when an MCP-family scan short-circuited because the server's handshake demanded credentials (401/403). Score 0 with empty layers then means 'could not evaluate', NOT 'failed everything' - treat the target as unscored rather than failing a gate on it.
436
+ * @description Legacy marker retained for compatibility with stored results. New authentication-required scans return an MCP_AUTH_REQUIRED error without score or grade; public reads of a historical marked result return the same error.
437
437
  * @enum {boolean}
438
438
  */
439
439
  mcpAuthRequired?: true;
@@ -623,11 +623,11 @@ export interface components {
623
623
  * @description The contract version this payload conforms to. SemVer: a major means a response-envelope break - a stable field removed, renamed, or changed in meaning, or the default response format flipping - and is safe to pin. Additive changes and check-catalog membership changes ship on a minor. See docs/api.md -> Contract and versioning.
624
624
  * @enum {string}
625
625
  */
626
- contractVersion: "1.24.0";
626
+ contractVersion: "1.25.0";
627
627
  /** @description Wall-clock duration of the scan that produced this stored result */
628
628
  durationMs: number | null;
629
629
  /**
630
- * @description Present when an MCP-family scan short-circuited because the server's handshake demanded credentials (401/403). Score 0 with empty layers then means 'could not evaluate', NOT 'failed everything' - treat the target as unscored rather than failing a gate on it.
630
+ * @description Legacy marker retained for compatibility with stored results. New authentication-required scans return an MCP_AUTH_REQUIRED error without score or grade; public reads of a historical marked result return the same error.
631
631
  * @enum {boolean}
632
632
  */
633
633
  mcpAuthRequired?: true;
@@ -667,7 +667,7 @@ export interface components {
667
667
  * @description The contract version this catalog conforms to - identical to the OpenAPI info.version and the MCP server version. SemVer: a major means a response-envelope break (a stable field, or a layer id, removed or renamed or changed in meaning, or the default response format flipping) and is safe to pin; check-catalog membership changes ship on a minor. The full versioning policy is published in the API description at /api/openapi.json.
668
668
  * @enum {string}
669
669
  */
670
- contractVersion: "1.24.0";
670
+ contractVersion: "1.25.0";
671
671
  /** @description The four scored layers in scoring order, with display name and current weight. */
672
672
  layers: {
673
673
  /** @description Stable layer id: discovery, accessibility, usability, or payments. Removing or renaming a layer id is a major version change. Note one intentional divergence: the id 'accessibility' carries the display name 'Access'. */
@@ -757,7 +757,7 @@ export interface components {
757
757
  url: string;
758
758
  /** @description Array of check ids from GET /api/checks - one id minimum, up to the catalogued check count. Duplicate ids are deduplicated; ids the catalog does not list are rejected with error code UNKNOWN_CHECK_IDS. */
759
759
  checkIds: string[];
760
- /** @description Optional URL of the target's MCP server, matching the same field on POST /api/scan. When omitted, ora auto-discovers MCP endpoints. An empty string is treated as absent. */
760
+ /** @description Optional URL of the target's MCP server, matching the same field on POST /api/scan. It pins the MCP endpoint; a failed handshake never substitutes a discovered server. When omitted, ora auto-discovers MCP endpoints. An empty string is treated as absent. */
761
761
  mcpUrl?: unknown;
762
762
  };
763
763
  /** @description The outcome of a selective check run. The run always executes - results are never served from a cache. The response carries no aggregate score of any kind: per-check score and maxScore only, with GET /api/score/{domain} as the score surface. Results carry no tier or layer fields - join with GET /api/checks by id to group or rank them. */
@@ -766,7 +766,7 @@ export interface components {
766
766
  * @description The contract version this response conforms to - identical to the OpenAPI info.version and the MCP server version. The full versioning policy is published in the API description at /api/openapi.json.
767
767
  * @enum {string}
768
768
  */
769
- contractVersion: "1.24.0";
769
+ contractVersion: "1.25.0";
770
770
  /** @description The apex domain derived from the requested URL. */
771
771
  domain: string;
772
772
  /** @description The normalized URL the run targeted. */
@@ -1983,7 +1983,7 @@ export interface components {
1983
1983
  * @enum {string}
1984
1984
  */
1985
1985
  urlKind?: "domain" | "mcp" | "mcp-app" | "ephemeral";
1986
- /** @description Optional. True when an MCP-family scan (urlKind 'mcp' or 'mcp-app') was short-circuited because the server returned 401/403 on the handshake. When set, 'layers' is empty and 'score' is 0; ora cannot evaluate agent-readiness for auth-gated MCP servers. UI surfaces an auth-required notice instead of the score hero. */
1986
+ /** @description Legacy marker retained for compatibility. New authentication-required scans and reads of historical marked results return HTTP 422 MCP_AUTH_REQUIRED without score or grade. */
1987
1987
  mcpAuthRequired?: boolean;
1988
1988
  /**
1989
1989
  * @description Present (and always true) only when POST /api/scan answered from the freshness window with a stored result instead of running a scan. Absent on a live scan and on GET /api/score/{domain}, which is always a cached read.
@@ -2161,6 +2161,18 @@ export interface components {
2161
2161
  /** @description Optional recovery hint (e.g. /api/scan on NOT_FOUND). */
2162
2162
  next?: string;
2163
2163
  };
2164
+ McpAuthRequiredResponse: {
2165
+ /** @description Why the MCP server could not be inspected. */
2166
+ error: string;
2167
+ /** @constant */
2168
+ code: "MCP_AUTH_REQUIRED";
2169
+ /** @constant */
2170
+ mcpAuthRequired: true;
2171
+ /** @description The MCP endpoint that required authentication. */
2172
+ mcpUrl: string;
2173
+ /** @enum {string} */
2174
+ urlKind: "mcp" | "mcp-app";
2175
+ };
2164
2176
  /**
2165
2177
  * @description ora's house error envelope. `error` is always present; the other fields depend on which guard rejected the request, so a client should branch on `code` / `retry_after_ms` being present rather than assume them.
2166
2178
  * @example {
@@ -2284,7 +2296,7 @@ export interface operations {
2284
2296
  */
2285
2297
  url: string;
2286
2298
  /**
2287
- * @description Optional MCP server URL to test
2299
+ * @description Optional MCP server URL to inspect as the sole MCP target. A failed endpoint is never replaced by a discovered server
2288
2300
  * @example
2289
2301
  */
2290
2302
  mcpUrl?: string;
@@ -2335,6 +2347,12 @@ export interface operations {
2335
2347
  "application/json": components["schemas"]["ErrorResponse"];
2336
2348
  };
2337
2349
  };
2350
+ /** @description MCP authentication is required. No score or grade was produced. The failed attempt does not overwrite a previous measured scan. */
2351
+ 422: {
2352
+ content: {
2353
+ "application/json": components["schemas"]["McpAuthRequiredResponse"];
2354
+ };
2355
+ };
2338
2356
  /** @description Rate limit exceeded - either the 10-per-minute burst cap or the durable daily quota (30 scans per rolling 24h per IP; 6 per day for force=true). Cache-served responses never count against the daily quota. The response includes a Retry-After header indicating seconds until the next request is allowed, and a JSON body with error and retry_after_ms. */
2339
2357
  429: {
2340
2358
  headers: {
@@ -2444,7 +2462,7 @@ export interface operations {
2444
2462
  query: {
2445
2463
  /** @description The domain, MCP server URL, or MCP app URL to scan. The server detects which kind of input was provided and runs the appropriate check set. */
2446
2464
  domain: string;
2447
- /** @description Optional explicit MCP server URL to test alongside the scan */
2465
+ /** @description Optional MCP server URL to inspect as the sole MCP target; it is never replaced by a discovered server */
2448
2466
  mcp?: string;
2449
2467
  /** @description Same freshness window as POST /api/scan: how stale a stored result may be and still be streamed back instead of running a new scan. Defaults to 21600 (6 hours), clamped to [3600, 86400]. */
2450
2468
  maxAgeSeconds?: number;
@@ -2457,7 +2475,7 @@ export interface operations {
2457
2475
  };
2458
2476
  };
2459
2477
  responses: {
2460
- /** @description Server-Sent Events stream of scan progress. With `?format=audit`, the terminal `scan_complete` event's `result` is `#/components/schemas/AuditScanResult`; every other event is unchanged. When a stored result inside the freshness window answers the request, the stream is a `kind_detected` frame followed by a terminal `scan_complete` event carrying `servedFromCache: true` and `resultAgeSeconds`, and the response carries an `Age` header. */
2478
+ /** @description Server-Sent Events stream of scan progress. If MCP authentication is required, the stream ends with an error event carrying code MCP_AUTH_REQUIRED, mcpAuthRequired: true, mcpUrl and urlKind, without scan_complete or a score. With `?format=audit`, the terminal `scan_complete` event's `result` is `#/components/schemas/AuditScanResult`; every other event is unchanged. When a stored result inside the freshness window answers the request, the stream is a `kind_detected` frame followed by a terminal `scan_complete` event carrying `servedFromCache: true` and `resultAgeSeconds`, and the response carries an `Age` header. */
2461
2479
  200: {
2462
2480
  content: {
2463
2481
  "text/event-stream": string;
@@ -2558,6 +2576,12 @@ export interface operations {
2558
2576
  "application/json": components["schemas"]["NotScannedResponse"];
2559
2577
  };
2560
2578
  };
2579
+ /** @description MCP authentication is required. No score or grade was produced. The failed attempt does not overwrite a previous measured scan. */
2580
+ 422: {
2581
+ content: {
2582
+ "application/json": components["schemas"]["McpAuthRequiredResponse"];
2583
+ };
2584
+ };
2561
2585
  /** @description Rate limit exceeded - max 10 requests per minute per IP. The response carries a Retry-After header with the seconds until the oldest request in the window ages out. */
2562
2586
  429: {
2563
2587
  headers: {
@@ -1,2 +1,2 @@
1
1
  /** The ora contract version (spec info.version) these types were generated from. */
2
- export declare const BUILT_AGAINST = "1.24.0";
2
+ export declare const BUILT_AGAINST = "1.25.0";
package/dist/index.cjs CHANGED
@@ -35,7 +35,7 @@ __export(src_exports, {
35
35
  module.exports = __toCommonJS(src_exports);
36
36
 
37
37
  // src/contract/version.ts
38
- var BUILT_AGAINST = "1.24.0";
38
+ var BUILT_AGAINST = "1.25.0";
39
39
 
40
40
  // src/contract/index.ts
41
41
  function minor(version) {
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/contract/version.ts
2
- var BUILT_AGAINST = "1.24.0";
2
+ var BUILT_AGAINST = "1.25.0";
3
3
 
4
4
  // src/contract/index.ts
5
5
  function minor(version) {
package/dist/main.cjs CHANGED
@@ -1,53 +1,56 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Jn=Object.create;var dt=Object.defineProperty;var Fn=Object.getOwnPropertyDescriptor;var Hn=Object.getOwnPropertyNames;var Gn=Object.getPrototypeOf,qn=Object.prototype.hasOwnProperty;var Kn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Vn=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Hn(t))!qn.call(e,o)&&o!==n&&dt(e,o,{get:()=>t[o],enumerable:!(r=Fn(t,o))||r.enumerable});return e};var U=(e,t,n)=>(n=e!=null?Jn(Gn(e)):{},Vn(t||!e||!e.__esModule?dt(n,"default",{value:e,enumerable:!0}):n,e));var D=Kn((ys,Me)=>{"use strict";var ge=process||{},vt=ge.argv||[],me=ge.env||{},ur=!(me.NO_COLOR||vt.includes("--no-color"))&&(!!me.FORCE_COLOR||vt.includes("--color")||ge.platform==="win32"||(ge.stdout||{}).isTTY&&me.TERM!=="dumb"||!!me.CI),dr=(e,t,n=e)=>r=>{let o=""+r,i=o.indexOf(t,e.length);return~i?e+pr(o,t,n,i)+t:e+o+t},pr=(e,t,n,r)=>{let o="",i=0;do o+=e.substring(i,r)+n,i=r+t.length,r=e.indexOf(t,i);while(~r);return o+e.substring(i)},St=(e=ur)=>{let t=e?dr:()=>String;return{isColorSupported:e,reset:t("\x1B[0m","\x1B[0m"),bold:t("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:t("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:t("\x1B[3m","\x1B[23m"),underline:t("\x1B[4m","\x1B[24m"),inverse:t("\x1B[7m","\x1B[27m"),hidden:t("\x1B[8m","\x1B[28m"),strikethrough:t("\x1B[9m","\x1B[29m"),black:t("\x1B[30m","\x1B[39m"),red:t("\x1B[31m","\x1B[39m"),green:t("\x1B[32m","\x1B[39m"),yellow:t("\x1B[33m","\x1B[39m"),blue:t("\x1B[34m","\x1B[39m"),magenta:t("\x1B[35m","\x1B[39m"),cyan:t("\x1B[36m","\x1B[39m"),white:t("\x1B[37m","\x1B[39m"),gray:t("\x1B[90m","\x1B[39m"),bgBlack:t("\x1B[40m","\x1B[49m"),bgRed:t("\x1B[41m","\x1B[49m"),bgGreen:t("\x1B[42m","\x1B[49m"),bgYellow:t("\x1B[43m","\x1B[49m"),bgBlue:t("\x1B[44m","\x1B[49m"),bgMagenta:t("\x1B[45m","\x1B[49m"),bgCyan:t("\x1B[46m","\x1B[49m"),bgWhite:t("\x1B[47m","\x1B[49m"),blackBright:t("\x1B[90m","\x1B[39m"),redBright:t("\x1B[91m","\x1B[39m"),greenBright:t("\x1B[92m","\x1B[39m"),yellowBright:t("\x1B[93m","\x1B[39m"),blueBright:t("\x1B[94m","\x1B[39m"),magentaBright:t("\x1B[95m","\x1B[39m"),cyanBright:t("\x1B[96m","\x1B[39m"),whiteBright:t("\x1B[97m","\x1B[39m"),bgBlackBright:t("\x1B[100m","\x1B[49m"),bgRedBright:t("\x1B[101m","\x1B[49m"),bgGreenBright:t("\x1B[102m","\x1B[49m"),bgYellowBright:t("\x1B[103m","\x1B[49m"),bgBlueBright:t("\x1B[104m","\x1B[49m"),bgMagentaBright:t("\x1B[105m","\x1B[49m"),bgCyanBright:t("\x1B[106m","\x1B[49m"),bgWhiteBright:t("\x1B[107m","\x1B[49m")}};Me.exports=St();Me.exports.createColors=St});var Yn=/\d/,Xn=["-","_","/","."];function zn(e=""){if(!Yn.test(e))return e!==e.toLowerCase()}function pt(e,t){let n=t??Xn,r=[];if(!e||typeof e!="string")return r;let o="",i,s;for(let a of e){let c=n.includes(a);if(c===!0){r.push(o),o="",i=void 0;continue}let l=zn(a);if(s===!1){if(i===!1&&l===!0){r.push(o),o=a,i=l;continue}if(i===!0&&l===!1&&o.length>1){let u=o.at(-1);r.push(o.slice(0,Math.max(0,o.length-1))),o=u+a,i=l;continue}}o+=a,i=l,s=c}return r.push(o),r}function Qn(e){return e?e[0].toUpperCase()+e.slice(1):""}function Zn(e){return e?e[0].toLowerCase()+e.slice(1):""}function er(e,t){return e?(Array.isArray(e)?e:pt(e)).map(n=>Qn(t?.normalize?n.toLowerCase():n)).join(""):""}function ne(e,t){return Zn(er(e||"",t))}function ce(e,t){return e?(Array.isArray(e)?e:pt(e)).map(n=>n.toLowerCase()).join(t??"-"):""}function mt(e){return ce(e||"","_")}var ft=require("util");function re(e){return Array.isArray(e)?e:e===void 0?[]:[e]}function Ce(e,t=""){let n=[];for(let r of e)for(let[o,i]of r.entries())n[o]=Math.max(n[o]||0,i.length);return e.map(r=>r.map((o,i)=>t+o[i===0?"padStart":"padEnd"](n[i])).join(" ")).join(`
3
- `)}function E(e){return typeof e=="function"?e():e}var J=class extends Error{code;constructor(e,t){super(e),this.name="CLIError",this.code=t}};function tr(e=[],t={}){let n=new Set(t.boolean||[]),r=new Set(t.string||[]),o=t.alias||{},i=t.default||{},s=new Map,a=new Map;for(let[m,y]of Object.entries(o)){let A=y;for(let C of A)s.set(m,C),a.has(C)||a.set(C,[]),a.get(C).push(m),s.set(C,m),a.has(m)||a.set(m,[]),a.get(m).push(C)}let c={};function l(m){if(n.has(m))return"boolean";let y=a.get(m)||[];for(let A of y)if(n.has(A))return"boolean";return"string"}function u(m){if(r.has(m))return!0;let y=a.get(m)||[];for(let A of y)if(r.has(A))return!0;return!1}let d=new Set([...n,...r,...Object.keys(o),...Object.values(o).flat(),...Object.keys(i)]);for(let m of d)c[m]||(c[m]={type:l(m),default:i[m]});for(let[m,y]of s.entries())m.length===1&&c[y]&&!c[y].short&&(c[y].short=m);let g=[],p={};for(let m=0;m<e.length;m++){let y=e[m];if(y==="--"){g.push(...e.slice(m));break}if(y.startsWith("--no-")){let A=y.slice(5);p[A]=!0;continue}g.push(y)}let f;try{f=(0,ft.parseArgs)({args:g,options:Object.keys(c).length>0?c:void 0,allowPositionals:!0,strict:!1})}catch{f={values:{},positionals:g}}let h={_:[]};h._=f.positionals;for(let[m,y]of Object.entries(f.values)){let A=y;l(m)==="boolean"&&typeof y=="string"?A=y!=="false":u(m)&&typeof y=="boolean"&&(A=""),h[m]=A}for(let[m]of Object.entries(p)){h[m]=!1;let y=s.get(m);y&&(h[y]=!1);let A=a.get(m);if(A)for(let C of A)h[C]=!1}for(let[m,y]of s.entries())h[m]!==void 0&&h[y]===void 0&&(h[y]=h[m]),h[y]!==void 0&&h[m]===void 0&&(h[m]=h[y]),h[m]!==h[y]&&i[y]===h[y]&&(h[y]=h[m]);return h}var nr=(()=>{let e=globalThis.process?.env??{};return e.NO_COLOR==="1"||e.TERM==="dumb"||e.TEST||e.CI})(),pe=(e,t=39)=>n=>nr?n:`\x1B[${e}m${n}\x1B[${t}m`,le=pe(1,22),j=pe(36),de=pe(90),ue=pe(4,24);function rr(e,t){let n={boolean:[],string:[],alias:{},default:{}},r=yt(t);for(let a of r){if(a.type==="positional")continue;a.type==="string"||a.type==="enum"?n.string.push(a.name):a.type==="boolean"&&n.boolean.push(a.name),a.default!==void 0&&(n.default[a.name]=a.default),a.alias&&(n.alias[a.name]=a.alias);let c=ne(a.name),l=ce(a.name);if(c!==a.name||l!==a.name){let u=re(n.alias[a.name]||[]);c!==a.name&&!u.includes(c)&&u.push(c),l!==a.name&&!u.includes(l)&&u.push(l),u.length>0&&(n.alias[a.name]=u)}}let o=tr(e,n),[...i]=o._,s=new Proxy(o,{get(a,c){return a[c]??a[ne(c)]??a[ce(c)]}});for(let[,a]of r.entries())if(a.type==="positional"){let c=i.shift();if(c!==void 0)s[a.name]=c;else{if(a.default===void 0&&a.required!==!1)throw new J(`Missing required positional argument: ${a.name.toUpperCase()}`,"EARG");s[a.name]=a.default}}else if(a.type==="enum"){let c=s[a.name],l=a.options||[];if(c!==void 0&&l.length>0&&!l.includes(c))throw new J(`Invalid value for argument: ${j(`--${a.name}`)} (${j(c)}). Expected one of: ${l.map(u=>j(u)).join(", ")}.`,"EARG")}else if(a.required&&s[a.name]===void 0)throw new J(`Missing required argument: --${a.name}`,"EARG");return s}function yt(e){let t=[];for(let[n,r]of Object.entries(e||{}))t.push({...r,name:n,alias:re(r.alias)});return t}async function or(e){return Promise.all(e.map(t=>E(t)))}async function Te(e,t){let n=await E(e.args||{}),r=rr(t.rawArgs,n),o={rawArgs:t.rawArgs,args:r,data:t.data,cmd:e},i=await or(e.plugins??[]),s,a;try{for(let u of i)await u.setup?.(o);typeof e.setup=="function"&&await e.setup(o);let l=await E(e.subCommands);if(l&&Object.keys(l).length>0){let u=bt(t.rawArgs,n),d=t.rawArgs[u];if(d){let g=await Ie(l,d);if(!g)throw new J(`Unknown command ${j(d)}`,"E_UNKNOWN_COMMAND");await Te(g,{rawArgs:t.rawArgs.slice(u+1)})}else{let g=await E(e.default);if(g){if(e.run)throw new J("Cannot specify both 'run' and 'default' on the same command.","E_DEFAULT_CONFLICT");let p=await Ie(l,g);if(!p)throw new J(`Default sub command ${j(g)} not found in subCommands.`,"E_UNKNOWN_COMMAND");await Te(p,{rawArgs:t.rawArgs})}else if(!e.run)throw new J("No command specified.","E_NO_COMMAND")}}typeof e.run=="function"&&(s=await e.run(o))}catch(l){a=l}let c=[];if(typeof e.cleanup=="function")try{await e.cleanup(o)}catch(l){c.push(l)}for(let l of[...i].reverse())try{await l.cleanup?.(o)}catch(u){c.push(u)}if(a)throw a;if(c.length===1)throw c[0];if(c.length>1)throw new Error("Multiple cleanup errors",{cause:c});return{result:s}}async function Pe(e,t,n){let r=await E(e.subCommands);if(r&&Object.keys(r).length>0){let o=bt(t,await E(e.args||{})),i=t[o],s=await Ie(r,i);if(s)return Pe(s,t.slice(o+1),e)}return[e,n]}async function Ie(e,t){if(t in e)return E(e[t]);for(let n of Object.values(e)){let r=await E(n),o=await E(r?.meta);if(o?.alias&&re(o.alias).includes(t))return r}}function bt(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(r==="--")return-1;if(r.startsWith("-")){!r.includes("=")&&ir(r,t)&&n++;continue}return n}return-1}function ir(e,t){let n=e.replace(/^-{1,2}/,""),r=ne(n);for(let[o,i]of Object.entries(t))if(!(i.type!=="string"&&i.type!=="enum")&&(r===ne(o)||(Array.isArray(i.alias)?i.alias:i.alias?[i.alias]:[]).includes(n)))return!0;return!1}async function sr(e,t){try{console.log(await cr(e,t)+`
4
- `)}catch(n){console.error(n)}}var ar=/^no[-A-Z]/;async function cr(e,t){let n=await E(e.meta||{}),r=yt(await E(e.args||{})),o=await E(t?.meta||{}),i=`${o.name?`${o.name} `:""}`+(n.name||process.argv[1]),s=[],a=[],c=[],l=[];for(let p of r)if(p.type==="positional"){let f=p.name.toUpperCase(),h=p.required!==!1&&p.default===void 0;a.push([j(f+Ee(p)),gt(p,h)]),l.push(h?`<${f}>`:`[${f}]`)}else{let f=p.required===!0&&p.default===void 0,h=[...(p.alias||[]).map(m=>`-${m}`),`--${p.name}`].join(", ")+Ee(p);if(s.push([j(h),gt(p,f)]),p.type==="boolean"&&(p.default===!0||p.negativeDescription)&&!ar.test(p.name)){let m=[...(p.alias||[]).map(y=>`--no-${y}`),`--no-${p.name}`].join(", ");s.push([j(m),[p.negativeDescription,f?de("(Required)"):""].filter(Boolean).join(" ")])}f&&l.push(`--${p.name}`+Ee(p))}if(e.subCommands){let p=[],f=await E(e.subCommands);for(let[h,m]of Object.entries(f)){let y=await E((await E(m))?.meta);if(y?.hidden)continue;let A=re(y?.alias),C=[h,...A].join(", ");c.push([j(C),y?.description||""]),p.push(h,...A)}l.push(p.join("|"))}let u=[],d=n.version||o.version;u.push(de(`${n.description} (${i+(d?` v${d}`:"")})`),"");let g=s.length>0||a.length>0;return u.push(`${ue(le("USAGE"))} ${j(`${i}${g?" [OPTIONS]":""} ${l.join(" ")}`)}`,""),a.length>0&&(u.push(ue(le("ARGUMENTS")),""),u.push(Ce(a," ")),u.push("")),s.length>0&&(u.push(ue(le("OPTIONS")),""),u.push(Ce(s," ")),u.push("")),c.length>0&&(u.push(ue(le("COMMANDS")),""),u.push(Ce(c," ")),u.push("",`Use ${j(`${i} <command> --help`)} for more information about a command.`)),u.filter(p=>typeof p=="string").join(`
5
- `)}function Ee(e){let t=e.valueHint?`=<${e.valueHint}>`:"",n=t||`=<${mt(e.name)}>`;return!e.type||e.type==="positional"||e.type==="boolean"?t:e.type==="enum"&&e.options?.length?`=<${e.options.join("|")}>`:n}function gt(e,t){let n=t?de("(Required)"):"",r=e.default===void 0?"":de(`(Default: ${e.default})`);return[e.description,n,r].filter(Boolean).join(" ")}async function wt(e,t={}){let n=t.rawArgs||process.argv.slice(2),r=t.showUsage||sr;try{let o=await lr(e);if(o.help.length>0&&n.some(i=>o.help.includes(i)))await r(...await Pe(e,n)),process.exit(0);else if(n.length===1&&o.version.includes(n[0])){let i=typeof e.meta=="function"?await e.meta():await e.meta;if(!i?.version)throw new J("No version specified","E_NO_VERSION");console.log(i.version)}else await Te(e,{rawArgs:n})}catch(o){o instanceof J?(await r(...await Pe(e,n)),console.error(o.message)):console.error(o,`
6
- `),process.exit(1)}}async function lr(e){let t=await E(e.args||{}),n=new Set,r=new Set;for(let[o,i]of Object.entries(t)){n.add(o);for(let s of re(i.alias))r.add(s)}return{help:ht("help","h",n,r),version:ht("version","v",n,r)}}function ht(e,t,n,r){return n.has(e)||r.has(e)?[]:n.has(t)||r.has(t)?[`--${e}`]:[`--${e}`,`-${t}`]}var Re=U(D(),1);var Oe={name:"ax",version:"0.7.5",description:"Score any site's agent readiness and watch real AI agents navigate it \u2014 powered by ora",type:"module",packageManager:"pnpm@10.34.5",bin:{ax:"./dist/main.cjs"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"}},main:"./dist/index.cjs",types:"./dist/index.d.ts",files:["dist",".env.example"],engines:{node:">=22.4.0"},scripts:{build:"rm -rf dist && tsup && tsc -p tsconfig.lib.json","contract:gen":"node scripts/contract-gen.mjs",smoke:"node scripts/smoke.mjs","smoke:webmcp":"node scripts/smoke-webmcp.mjs","verify:pack":"node scripts/verify-pack.mjs",test:"vitest","test:ci":"vitest run --coverage","test:capture":"vitest run src/webmcp/capture.live.test.ts",lint:"biome check .","lint:fix":"biome check --write .",typecheck:"tsc --noEmit",prepublishOnly:"npm run build"},devDependencies:{"@biomejs/biome":"^2.5.7","@commitlint/cli":"^21.2.2","@commitlint/config-conventional":"^21.2.2","@types/node":"^26.2.0","@vitest/coverage-v8":"^3",citty:"^0.2.2","openapi-typescript":"^6.7.6",picocolors:"^1",tsup:"^8",typescript:"^7.0.2",vitest:"^3"},publishConfig:{access:"public"},pnpm:{onlyBuiltDependencies:["@biomejs/biome","esbuild"],overrides:{"undici@<6.28.0":"^6.28.0"}},license:"MIT",author:{name:"Era AI Labs",url:"https://ora.ai"},homepage:"https://ora.ai/docs#cli",bugs:"https://github.com/ora/ax/issues",repository:{type:"git",url:"git+https://github.com/ora/ax.git"},keywords:["ai","agents","agent-readiness","agent-experience","llms.txt","ora","cli","scan"]};var Ne="1.24.0";function kt(e){let[t=0,n=0]=e.split(".").map(r=>Number.parseInt(r,10));return[t,n]}function gr(e){if(!e||!/^\d+\.\d+\.\d+$/.test(e))return!1;let[t,n]=kt(e),[r,o]=kt(Ne);return t>r||t===r&&n>o}var xt=!1;function oe(e){xt||!gr(e)||(xt=!0,process.stderr.write(`ora reports contract ${e}; this CLI was built against ${Ne}. Newer fields may be missing from the output - upgrade with: npm i -g ax@latest
7
- `))}function F(e){let t=new AbortController,n=!1,r,o=()=>{clearTimeout(r),r=setTimeout(()=>{n=!0,t.abort()},e)};return o(),{signal:t.signal,poke:o,disarm:()=>clearTimeout(r),tripped:()=>n}}async function H(e){try{let t=await e.json();return t.message||t.error||`HTTP ${e.status}`}catch{return`HTTP ${e.status}`}}var K=e=>new Promise(t=>setTimeout(t,e));var hr="https://ora.ai",fr=6e4,yr=2e3,br=45,je=14,O=class extends Error{};function At(e){return e?{authorization:`Bearer ${e}`}:{}}async function $t(e,t={}){let n=(t.baseUrl??process.env.ORA_API_URL??hr).replace(/\/+$/,"");t={...t,apiKey:t.apiKey||process.env.ORA_SCAN_API_KEY||void 0},t.progress?.(`Auditing ${e} with ora`);let r=await vr(n,e,t);oe(r.result.contractVersion);let o=r.result;return _t(o)&&(o=await xr(n,o,t)),{result:o,verdict:r.verdict}}function wr(e,t,n){let r=new URLSearchParams({domain:t,format:"audit"});return n.force&&r.set("force","1"),n.ephemeral&&r.set("ephemeral","1"),n.maxAgeSeconds!==void 0&&r.set("maxAgeSeconds",String(n.maxAgeSeconds)),`${e}/api/scan/stream?${r}`}async function vr(e,t,n){let r=n.idleMs??fr,o=F(r),i=()=>new O(`ora audit timed out \u2014 no progress for ${Math.round(r/1e3)}s`),s;try{s=await fetch(wr(e,t,n),{headers:{accept:"text/event-stream",...At(n.apiKey)},signal:o.signal})}catch(g){if(o.disarm(),o.tripped())throw i();let p=g instanceof Error?g.message:String(g);throw new O(`ora audit request failed: ${p}`)}if(s.status===429){o.disarm();let g=s.headers.get("retry-after");throw new O(`ora rate limit exceeded${g?` \u2014 retry after ${g}s`:""} (burst: 10 scans/min/IP; daily: 30 scans + 6 force per 24h). An ora-issued scan API key lifts these limits: set ORA_SCAN_API_KEY or pass --api-key.`)}if(!s.ok||!s.body)throw o.disarm(),new O(`ora audit failed: ${await H(s)}`);let a=kr(),c=new TextDecoder,l="",u,d;try{e:for await(let g of s.body){o.poke(),l=`${l}${c.decode(g,{stream:!0})}`.replace(/\r\n?/g,`
8
- `);let p=l.indexOf(`
2
+ "use strict";var Or=Object.create;var Ot=Object.defineProperty;var Ir=Object.getOwnPropertyDescriptor;var Mr=Object.getOwnPropertyNames;var Lr=Object.getPrototypeOf,Nr=Object.prototype.hasOwnProperty;var jr=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Ur=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Mr(t))!Nr.call(e,o)&&o!==n&&Ot(e,o,{get:()=>t[o],enumerable:!(r=Ir(t,o))||r.enumerable});return e};var G=(e,t,n)=>(n=e!=null?Or(Lr(e)):{},Ur(t||!e||!e.__esModule?Ot(n,"default",{value:e,enumerable:!0}):n,e));var J=jr((Sa,ze)=>{"use strict";var Te=process||{},Ft=Te.argv||[],Ee=Te.env||{},eo=!(Ee.NO_COLOR||Ft.includes("--no-color"))&&(!!Ee.FORCE_COLOR||Ft.includes("--color")||Te.platform==="win32"||(Te.stdout||{}).isTTY&&Ee.TERM!=="dumb"||!!Ee.CI),to=(e,t,n=e)=>r=>{let o=""+r,s=o.indexOf(t,e.length);return~s?e+no(o,t,n,s)+t:e+o+t},no=(e,t,n,r)=>{let o="",s=0;do o+=e.substring(s,r)+n,s=r+t.length,r=e.indexOf(t,s);while(~r);return o+e.substring(s)},Bt=(e=eo)=>{let t=e?to:()=>String;return{isColorSupported:e,reset:t("\x1B[0m","\x1B[0m"),bold:t("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:t("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:t("\x1B[3m","\x1B[23m"),underline:t("\x1B[4m","\x1B[24m"),inverse:t("\x1B[7m","\x1B[27m"),hidden:t("\x1B[8m","\x1B[28m"),strikethrough:t("\x1B[9m","\x1B[29m"),black:t("\x1B[30m","\x1B[39m"),red:t("\x1B[31m","\x1B[39m"),green:t("\x1B[32m","\x1B[39m"),yellow:t("\x1B[33m","\x1B[39m"),blue:t("\x1B[34m","\x1B[39m"),magenta:t("\x1B[35m","\x1B[39m"),cyan:t("\x1B[36m","\x1B[39m"),white:t("\x1B[37m","\x1B[39m"),gray:t("\x1B[90m","\x1B[39m"),bgBlack:t("\x1B[40m","\x1B[49m"),bgRed:t("\x1B[41m","\x1B[49m"),bgGreen:t("\x1B[42m","\x1B[49m"),bgYellow:t("\x1B[43m","\x1B[49m"),bgBlue:t("\x1B[44m","\x1B[49m"),bgMagenta:t("\x1B[45m","\x1B[49m"),bgCyan:t("\x1B[46m","\x1B[49m"),bgWhite:t("\x1B[47m","\x1B[49m"),blackBright:t("\x1B[90m","\x1B[39m"),redBright:t("\x1B[91m","\x1B[39m"),greenBright:t("\x1B[92m","\x1B[39m"),yellowBright:t("\x1B[93m","\x1B[39m"),blueBright:t("\x1B[94m","\x1B[39m"),magentaBright:t("\x1B[95m","\x1B[39m"),cyanBright:t("\x1B[96m","\x1B[39m"),whiteBright:t("\x1B[97m","\x1B[39m"),bgBlackBright:t("\x1B[100m","\x1B[49m"),bgRedBright:t("\x1B[101m","\x1B[49m"),bgGreenBright:t("\x1B[102m","\x1B[49m"),bgYellowBright:t("\x1B[103m","\x1B[49m"),bgBlueBright:t("\x1B[104m","\x1B[49m"),bgMagentaBright:t("\x1B[105m","\x1B[49m"),bgCyanBright:t("\x1B[106m","\x1B[49m"),bgWhiteBright:t("\x1B[107m","\x1B[49m")}};ze.exports=Bt();ze.exports.createColors=Bt});var Dr=/\d/,Wr=["-","_","/","."];function Fr(e=""){if(!Dr.test(e))return e!==e.toLowerCase()}function It(e,t){let n=t??Wr,r=[];if(!e||typeof e!="string")return r;let o="",s,i;for(let a of e){let c=n.includes(a);if(c===!0){r.push(o),o="",s=void 0;continue}let l=Fr(a);if(i===!1){if(s===!1&&l===!0){r.push(o),o=a,s=l;continue}if(s===!0&&l===!1&&o.length>1){let u=o.at(-1);r.push(o.slice(0,Math.max(0,o.length-1))),o=u+a,s=l;continue}}o+=a,s=l,i=c}return r.push(o),r}function Br(e){return e?e[0].toUpperCase()+e.slice(1):""}function Jr(e){return e?e[0].toLowerCase()+e.slice(1):""}function Hr(e,t){return e?(Array.isArray(e)?e:It(e)).map(n=>Br(t?.normalize?n.toLowerCase():n)).join(""):""}function pe(e,t){return Jr(Hr(e||"",t))}function xe(e,t){return e?(Array.isArray(e)?e:It(e)).map(n=>n.toLowerCase()).join(t??"-"):""}function Mt(e){return xe(e||"","_")}var jt=require("util");function me(e){return Array.isArray(e)?e:e===void 0?[]:[e]}function qe(e,t=""){let n=[];for(let r of e)for(let[o,s]of r.entries())n[o]=Math.max(n[o]||0,s.length);return e.map(r=>r.map((o,s)=>t+o[s===0?"padStart":"padEnd"](n[s])).join(" ")).join(`
3
+ `)}function I(e){return typeof e=="function"?e():e}var q=class extends Error{code;constructor(e,t){super(e),this.name="CLIError",this.code=t}};function Gr(e=[],t={}){let n=new Set(t.boolean||[]),r=new Set(t.string||[]),o=t.alias||{},s=t.default||{},i=new Map,a=new Map;for(let[p,y]of Object.entries(o)){let A=y;for(let T of A)i.set(p,T),a.has(T)||a.set(T,[]),a.get(T).push(p),i.set(T,p),a.has(p)||a.set(p,[]),a.get(p).push(T)}let c={};function l(p){if(n.has(p))return"boolean";let y=a.get(p)||[];for(let A of y)if(n.has(A))return"boolean";return"string"}function u(p){if(r.has(p))return!0;let y=a.get(p)||[];for(let A of y)if(r.has(A))return!0;return!1}let d=new Set([...n,...r,...Object.keys(o),...Object.values(o).flat(),...Object.keys(s)]);for(let p of d)c[p]||(c[p]={type:l(p),default:s[p]});for(let[p,y]of i.entries())p.length===1&&c[y]&&!c[y].short&&(c[y].short=p);let h=[],m={};for(let p=0;p<e.length;p++){let y=e[p];if(y==="--"){h.push(...e.slice(p));break}if(y.startsWith("--no-")){let A=y.slice(5);m[A]=!0;continue}h.push(y)}let f;try{f=(0,jt.parseArgs)({args:h,options:Object.keys(c).length>0?c:void 0,allowPositionals:!0,strict:!1})}catch{f={values:{},positionals:h}}let g={_:[]};g._=f.positionals;for(let[p,y]of Object.entries(f.values)){let A=y;l(p)==="boolean"&&typeof y=="string"?A=y!=="false":u(p)&&typeof y=="boolean"&&(A=""),g[p]=A}for(let[p]of Object.entries(m)){g[p]=!1;let y=i.get(p);y&&(g[y]=!1);let A=a.get(p);if(A)for(let T of A)g[T]=!1}for(let[p,y]of i.entries())g[p]!==void 0&&g[y]===void 0&&(g[y]=g[p]),g[y]!==void 0&&g[p]===void 0&&(g[p]=g[y]),g[p]!==g[y]&&s[y]===g[y]&&(g[y]=g[p]);return g}var qr=(()=>{let e=globalThis.process?.env??{};return e.NO_COLOR==="1"||e.TERM==="dumb"||e.TEST||e.CI})(),Re=(e,t=39)=>n=>qr?n:`\x1B[${e}m${n}\x1B[${t}m`,Ae=Re(1,22),W=Re(36),$e=Re(90),ke=Re(4,24);function Kr(e,t){let n={boolean:[],string:[],alias:{},default:{}},r=Ut(t);for(let a of r){if(a.type==="positional")continue;a.type==="string"||a.type==="enum"?n.string.push(a.name):a.type==="boolean"&&n.boolean.push(a.name),a.default!==void 0&&(n.default[a.name]=a.default),a.alias&&(n.alias[a.name]=a.alias);let c=pe(a.name),l=xe(a.name);if(c!==a.name||l!==a.name){let u=me(n.alias[a.name]||[]);c!==a.name&&!u.includes(c)&&u.push(c),l!==a.name&&!u.includes(l)&&u.push(l),u.length>0&&(n.alias[a.name]=u)}}let o=Gr(e,n),[...s]=o._,i=new Proxy(o,{get(a,c){return a[c]??a[pe(c)]??a[xe(c)]}});for(let[,a]of r.entries())if(a.type==="positional"){let c=s.shift();if(c!==void 0)i[a.name]=c;else{if(a.default===void 0&&a.required!==!1)throw new q(`Missing required positional argument: ${a.name.toUpperCase()}`,"EARG");i[a.name]=a.default}}else if(a.type==="enum"){let c=i[a.name],l=a.options||[];if(c!==void 0&&l.length>0&&!l.includes(c))throw new q(`Invalid value for argument: ${W(`--${a.name}`)} (${W(c)}). Expected one of: ${l.map(u=>W(u)).join(", ")}.`,"EARG")}else if(a.required&&i[a.name]===void 0)throw new q(`Missing required argument: --${a.name}`,"EARG");return i}function Ut(e){let t=[];for(let[n,r]of Object.entries(e||{}))t.push({...r,name:n,alias:me(r.alias)});return t}async function Yr(e){return Promise.all(e.map(t=>I(t)))}async function Ye(e,t){let n=await I(e.args||{}),r=Kr(t.rawArgs,n),o={rawArgs:t.rawArgs,args:r,data:t.data,cmd:e},s=await Yr(e.plugins??[]),i,a;try{for(let u of s)await u.setup?.(o);typeof e.setup=="function"&&await e.setup(o);let l=await I(e.subCommands);if(l&&Object.keys(l).length>0){let u=Dt(t.rawArgs,n),d=t.rawArgs[u];if(d){let h=await Xe(l,d);if(!h)throw new q(`Unknown command ${W(d)}`,"E_UNKNOWN_COMMAND");await Ye(h,{rawArgs:t.rawArgs.slice(u+1)})}else{let h=await I(e.default);if(h){if(e.run)throw new q("Cannot specify both 'run' and 'default' on the same command.","E_DEFAULT_CONFLICT");let m=await Xe(l,h);if(!m)throw new q(`Default sub command ${W(h)} not found in subCommands.`,"E_UNKNOWN_COMMAND");await Ye(m,{rawArgs:t.rawArgs})}else if(!e.run)throw new q("No command specified.","E_NO_COMMAND")}}typeof e.run=="function"&&(i=await e.run(o))}catch(l){a=l}let c=[];if(typeof e.cleanup=="function")try{await e.cleanup(o)}catch(l){c.push(l)}for(let l of[...s].reverse())try{await l.cleanup?.(o)}catch(u){c.push(u)}if(a)throw a;if(c.length===1)throw c[0];if(c.length>1)throw new Error("Multiple cleanup errors",{cause:c});return{result:i}}async function Ve(e,t,n){let r=await I(e.subCommands);if(r&&Object.keys(r).length>0){let o=Dt(t,await I(e.args||{})),s=t[o],i=await Xe(r,s);if(i)return Ve(i,t.slice(o+1),e)}return[e,n]}async function Xe(e,t){if(t in e)return I(e[t]);for(let n of Object.values(e)){let r=await I(n),o=await I(r?.meta);if(o?.alias&&me(o.alias).includes(t))return r}}function Dt(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(r==="--")return-1;if(r.startsWith("-")){!r.includes("=")&&Vr(r,t)&&n++;continue}return n}return-1}function Vr(e,t){let n=e.replace(/^-{1,2}/,""),r=pe(n);for(let[o,s]of Object.entries(t))if(!(s.type!=="string"&&s.type!=="enum")&&(r===pe(o)||(Array.isArray(s.alias)?s.alias:s.alias?[s.alias]:[]).includes(n)))return!0;return!1}async function Xr(e,t){try{console.log(await Zr(e,t)+`
4
+ `)}catch(n){console.error(n)}}var zr=/^no[-A-Z]/;async function Zr(e,t){let n=await I(e.meta||{}),r=Ut(await I(e.args||{})),o=await I(t?.meta||{}),s=`${o.name?`${o.name} `:""}`+(n.name||process.argv[1]),i=[],a=[],c=[],l=[];for(let m of r)if(m.type==="positional"){let f=m.name.toUpperCase(),g=m.required!==!1&&m.default===void 0;a.push([W(f+Ke(m)),Lt(m,g)]),l.push(g?`<${f}>`:`[${f}]`)}else{let f=m.required===!0&&m.default===void 0,g=[...(m.alias||[]).map(p=>`-${p}`),`--${m.name}`].join(", ")+Ke(m);if(i.push([W(g),Lt(m,f)]),m.type==="boolean"&&(m.default===!0||m.negativeDescription)&&!zr.test(m.name)){let p=[...(m.alias||[]).map(y=>`--no-${y}`),`--no-${m.name}`].join(", ");i.push([W(p),[m.negativeDescription,f?$e("(Required)"):""].filter(Boolean).join(" ")])}f&&l.push(`--${m.name}`+Ke(m))}if(e.subCommands){let m=[],f=await I(e.subCommands);for(let[g,p]of Object.entries(f)){let y=await I((await I(p))?.meta);if(y?.hidden)continue;let A=me(y?.alias),T=[g,...A].join(", ");c.push([W(T),y?.description||""]),m.push(g,...A)}l.push(m.join("|"))}let u=[],d=n.version||o.version;u.push($e(`${n.description} (${s+(d?` v${d}`:"")})`),"");let h=i.length>0||a.length>0;return u.push(`${ke(Ae("USAGE"))} ${W(`${s}${h?" [OPTIONS]":""} ${l.join(" ")}`)}`,""),a.length>0&&(u.push(ke(Ae("ARGUMENTS")),""),u.push(qe(a," ")),u.push("")),i.length>0&&(u.push(ke(Ae("OPTIONS")),""),u.push(qe(i," ")),u.push("")),c.length>0&&(u.push(ke(Ae("COMMANDS")),""),u.push(qe(c," ")),u.push("",`Use ${W(`${s} <command> --help`)} for more information about a command.`)),u.filter(m=>typeof m=="string").join(`
5
+ `)}function Ke(e){let t=e.valueHint?`=<${e.valueHint}>`:"",n=t||`=<${Mt(e.name)}>`;return!e.type||e.type==="positional"||e.type==="boolean"?t:e.type==="enum"&&e.options?.length?`=<${e.options.join("|")}>`:n}function Lt(e,t){let n=t?$e("(Required)"):"",r=e.default===void 0?"":$e(`(Default: ${e.default})`);return[e.description,n,r].filter(Boolean).join(" ")}async function Wt(e,t={}){let n=t.rawArgs||process.argv.slice(2),r=t.showUsage||Xr;try{let o=await Qr(e);if(o.help.length>0&&n.some(s=>o.help.includes(s)))await r(...await Ve(e,n)),process.exit(0);else if(n.length===1&&o.version.includes(n[0])){let s=typeof e.meta=="function"?await e.meta():await e.meta;if(!s?.version)throw new q("No version specified","E_NO_VERSION");console.log(s.version)}else await Ye(e,{rawArgs:n})}catch(o){o instanceof q?(await r(...await Ve(e,n)),console.error(o.message)):console.error(o,`
6
+ `),process.exit(1)}}async function Qr(e){let t=await I(e.args||{}),n=new Set,r=new Set;for(let[o,s]of Object.entries(t)){n.add(o);for(let i of me(s.alias))r.add(i)}return{help:Nt("help","h",n,r),version:Nt("version","v",n,r)}}function Nt(e,t,n,r){return n.has(e)||r.has(e)?[]:n.has(t)||r.has(t)?[`--${e}`]:[`--${e}`,`-${t}`]}var Ge=G(J(),1);var he={name:"ax",version:"0.8.0",description:"Score any site's agent readiness and watch real AI agents navigate it \u2014 powered by ora",type:"module",packageManager:"pnpm@10.34.5",bin:{ax:"./dist/main.cjs"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"}},main:"./dist/index.cjs",types:"./dist/index.d.ts",files:["dist",".env.example"],engines:{node:">=22.4.0"},scripts:{build:"rm -rf dist && tsup && tsc -p tsconfig.lib.json","contract:gen":"node scripts/contract-gen.mjs",smoke:"node scripts/smoke.mjs","smoke:webmcp":"node scripts/smoke-webmcp.mjs","verify:pack":"node scripts/verify-pack.mjs",test:"vitest","test:ci":"vitest run --coverage","test:capture":"vitest run src/webmcp/capture.live.test.ts",lint:"biome check .","lint:fix":"biome check --write .",typecheck:"tsc --noEmit",prepublishOnly:"npm run build"},devDependencies:{"@biomejs/biome":"^2.5.7","@commitlint/cli":"^21.2.2","@commitlint/config-conventional":"^21.2.2","@ora-ai/tunnel-protocol":"^0.2.0","@types/node":"^26.2.0","@vitest/coverage-v8":"^3",citty:"^0.2.2","openapi-typescript":"^6.7.6",picocolors:"^1",tsup:"^8",typescript:"^7.0.2",vitest:"^3"},publishConfig:{access:"public"},pnpm:{onlyBuiltDependencies:["@biomejs/biome","esbuild"],overrides:{"undici@<6.28.0":"^6.28.0"}},license:"MIT",author:{name:"Era AI Labs",url:"https://ora.ai"},homepage:"https://ora.ai/docs#cli",bugs:"https://github.com/ora/ax/issues",repository:{type:"git",url:"git+https://github.com/ora/ax.git"},keywords:["ai","agents","agent-readiness","agent-experience","llms.txt","ora","cli","scan"]};var Ze="1.25.0";function Jt(e){let[t=0,n=0]=e.split(".").map(r=>Number.parseInt(r,10));return[t,n]}function oo(e){if(!e||!/^\d+\.\d+\.\d+$/.test(e))return!1;let[t,n]=Jt(e),[r,o]=Jt(Ze);return t>r||t===r&&n>o}var Ht=!1;function ge(e){Ht||!oo(e)||(Ht=!0,process.stderr.write(`ora reports contract ${e}; this CLI was built against ${Ze}. Newer fields may be missing from the output - upgrade with: npm i -g ax@latest
7
+ `))}function Y(e){let t=new AbortController,n=!1,r,o=()=>{clearTimeout(r),r=setTimeout(()=>{n=!0,t.abort()},e)};return o(),{signal:t.signal,poke:o,disarm:()=>clearTimeout(r),tripped:()=>n}}async function V(e){try{let t=await e.json();return t.message||t.error||`HTTP ${e.status}`}catch{return`HTTP ${e.status}`}}var z=e=>new Promise(t=>setTimeout(t,e));var so="https://ora.ai",io=6e4,ao=2e3,co=45,Qe=14,j=class extends Error{};function Gt(e){return e?{authorization:`Bearer ${e}`}:{}}async function qt(e,t={}){let n=(t.baseUrl??process.env.ORA_API_URL??so).replace(/\/+$/,"");t={...t,apiKey:t.apiKey||process.env.ORA_SCAN_API_KEY||void 0},t.progress?.(`Auditing ${e} with ora`);let r=await uo(n,e,t);ge(r.result.contractVersion);let o=r.result;return Kt(o)&&(o=await ho(n,o,t)),{result:o,verdict:r.verdict}}function lo(e,t,n){let r=new URLSearchParams({domain:t,format:"audit"});return n.force&&r.set("force","1"),n.ephemeral&&r.set("ephemeral","1"),n.maxAgeSeconds!==void 0&&r.set("maxAgeSeconds",String(n.maxAgeSeconds)),`${e}/api/scan/stream?${r}`}async function uo(e,t,n){let r=n.idleMs??io,o=Y(r),s=()=>new j(`ora audit timed out \u2014 no progress for ${Math.round(r/1e3)}s`),i;try{i=await fetch(lo(e,t,n),{headers:{accept:"text/event-stream",...Gt(n.apiKey)},signal:o.signal})}catch(h){if(o.disarm(),o.tripped())throw s();let m=h instanceof Error?h.message:String(h);throw new j(`ora audit request failed: ${m}`)}if(i.status===429){o.disarm();let h=i.headers.get("retry-after");throw new j(`ora rate limit exceeded${h?` \u2014 retry after ${h}s`:""} (burst: 10 scans/min/IP; daily: 30 scans + 6 force per 24h). An ora-issued scan API key lifts these limits: set ORA_SCAN_API_KEY or pass --api-key.`)}if(!i.ok||!i.body)throw o.disarm(),new j(`ora audit failed: ${await V(i)}`);let a=mo(),c=new TextDecoder,l="",u,d;try{e:for await(let h of i.body){o.poke(),l=`${l}${c.decode(h,{stream:!0})}`.replace(/\r\n?/g,`
8
+ `);let m=l.indexOf(`
9
9
 
10
- `);for(;p!==-1;){let f=Sr(l.slice(0,p));if(l=l.slice(p+2),p=l.indexOf(`
10
+ `);for(;m!==-1;){let f=po(l.slice(0,m));if(l=l.slice(m+2),m=l.indexOf(`
11
11
 
12
- `),!f)continue;let h;try{h=JSON.parse(f)}catch{continue}let m=a(h);if(m&&n.progress?.(m),h.type==="error")throw new O(`ora audit failed: ${typeof h.message=="string"?h.message:"scan error"}`);if(h.type==="scan_complete"&&h.result?u=h.result:h.type==="summary_ready"&&typeof h.agenticSummary=="string"&&(d=h.agenticSummary),u&&d)break e}}}catch(g){if(o.tripped())throw i();if(g instanceof O)throw g;let p=g instanceof Error?g.message:String(g);throw new O(`ora audit stream error: ${p}`)}finally{o.disarm(),s.body.cancel().catch(()=>{})}if(!u)throw new O("ora audit stream ended before completing");return{result:u,verdict:d}}function Sr(e){let t=[];for(let n of e.split(`
12
+ `),!f)continue;let g;try{g=JSON.parse(f)}catch{continue}let p=a(g);if(p&&n.progress?.(p),g.type==="error")throw new j(`ora audit failed: ${typeof g.message=="string"?g.message:"scan error"}`);if(g.type==="scan_complete"&&g.result?u=g.result:g.type==="summary_ready"&&typeof g.agenticSummary=="string"&&(d=g.agenticSummary),u&&d)break e}}}catch(h){if(o.tripped())throw s();if(h instanceof j)throw h;let m=h instanceof Error?h.message:String(h);throw new j(`ora audit stream error: ${m}`)}finally{o.disarm(),i.body.cancel().catch(()=>{})}if(!u)throw new j("ora audit stream ended before completing");return{result:u,verdict:d}}function po(e){let t=[];for(let n of e.split(`
13
13
  `))n.startsWith("data:")&&t.push(n.slice(5).replace(/^ /,""));return t.join(`
14
- `)}function kr(){let e=0,t=0,n="";return r=>{switch(r.type){case"kind_detecting":return"Detecting URL kind\u2026";case"kind_detected":return typeof r.kind=="string"?`Detected ${r.kind}, scanning\u2026`:void 0;case"scan_init":Array.isArray(r.checkRoster)&&(e=r.checkRoster.length);return;case"discovery_phase":return typeof r.label=="string"?r.label:void 0;case"check_complete":{if(t+=1,typeof r.checkName=="string"&&(n=r.checkName),e<=0)return`Running checks\u2026 (${t})`;let o=Math.min(t,e),i=Math.min(je,Math.max(0,Math.round(o/e*je)));return`${`${"\u2588".repeat(i)}${"\u2591".repeat(je-i)}`} ${o}/${e}${n?` \xB7 ${n}`:""}`}case"scan_complete":return"Finishing up\u2026";default:return}}}function _t(e){return e.analysisStatus==="complete"||e.analysisStatus==="stuck"?!1:e.analysisStatus==="partial"?!0:(e.pendingChecks?.length??0)>0}async function xr(e,t,n){let r=`${e}/api/score/${encodeURIComponent(t.domain)}?format=audit`,o=n.pollEveryMs??yr,i=n.pollLimit??br,s=t;for(let a=0;a<i&&_t(s);a++){let c=s.pendingChecks?.length??0;n.progress?.(c?`Analyzing\u2026 ${c} check${c===1?"":"s"} pending`:"Analyzing\u2026"),await K(o);try{let l=await fetch(r,{headers:{accept:"application/json",...At(n.apiKey)},signal:AbortSignal.timeout(15e3)});l.ok&&(s=await l.json())}catch{}}return s}function Ar(e,t){let n=t.filter(r=>!r.skipped);return{name:e,checks:t,passed:n.filter(r=>r.passed).length,total:n.length,skipped:t.length-n.length}}function $r(e){let t=e.status==="pass",n=e.status==="na"||e.status==="pending",r={id:e.id,name:e.name,passed:t,status:e.status};return n&&(r.skipped=!0),n&&e.naReason?r.detail=e.naReason:e.details&&(r.detail=e.details),typeof e.estScoreGain=="number"&&(r.estScoreGain=e.estScoreGain),e.specUrl&&(r.specUrl=e.specUrl),!t&&!n&&e.recommendation&&(r.hint=e.recommendation),r}function Rt(e,t){let{result:n}=e,r=(n.layers??[]).map(s=>Ar(s.name,(s.checks??[]).map($r))),o={target:n.domain||t,score:n.score,grade:n.grade,summary:e.verdict,sections:r,topFixes:n.topFixes??[],reportUrl:n.url,analysisStatus:n.analysisStatus},i=n;return i.servedFromCache&&typeof i.resultAgeSeconds=="number"&&(o.cacheAgeSeconds=i.resultAgeSeconds),n.mcpAuthRequired&&(o.mcpAuthRequired=!0),o}var v=U(D(),1),_r=80,Rr=120,he=10;function Cr(){return Math.min(Rr,Math.max(_r,process.stdout.columns??100))}function We(e,t){return e.length<t?e+" ".repeat(t-e.length):e}function Et(e,t){if(t<=0||e.length<=t)return[e];let n=[],r="";for(let o of e.split(/\s+/))for(r=r?`${r} ${o}`:o;r.length>t;){let i=r.lastIndexOf(" ");i>0&&r.length-i-1<=t?(n.push(r.slice(0,i)),r=r.slice(i+1)):(n.push(r.slice(0,t)),r=r.slice(t))}return r&&n.push(r),n.length?n:[""]}function Le(e,t){let n=(s,a,c)=>v.default.dim(s+e.map(l=>"\u2500".repeat(l.width+2)).join(a)+c),r=v.default.dim("\u2502"),o=(s,a)=>{let c=s.map((d,g)=>Et(typeof d=="string"?d:d[0],e[g].width)),l=Math.max(1,...c.map(d=>d.length)),u=[];for(let d=0;d<l;d++){let g=c.map((p,f)=>{let h=We(p[d]??"",e[f].width),m=a??(typeof s[f]=="string"?e[f].paint:s[f][1]);return` ${m?m(h):h} `});u.push(r+g.join(r)+r)}return u},i=[n("\u250C","\u252C","\u2510")];return i.push(...o(e.map(s=>s.title),v.default.bold)),i.push(n("\u251C","\u253C","\u2524")),t.forEach((s,a)=>{i.push(...o(s)),a<t.length-1&&i.push(n("\u251C","\u253C","\u2524"))}),i.push(n("\u2514","\u2534","\u2518")),i}function Er(e,t){let r=Math.max(46,e-4-13),o=14,i=Math.min(26,Math.max(5,...t.map(l=>l.length))),s=r-1-i;s<o*2&&(i=Math.max(12,i-(o*2-s)),s=r-1-i);let a=Math.max(o,Math.ceil(s/2)),c=Math.max(o,s-a);return[{title:"",width:1},{title:"Check",width:i,paint:v.default.bold},{title:"What's wrong",width:a},{title:"How to fix",width:c,paint:v.default.cyan}]}function Ct(e,t,n,r){let i=Math.max(40,e-4-7),s=Math.min(30,Math.max(n[0].length,...t.map(a=>a.length)));return[{title:n[0],width:s,paint:r},{title:n[1],width:Math.max(20,i-s),paint:r}]}function Tr(e,t){if(t<=0)return v.default.dim("\u2500".repeat(he));let n=Math.min(he,Math.max(0,Math.round(e/t*he)));return v.default.green("\u2588".repeat(n))+v.default.dim("\u2591".repeat(he-n))}function Pr(e,t,n,r){let o=[""],i=e.total>0?`${e.passed}/${e.total} passed`:"no applicable checks",s=e.skipped>0?` \xB7 ${e.skipped} skipped`:"";o.push(` ${v.default.bold(We(e.name,n))} ${Tr(e.passed,e.total)} ${v.default.dim(i+s)}`);let a=e.checks.filter(c=>!c.passed&&!c.skipped);if(a.length){o.push(` ${v.default.red("\u2717")} ${v.default.bold(`Issues (${a.length})`)}`);let c=Le(Er(t,a.map(u=>u.name)),a.map(u=>[u.status==="warning"?["\u26A0",v.default.yellow]:["\u2717",v.default.red],u.name,[u.detail??"",d=>d],u.hint??""]));o.push(...c.map(u=>` ${u}`));let l=a.filter(u=>u.specUrl);for(let u of l)o.push(v.default.dim(` \u21B3 ${u.id} spec: ${u.specUrl}`))}if(r.showPassing){let c=e.checks.filter(l=>l.passed&&!l.skipped);if(c.length){o.push(` ${v.default.green("\u2713")} ${v.default.bold(`Passed (${c.length})`)}`);let l=Le(Ct(t,c.map(u=>u.name),["Check","Details"]),c.map(u=>[u.name,u.detail??""]));o.push(...l.map(u=>` ${u}`))}}if(r.showSkipped){let c=e.checks.filter(l=>l.skipped);if(c.length){o.push(` ${v.default.dim(`\u25CB Skipped (${c.length})`)}`);let l=Le(Ct(t,c.map(u=>u.name),["Check","Reason"],v.default.dim),c.map(u=>[u.name,u.detail??""]));o.push(...l.map(u=>` ${u}`))}}return o}function Ir(e){if(!e.topFixes.length)return[];let t=["",` ${v.default.bold("Top fixes")} ${v.default.dim("(ranked by ora)")}`],n=e.topFixes.reduce((r,o)=>Math.max(r,o.id.length),0);return e.topFixes.forEach((r,o)=>{let i=typeof r.estScoreGain=="number"?v.default.green(`\u2248 +${r.estScoreGain} pts`):v.default.dim("\u2014"),s=r.bonus?v.default.dim(" (bonus)"):"";t.push(` ${o+1}. ${v.default.bold(We(r.id,n))} ${i}${s}`)}),t}function Mr(e){return e<90?`${e}s`:e<5400?`${Math.round(e/60)} min`:`${Math.round(e/3600)}h`}function Tt(e,t={}){let n=Cr(),r=e.sections.reduce((l,u)=>Math.max(l,u.name.length),0),o=[""],i=e.score>=70?v.default.green:e.score>=50?v.default.yellow:v.default.red;if(o.push(` ${v.default.bold(e.target)} ${i(v.default.bold(`${e.score}/100 ${e.grade}`))}`),t.tunnel&&o.push(v.default.dim(" tunnel audit \u2014 disposable result, excluded from rankings; off-site checks (registry listings, brand search) usually fail for a throwaway hostname")),e.mcpAuthRequired&&o.push(v.default.yellow(" \u26A0 MCP handshake requires credentials \u2014 target is unscored (0/F means could not evaluate, not failed everything)")),e.summary)for(let l of Et(e.summary,n-4))o.push(` ${v.default.dim(l)}`);for(let l of e.sections)o.push(...Pr(l,n,r,t));o.push(...Ir(e));let s=e.sections.reduce((l,u)=>l+u.passed,0),a=e.sections.reduce((l,u)=>l+u.skipped,0),c=[];if(!t.showPassing&&s>0&&c.push(` Run with --show-passing to list all ${s} passing checks`),!t.showSkipped&&a>0&&c.push(` ${a} check${a===1?"":"s"} skipped \u2014 run with --show-skipped to see them`),e.analysisStatus==="partial"?c.push(" Analysis still finishing \u2014 re-run shortly for the final score"):e.analysisStatus==="stuck"&&c.push(" Scan did not fully resolve \u2014 re-run with --force to complete it"),typeof e.cacheAgeSeconds=="number"&&c.push(` cached result (${Mr(e.cacheAgeSeconds)} old) \xB7 pass --force for a fresh scan`),e.reportUrl&&c.push(` Full report: ${e.reportUrl}`),c.length){o.push("");for(let l of c)o.push(v.default.dim(l))}return o.push(""),o}var Pt=require("child_process"),Q=class extends Error{},Or=3e4,Nr=9e4,jr=1e4;function De(e){try{let n=new URL(e.includes("://")?e:`http://${e}`).hostname;return n==="localhost"||n==="127.0.0.1"||n==="::1"||n==="[::1]"||n.endsWith(".local")||n.endsWith(".localhost")}catch{return!1}}function Lr(e){for(let t of e.matchAll(/https:\/\/[^\s"'|]+/g))try{let n=new URL(t[0]);if(n.pathname==="/"&&!n.search&&!De(n.hostname))return n.origin}catch{}}async function It(e,t=Or){let n=await Dr(e,t);try{await Wr(n.url,Nr)}catch(r){throw n.close(),r}return n}async function Wr(e,t){let n=Date.now()+t;for(;Date.now()<n;){try{if((await fetch(e,{redirect:"manual",signal:AbortSignal.timeout(jr)})).status<500)return}catch{}await new Promise(r=>setTimeout(r,5e3))}throw new Q([`tunnel opened but never became routable within ${Math.round(t/1e3)}s.`,"Some networks and DNS filters block tunnel vendors' domains entirely -","if this repeats, try another network, DNS resolver, or tunnel tool."].join(`
15
- `))}function Dr(e,t){return new Promise((n,r)=>{let o=process.platform!=="win32",i=(0,Pt.spawn)(e,{shell:!0,detached:o,stdio:["ignore","pipe","pipe"]}),s=!1,a="",c=()=>{try{o&&i.pid?process.kill(-i.pid,"SIGTERM"):i.kill("SIGTERM")}catch{}},l=d=>{s||(s=!0,clearTimeout(u),c(),r(d))},u=setTimeout(()=>l(new Q(`tunnel command did not print a public https URL within ${Math.round(t/1e3)}s: ${e}`)),t);i.on("error",d=>l(new Q(d.message))),i.on("exit",d=>{let g=a.trim()?`
16
- output: ${a.trim().slice(-300)}`:"";l(new Q(`tunnel command exited before printing a public https URL (code ${d??"unknown"}): ${e}${g}`))});for(let d of[i.stdout,i.stderr])d?.setEncoding("utf8"),d?.on("data",g=>{a=(a+g).slice(-2e3);let p=Lr(a);p&&!s&&(s=!0,clearTimeout(u),i.removeAllListeners("exit"),n({url:p,close:c}))})})}var Be=U(D(),1);function G(e,t){let n=process.stdout.columns??100;return Math.min(t,Math.max(e,n))}function V(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function T(e,t){let n=[],r="";for(let o of e.replace(/\s+/g," ").trim().split(" "))r&&r.length+1+o.length>t?(n.push(r),r=o):r=r?`${r} ${o}`:o;return r&&n.push(r),n}var Z=["\u25C7","\u25C7","\u25C8","\u25C8","\u25C6","\u25C6","\u25C8","\u25C8"];function _(e){return e.replace(/[\u0000-\u001f\u007f-\u009f]/g," ")}var Br=80,fe,Ue=0,ie="";function Ur(){let e=Be.default.cyan(Z[Ue%Z.length]),t=Math.max(10,(process.stderr.columns??80)-2),n=ie.length>t?`${ie.slice(0,t-1)}\u2026`:ie;process.stderr.write(`\r\x1B[K${e} ${Be.default.dim(n)}`),Ue++}var k={start(e){k.stop(),Ue=0,ie=e,process.stderr.isTTY&&(fe=setInterval(Ur,Br))},update(e){ie=e},stop(){fe&&(clearInterval(fe),fe=void 0,process.stderr.write("\r\x1B[K"))}};var P={OK:0,BELOW_MIN_SCORE:1,USAGE:2,API:3};function Mt(e,t,n,r){if(e===void 0)return{};let o=Number(e);return e.trim()===""||!Number.isInteger(o)||o<n||o>r?{error:`${t} must be an integer between ${n} and ${r}, got ${JSON.stringify(e)}`}:{value:o}}function Jr(e){let t=e.trim().replace(/\/+$/,"");if(!(!t||/\s/.test(t)))try{let n=new URL(t.includes("://")?t:`https://${t}`);return!n.hostname.includes(".")&&n.hostname!=="localhost"?void 0:t}catch{return}}async function Ot(e){let t=Jr(e.url);if(!t)return console.error(`Not a scannable URL or domain: ${JSON.stringify(e.url)}`),P.USAGE;let n=Mt(e.minScore,"--min-score",0,100),r=Mt(e.maxAge,"--max-age",0,86400);for(let p of[n,r])if(p.error)return console.error(p.error),P.USAGE;let o=e.tunnelCmd?.trim()||process.env.ORA_TUNNEL_CMD?.trim(),i=!!o;if(!i&&De(t))return console.error([`${t} only exists on this machine, and ora audits public URLs.`,"Either audit a publicly reachable deployment of this site (e.g. a preview URL),","or run it through a tunnel you provide:"," ax audit localhost:3000 --tunnel-cmd 'ngrok http 3000 --log stdout'","Any command that prints a public https URL works; the result is stored as","ephemeral (excluded from rankings, deleted after a few days)."].join(`
17
- `)),P.USAGE;let s=!e.json;s&&k.start(`Auditing ${t} with ora`);let a,c=()=>a?.close(),l=p=>{c(),process.exit(p==="SIGINT"?130:143)},u=t;if(i&&o){s&&k.update(`Opening a tunnel to ${t}`);try{a=await It(o)}catch(p){return k.stop(),console.error(p instanceof Error?p.message:String(p)),P.USAGE}process.on("SIGINT",l),process.on("SIGTERM",l),u=a.url}let d;try{d=await $t(u,{progress:s?p=>k.update(p):void 0,maxAgeSeconds:r.value,force:e.force,ephemeral:i||void 0,apiKey:e.apiKey?.trim()||void 0})}catch(p){return k.stop(),console.error(`Audit failed: ${p instanceof Error?p.message:String(p)}`),p instanceof O?P.API:P.USAGE}finally{c(),process.removeListener("SIGINT",l),process.removeListener("SIGTERM",l)}k.stop();let{result:g}=d;if(e.json)process.stdout.write(`${JSON.stringify(g,null,2)}
18
- `);else for(let p of Tt(Rt(d,t),{showSkipped:e.showSkipped,showPassing:e.showPassing,tunnel:i}))console.log(p);if(n.value!==void 0){if(g.mcpAuthRequired)return process.stderr.write(`--min-score skipped: the MCP handshake requires credentials, so the target is unscored
19
- `),P.OK;if(g.score<n.value)return e.json||console.log(` Score ${g.score} is below the required minimum ${n.value}
20
- `),P.BELOW_MIN_SCORE}return P.OK}var w=U(D(),1);var Fr="https://api.agentfront.sh",Hr=12e4;async function Gr(e,t){let n=await fetch(`${e}/auth/token`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:"{}"});if(n.status===401)throw new Error("ora rejected the API key (401). Check ORA_API_KEY.");let r=await n.json().catch(()=>({}));if(!n.ok||!r.token)throw new Error(`ora auth failed (${n.status})${r.error?`: ${r.error}`:""}`);return r.token}async function qr(e,t,n){let r={intent:n.intent};n.domain&&(r.domain=n.domain),n.harness&&(r.harness=n.harness),n.model&&(r.model=n.model),n.executionKind&&(r.execution_kind=n.executionKind);let o=await fetch(`${e}/experiment/v1/runs`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify(r)});if(o.status===429)throw new Error("ora rate limit hit (429). Wait a moment and retry.");let i=await o.text(),s;try{s=JSON.parse(i)}catch{throw new Error(`ora returned a non-JSON response (${o.status})`)}if(!o.ok||!s.runId)throw new Error(`ora run failed (${o.status}): ${s.message??s.error??i}`);return s}function Je(e){let t="message",n=[];for(let r of e.split(`
14
+ `)}function mo(){let e=0,t=0,n="";return r=>{switch(r.type){case"kind_detecting":return"Detecting URL kind\u2026";case"kind_detected":return typeof r.kind=="string"?`Detected ${r.kind}, scanning\u2026`:void 0;case"scan_init":Array.isArray(r.checkRoster)&&(e=r.checkRoster.length);return;case"discovery_phase":return typeof r.label=="string"?r.label:void 0;case"check_complete":{if(t+=1,typeof r.checkName=="string"&&(n=r.checkName),e<=0)return`Running checks\u2026 (${t})`;let o=Math.min(t,e),s=Math.min(Qe,Math.max(0,Math.round(o/e*Qe)));return`${`${"\u2588".repeat(s)}${"\u2591".repeat(Qe-s)}`} ${o}/${e}${n?` \xB7 ${n}`:""}`}case"scan_complete":return"Finishing up\u2026";default:return}}}function Kt(e){return e.analysisStatus==="complete"||e.analysisStatus==="stuck"?!1:e.analysisStatus==="partial"?!0:(e.pendingChecks?.length??0)>0}async function ho(e,t,n){let r=`${e}/api/score/${encodeURIComponent(t.domain)}?format=audit`,o=n.pollEveryMs??ao,s=n.pollLimit??co,i=t;for(let a=0;a<s&&Kt(i);a++){let c=i.pendingChecks?.length??0;n.progress?.(c?`Analyzing\u2026 ${c} check${c===1?"":"s"} pending`:"Analyzing\u2026"),await z(o);try{let l=await fetch(r,{headers:{accept:"application/json",...Gt(n.apiKey)},signal:AbortSignal.timeout(15e3)});l.ok&&(i=await l.json())}catch{}}return i}function go(e,t){let n=t.filter(r=>!r.skipped);return{name:e,checks:t,passed:n.filter(r=>r.passed).length,total:n.length,skipped:t.length-n.length}}function fo(e){let t=e.status==="pass",n=e.status==="na"||e.status==="pending",r={id:e.id,name:e.name,passed:t,status:e.status};return n&&(r.skipped=!0),n&&e.naReason?r.detail=e.naReason:e.details&&(r.detail=e.details),typeof e.estScoreGain=="number"&&(r.estScoreGain=e.estScoreGain),e.specUrl&&(r.specUrl=e.specUrl),!t&&!n&&e.recommendation&&(r.hint=e.recommendation),r}function Yt(e,t){let{result:n}=e,r=(n.layers??[]).map(i=>go(i.name,(i.checks??[]).map(fo))),o={target:n.domain||t,score:n.score,grade:n.grade,summary:e.verdict,sections:r,topFixes:n.topFixes??[],reportUrl:n.url,analysisStatus:n.analysisStatus},s=n;return s.servedFromCache&&typeof s.resultAgeSeconds=="number"&&(o.cacheAgeSeconds=s.resultAgeSeconds),n.mcpAuthRequired&&(o.mcpAuthRequired=!0),o}var v=G(J(),1),yo=80,bo=120,_e=10;function wo(){return Math.min(bo,Math.max(yo,process.stdout.columns??100))}function tt(e,t){return e.length<t?e+" ".repeat(t-e.length):e}function Xt(e,t){if(t<=0||e.length<=t)return[e];let n=[],r="";for(let o of e.split(/\s+/))for(r=r?`${r} ${o}`:o;r.length>t;){let s=r.lastIndexOf(" ");s>0&&r.length-s-1<=t?(n.push(r.slice(0,s)),r=r.slice(s+1)):(n.push(r.slice(0,t)),r=r.slice(t))}return r&&n.push(r),n.length?n:[""]}function et(e,t){let n=(i,a,c)=>v.default.dim(i+e.map(l=>"\u2500".repeat(l.width+2)).join(a)+c),r=v.default.dim("\u2502"),o=(i,a)=>{let c=i.map((d,h)=>Xt(typeof d=="string"?d:d[0],e[h].width)),l=Math.max(1,...c.map(d=>d.length)),u=[];for(let d=0;d<l;d++){let h=c.map((m,f)=>{let g=tt(m[d]??"",e[f].width),p=a??(typeof i[f]=="string"?e[f].paint:i[f][1]);return` ${p?p(g):g} `});u.push(r+h.join(r)+r)}return u},s=[n("\u250C","\u252C","\u2510")];return s.push(...o(e.map(i=>i.title),v.default.bold)),s.push(n("\u251C","\u253C","\u2524")),t.forEach((i,a)=>{s.push(...o(i)),a<t.length-1&&s.push(n("\u251C","\u253C","\u2524"))}),s.push(n("\u2514","\u2534","\u2518")),s}function vo(e,t){let r=Math.max(46,e-4-13),o=14,s=Math.min(26,Math.max(5,...t.map(l=>l.length))),i=r-1-s;i<o*2&&(s=Math.max(12,s-(o*2-i)),i=r-1-s);let a=Math.max(o,Math.ceil(i/2)),c=Math.max(o,i-a);return[{title:"",width:1},{title:"Check",width:s,paint:v.default.bold},{title:"What's wrong",width:a},{title:"How to fix",width:c,paint:v.default.cyan}]}function Vt(e,t,n,r){let s=Math.max(40,e-4-7),i=Math.min(30,Math.max(n[0].length,...t.map(a=>a.length)));return[{title:n[0],width:i,paint:r},{title:n[1],width:Math.max(20,s-i),paint:r}]}function So(e,t){if(t<=0)return v.default.dim("\u2500".repeat(_e));let n=Math.min(_e,Math.max(0,Math.round(e/t*_e)));return v.default.green("\u2588".repeat(n))+v.default.dim("\u2591".repeat(_e-n))}function xo(e,t,n,r){let o=[""],s=e.total>0?`${e.passed}/${e.total} passed`:"no applicable checks",i=e.skipped>0?` \xB7 ${e.skipped} skipped`:"";o.push(` ${v.default.bold(tt(e.name,n))} ${So(e.passed,e.total)} ${v.default.dim(s+i)}`);let a=e.checks.filter(c=>!c.passed&&!c.skipped);if(a.length){o.push(` ${v.default.red("\u2717")} ${v.default.bold(`Issues (${a.length})`)}`);let c=et(vo(t,a.map(u=>u.name)),a.map(u=>[u.status==="warning"?["\u26A0",v.default.yellow]:["\u2717",v.default.red],u.name,[u.detail??"",d=>d],u.hint??""]));o.push(...c.map(u=>` ${u}`));let l=a.filter(u=>u.specUrl);for(let u of l)o.push(v.default.dim(` \u21B3 ${u.id} spec: ${u.specUrl}`))}if(r.showPassing){let c=e.checks.filter(l=>l.passed&&!l.skipped);if(c.length){o.push(` ${v.default.green("\u2713")} ${v.default.bold(`Passed (${c.length})`)}`);let l=et(Vt(t,c.map(u=>u.name),["Check","Details"]),c.map(u=>[u.name,u.detail??""]));o.push(...l.map(u=>` ${u}`))}}if(r.showSkipped){let c=e.checks.filter(l=>l.skipped);if(c.length){o.push(` ${v.default.dim(`\u25CB Skipped (${c.length})`)}`);let l=et(Vt(t,c.map(u=>u.name),["Check","Reason"],v.default.dim),c.map(u=>[u.name,u.detail??""]));o.push(...l.map(u=>` ${u}`))}}return o}function Ao(e){if(!e.topFixes.length)return[];let t=["",` ${v.default.bold("Top fixes")} ${v.default.dim("(ranked by ora)")}`],n=e.topFixes.reduce((r,o)=>Math.max(r,o.id.length),0);return e.topFixes.forEach((r,o)=>{let s=typeof r.estScoreGain=="number"?v.default.green(`\u2248 +${r.estScoreGain} pts`):v.default.dim("\u2014"),i=r.bonus?v.default.dim(" (bonus)"):"";t.push(` ${o+1}. ${v.default.bold(tt(r.id,n))} ${s}${i}`)}),t}function ko(e){return e<90?`${e}s`:e<5400?`${Math.round(e/60)} min`:`${Math.round(e/3600)}h`}function zt(e,t={}){let n=wo(),r=e.sections.reduce((l,u)=>Math.max(l,u.name.length),0),o=[""],s=e.score>=70?v.default.green:e.score>=50?v.default.yellow:v.default.red;if(o.push(` ${v.default.bold(e.target)} ${s(v.default.bold(`${e.score}/100 ${e.grade}`))}`),t.tunnel&&o.push(v.default.dim(" tunnel audit \u2014 disposable result, excluded from rankings; off-site checks (registry listings, brand search) usually fail for a throwaway hostname")),e.mcpAuthRequired&&o.push(v.default.yellow(" \u26A0 MCP handshake requires credentials \u2014 target is unscored (0/F means could not evaluate, not failed everything)")),e.summary)for(let l of Xt(e.summary,n-4))o.push(` ${v.default.dim(l)}`);for(let l of e.sections)o.push(...xo(l,n,r,t));o.push(...Ao(e));let i=e.sections.reduce((l,u)=>l+u.passed,0),a=e.sections.reduce((l,u)=>l+u.skipped,0),c=[];if(!t.showPassing&&i>0&&c.push(` Run with --show-passing to list all ${i} passing checks`),!t.showSkipped&&a>0&&c.push(` ${a} check${a===1?"":"s"} skipped \u2014 run with --show-skipped to see them`),e.analysisStatus==="partial"?c.push(" Analysis still finishing \u2014 re-run shortly for the final score"):e.analysisStatus==="stuck"&&c.push(" Scan did not fully resolve \u2014 re-run with --force to complete it"),typeof e.cacheAgeSeconds=="number"&&c.push(` cached result (${ko(e.cacheAgeSeconds)} old) \xB7 pass --force for a fresh scan`),e.reportUrl&&c.push(` Full report: ${e.reportUrl}`),c.length){o.push("");for(let l of c)o.push(v.default.dim(l))}return o.push(""),o}var Zt=require("child_process"),E=class extends Error{},$o=3e4,Qt=9e4,Ro=1e4;function nt(e){try{let n=new URL(e.includes("://")?e:`http://${e}`).hostname;return n==="localhost"||n==="127.0.0.1"||n==="::1"||n==="[::1]"||n.endsWith(".local")||n.endsWith(".localhost")}catch{return!1}}function Eo(e){for(let t of e.matchAll(/https:\/\/[^\s"'|]+/g))try{let n=new URL(t[0]);if(n.pathname==="/"&&!n.search&&!nt(n.hostname))return n.origin}catch{}}async function en(e,t=$o){let n=await To(e,t);try{await rt(n.url,Qt)}catch(r){throw n.close(),r}return n}async function rt(e,t=Qt,n=5e3,r){let o=Date.now()+t;for(;Date.now()<o;){if(r?.aborted)throw new E("interrupted while waiting for the tunnel");try{if((await fetch(e,{redirect:"manual",signal:AbortSignal.timeout(Ro)})).status<500)return}catch{}await new Promise(s=>setTimeout(s,n))}throw new E([`tunnel opened but never became routable within ${Math.round(t/1e3)}s.`,"Some networks and DNS filters block tunnel vendors' domains entirely -","if this repeats, try another network, DNS resolver, or tunnel tool."].join(`
15
+ `))}function To(e,t){return new Promise((n,r)=>{let o=process.platform!=="win32",s=(0,Zt.spawn)(e,{shell:!0,detached:o,stdio:["ignore","pipe","pipe"]}),i=!1,a="",c=()=>{try{o&&s.pid?process.kill(-s.pid,"SIGTERM"):s.kill("SIGTERM")}catch{}},l=d=>{i||(i=!0,clearTimeout(u),c(),r(d))},u=setTimeout(()=>l(new E(`tunnel command did not print a public https URL within ${Math.round(t/1e3)}s: ${e}`)),t);s.on("error",d=>l(new E(d.message))),s.on("exit",d=>{let h=a.trim()?`
16
+ output: ${a.trim().slice(-300)}`:"";l(new E(`tunnel command exited before printing a public https URL (code ${d??"unknown"}): ${e}${h}`))});for(let d of[s.stdout,s.stderr])d?.setEncoding("utf8"),d?.on("data",h=>{a=(a+h).slice(-2e3);let m=Eo(a);m&&!i&&(i=!0,clearTimeout(u),s.removeAllListeners("exit"),n({url:m,close:c}))})})}var vn=require("crypto"),Sn=require("events"),xn=require("http");var tn="https://api.agentfront.sh";function nn(e){return(e??process.env.ORA_PLATFORM_URL??tn).replace(/\/+$/,"")}var _o=12e4;async function Ce(e,t){let n=await fetch(`${e}/auth/token`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:"{}"});if(n.status===401)throw new Error("ora rejected the API key (401). Check ORA_API_KEY.");let r=await n.json().catch(()=>({}));if(!n.ok||!r.token)throw new Error(`ora auth failed (${n.status})${r.error?`: ${r.error}`:""}`);return r.token}async function Co(e,t,n){let r={intent:n.intent};n.domain&&(r.domain=n.domain),n.harness&&(r.harness=n.harness),n.model&&(r.model=n.model),n.executionKind&&(r.execution_kind=n.executionKind);let o=await fetch(`${e}/experiment/v1/runs`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify(r)});if(o.status===429)throw new Error("ora rate limit hit (429). Wait a moment and retry.");let s=await o.text(),i;try{i=JSON.parse(s)}catch{throw new Error(`ora returned a non-JSON response (${o.status})`)}if(!o.ok||!i.runId)throw new Error(`ora run failed (${o.status}): ${i.message??i.error??s}`);return i}function ot(e){let t="message",n=[];for(let r of e.split(`
21
17
  `))r.startsWith(":")||(r.startsWith("event:")?t=r.slice(6).trim():r.startsWith("data:")&&n.push(r.slice(5).replace(/^ /,"")));return n.length?{event:t,data:n.join(`
22
- `)}:null}async function Kr(e,t,n,r,o){let i=n.startsWith("http")?n:`${e}${n}`,s=F(o),a=await fetch(i,{headers:{authorization:`Bearer ${t}`,accept:"text/event-stream"},signal:s.signal});if(!a.ok||!a.body)throw s.disarm(),new Error(`ora run stream failed (${a.status})`);let c=new TextDecoder,l={steps:[],trajectory:[]},u="";try{e:for await(let d of a.body){s.poke(),u=`${u}${c.decode(d,{stream:!0})}`.replace(/\r\n?/g,`
23
- `);let g=u.indexOf(`
24
-
25
- `);for(;g!==-1;){let p=Je(u.slice(0,g));if(u=u.slice(g+2),g=u.indexOf(`
26
-
27
- `),!p)continue;let f;try{f=JSON.parse(p.data)}catch{continue}if(Vr(l,p.event,f,r),l.summary&&l.insight)break e}}}catch(d){throw s.tripped()?new Error(`ora run stream timed out after ${o}ms of silence`):d}finally{s.disarm(),a.body.cancel().catch(()=>{})}return l}function Vr(e,t,n,r){switch(t){case"trajectory":{let o=n.steps;Array.isArray(o)&&(e.trajectory=o,r.snapshot?.(e.trajectory));return}case"step":{let o=n.step;o&&(e.steps.push(o),r.step?.(o,Number(n.seq??e.steps.length)));return}case"result":{let o=n.result;o&&(e.summary=o,r.finished?.(o));return}case"insight":{let o=n.insight;o&&(e.insight=o,r.scored?.(o));return}default:return}}async function Yr(e,t,n){for(let r=0;;r++){let o;try{let i=await fetch(`${e}/experiment/v1/runs?pageSize=50`,{headers:{authorization:`Bearer ${t}`}});if(!i.ok)return;o=(await i.json()).results?.find(a=>a.id===n)}catch{return}if(!o)return;if(o.total_tokens!=null||o.cost_usd!=null)return{totalTokens:o.total_tokens??void 0,inputTokens:o.input_tokens??void 0,outputTokens:o.output_tokens??void 0,cacheReadTokens:o.cache_read_tokens??void 0,cacheCreationTokens:o.cache_creation_tokens??void 0,costUsd:o.cost_usd??void 0};if(r>0)return;await K(1200)}}async function Fe(e,t={}){let n=(e.baseUrl??process.env.ORA_PLATFORM_URL??Fr).replace(/\/+$/,""),r=e.apiKey??process.env.ORA_API_KEY;if(!r)throw new Error("Missing ORA_API_KEY. Set it in your environment or a local .env file (see .env.example).");let o=await Gr(n,r),i=await qr(n,o,e),s={runId:i.runId,intent:e.intent,domain:e.domain,harness:e.harness};if(i.status==="succeeded"&&!i.streamUrl)return{...s,steps:[],trajectory:[]};t.opened?.(i.runId);let a=await Kr(n,o,i.streamUrl??`/experiment/v1/runs/${i.runId}/stream`,t,e.idleMs??Hr),c=a.summary?await Yr(n,o,i.runId):void 0;return{...s,result:a.summary,insight:a.insight,usage:c,steps:a.steps,trajectory:a.trajectory}}var Xr="https://ora.ai",zr=12e4,Qr=5e3,Zr=180,R=class extends Error{};function He(e){return(e??process.env.ORA_API_URL??Xr).replace(/\/+$/,"")}async function Ge(e){let t;try{t=await fetch(e,{headers:{accept:"application/json"},signal:AbortSignal.timeout(15e3)})}catch(n){let r=n instanceof Error?n.message:String(n);throw new R(`ora request failed: ${r}`)}if(!t.ok)throw new R(`ora request failed: ${await H(t)}`);return await t.json()}function Lt(e){return Ge(`${He(e)}/api/journey/intents`)}function Wt(e){return Ge(`${He(e)}/api/journey/agents`)}function eo(e){let t=r=>{let o=e.headers.get(r);if(o===null)return;let i=Number.parseInt(o,10);return Number.isFinite(i)?i:void 0},n=t("x-ratelimit-reset");return{limit:t("x-ratelimit-limit"),remaining:t("x-ratelimit-remaining"),resetAtMs:n!==void 0?n*1e3:void 0}}async function to(e,t,n){let r={intent:n.task?{custom:n.task,domain:t}:{...n.intentId?{intent_id:n.intentId}:{},domain:t},harness:n.harness,model:n.model},o;try{o=await fetch(`${e}/api/journey/runs`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json",...n.apiKey?{authorization:`Bearer ${n.apiKey}`}:{}},body:JSON.stringify(r),signal:AbortSignal.timeout(3e4)})}catch(s){let a=s instanceof Error?s.message:String(s);throw new R(`ora journey request failed: ${a}`)}if(o.status===401)throw new R("free-text tasks need an ora partner API key \u2014 set ORA_PARTNER_API_KEY or pass --api-key (keys are issued by ora on request)");if(o.status===429){let s=o.headers.get("retry-after"),a=n.apiKey?"keyed allowance: 1000 runs per 24h per key":"burst: 20/min/IP; daily: 200 runs per 24h per IP \u2014 an ora partner API key raises this to 1000/24h per key: set ORA_PARTNER_API_KEY or pass --api-key";throw new R(`ora journey caller limit exceeded${s?` \u2014 retry after ${qe(Number(s)*1e3)}`:""} (${a})`)}if(o.status===503)throw new R("ora's run engine is unavailable right now \u2014 try again shortly");if(!o.ok)throw new R(`ora journey request failed: ${await H(o)}`);let i=await o.json();return oe(i.contractVersion),{record:i,cached:i.rate_limited===!0,allowance:eo(o)}}function qe(e){if(!Number.isFinite(e)||e<=0)return"soon";let t=e/36e5;if(t>=1)return`${Math.ceil(t)}h`;let n=e/6e4;return n>=1?`${Math.ceil(n)}m`:`${Math.ceil(e/1e3)}s`}function no(e){if(!e)return"starting\u2026";if(e.type==="text")return"thinking\u2026";if(e.action==="search")return e.search_query?`searching \u201C${Nt(e.search_query,40)}\u201D`:"searching\u2026";let t=e.label??`${e.url_host??""}${e.url_path??""}`,n=e.completed===!1?"fetching":"fetched";return t?`${n} ${Nt(t,48)}`:`${n}\u2026`}function Nt(e,t){return e.length>t?`${e.slice(0,t-1)}\u2026`:e}async function ro(e,t,n){let r=t.startsWith("http")?t:`${e}${t}`,o=n.idleMs??zr,i=F(o),s=()=>new R(`ora journey stream timed out \u2014 no frames for ${Math.round(o/1e3)}s`),a;try{a=await fetch(r,{headers:{accept:"text/event-stream"},signal:i.signal})}catch(d){if(i.disarm(),i.tripped())throw s();let g=d instanceof Error?d.message:String(d);throw new R(`ora journey stream failed: ${g}`)}if(!a.ok||!a.body)throw i.disarm(),new R(`ora journey stream failed: ${await H(a)}`);let c=new TextDecoder,l={},u="";try{e:for await(let d of a.body){i.poke(),u=`${u}${c.decode(d,{stream:!0})}`.replace(/\r\n?/g,`
28
- `);let g=u.indexOf(`
29
-
30
- `);for(;g!==-1;){let p=Je(u.slice(0,g));if(u=u.slice(g+2),g=u.indexOf(`
31
-
32
- `),!p)continue;let f;try{f=JSON.parse(p.data)}catch{continue}if(p.event==="trajectory"){let h=f.steps??[],m=h.filter(y=>y.type==="tool_call").at(-1);n.progress?.(`step ${h.length} \xB7 ${no(m??h.at(-1))}`),n.onTrajectory?.(h)}else if(p.event==="processing")n.progress?.(typeof f.message=="string"?f.message:"generating insights\u2026");else if(p.event==="result"){l.result=f;break e}else if(p.event==="error"){l.errorMessage=typeof f.message=="string"?f.message:"unknown engine error";break e}}}}catch(d){if(i.tripped())throw s();if(d instanceof R)throw d;let g=d instanceof Error?d.message:String(d);throw new R(`ora journey stream error: ${g}`)}finally{i.disarm(),a.body.cancel().catch(()=>{})}return l}function ye(e,t){return Ge(`${e}/api/journey/runs/${encodeURIComponent(t)}`)}async function jt(e,t,n){let r=n.pollEveryMs??Qr,o=n.pollLimit??Zr,i=await ye(e,t);for(let s=0;s<o&&i.status==="running";s++){n.progress?.("agent working\u2026 (polling)"),await K(r);try{i=await ye(e,t)}catch{}}return i}async function Dt(e,t){let n=He(t.baseUrl);t={...t,apiKey:t.apiKey||process.env.ORA_PARTNER_API_KEY||process.env.ORA_SCAN_API_KEY||void 0};let r=await to(n,e,t),{record:o}=r;r.cached&&t.progress?.("target at its 24h cap \u2014 fetching the most recent stored run");let i;if(!t.noStream&&o.status==="running")try{i=(await ro(n,o.stream_url,t)).errorMessage}catch{t.progress?.("stream went quiet \u2014 switching to polling"),await jt(n,o.id,t)}else t.noStream&&o.status==="running"&&await jt(n,o.id,t);let s=await oo(n,o.id,t);if(s.status==="running")throw i?new R(`ora journey run failed: ${i}`):new R(`run ${o.id} is still executing \u2014 the ${t.noStream?"poll budget ran out":"stream ended"} before a terminal result. Check ${n}/api/journey/runs/${o.id} shortly`);return oe(s.contractVersion),{record:o,cached:r.cached,retryAfterMs:r.record.retry_after_ms,allowance:r.allowance,detail:s,engineError:i}}async function oo(e,t,n){let r=await ye(e,t);for(let o=0;o<3&&r.status==="running";o++)n.progress?.("finalizing\u2026"),await K(1500),r=await ye(e,t);return r}var $=U(D(),1);function Ke(e){if(!e)return{};let t=e.match(/https?:\/\/([^/\s]+)(\/\S*)?/i);return t?{host:t[1],path:t[2]??"/"}:{}}function Y(e){return/search/i.test(`${e.tool??""} ${e.action??""}`)}function io(e){if(Y(e))return"\u{1F50D}";let t=`${e.tool??""} ${e.action??""}`.toLowerCase();return/fetch|http|get/.test(t)?"\u{1F310}":/read|open|view/.test(t)?"\u{1F4C4}":"\u{1F310}"}function so(e,t){if(Y(e)){let c=e.input_display??String(e.input?.query??"search"),l=e.output_structured?.links?.length;return{id:e.id,kind:"search",icon:"\u{1F50D}",label:V(`"${c}"`,t),meta:l?`${l} results`:void 0,tone:"ok",notes:[],children:[]}}let{host:n,path:r}=Ke(e.input_display??String(e.input?.url??"")),o=e.status,i=o!=null&&o>=300&&o<400,s=!!e.is_error||o!=null&&o>=400,a;if(i)a=`\u21B3 ${o}`;else if(s)a=`\u2717 ${o??"error"}`;else{let c=["\u2713"];o&&c.push(String(o)),e.duration_ms&&c.push(`${(e.duration_ms/1e3).toFixed(1)}s`),a=c.join(" ")}return{id:e.id,kind:"fetch",icon:io(e),label:V(`${n??"?"}${r??""}`,t),meta:a,tone:i?"redirect":s?"error":"ok",notes:[],children:[]}}function be(e,t,n){let r=G(60,120),o=Math.min(52,Math.max(24,r-40)),i=Math.max(30,r-24),s={id:-1,kind:"intent",icon:"\u25C6",label:V(t,i),tone:"root",notes:[],children:[]},a=new Map,c=[],l,u,d;for(let g of e){if(g.type==="text"&&g.kind==="reasoning"){let h=(g.thinking??g.text??"").trim();h&&c.push(V(h,i));continue}if(g.type!=="tool_call")continue;let p=so(g,o);p.notes=c,c=[],a.set(g.id,p);let f=s;if(!Y(g)){let h=g.attribution?.referrer?.step_id,m=g.attribution?.kind,y=h!=null?a.get(h):void 0;y&&y!==p?f=y:m==="web_search"&&l?f=l:m==="previous_artifact"&&u&&(f=u)}f.children.push(p),Y(g)?l=p:u=p,d=p}return d&&!n&&(d.tone="active",d.meta="\u2026"),{root:s,looseNotes:c}}function we(e){let t=e.filter(o=>o.kind==="reasoning").length,n=e.filter(o=>o.type==="tool_call"&&Y(o)).length,r=[`${$.default.bold(String(e.length))} steps`];return t&&r.push(`${$.default.bold(String(t))} reasoning`),n&&r.push(`${$.default.bold(String(n))} search${n===1?"":"es"}`),r.join($.default.dim(" \xB7 "))}function ao(e){switch(e){case"root":return{frame:$.default.dim,ink:t=>$.default.bold(t)};case"active":return{frame:$.default.cyan,ink:t=>$.default.cyan($.default.bold(t))};case"redirect":return{frame:$.default.yellow,ink:$.default.yellow};case"error":return{frame:$.default.red,ink:$.default.red};default:return{frame:$.default.green,ink:$.default.green}}}var Bt=e=>$.default.dim(`(\u2026) ${e}`);function Ut(e,t){let{frame:n,ink:r}=ao(e.tone),i=`${e.icon} ${e.label}${e.meta?` ${e.meta}`:""}`.length+2,s=`${e.icon} ${r(e.label)}${e.meta?` ${$.default.dim(e.meta)}`:""}`,a=e.children.length>0,c=e.notes.map(Bt);return c.push(n(`\u256D${"\u2500".repeat(i)}\u256E`)),c.push(`${n(t?"\u2524":"\u2502")} ${s} ${n("\u2502")}`),c.push(n(a?`\u2570\u2500\u252C${"\u2500".repeat(i-2)}\u256F`:`\u2570${"\u2500".repeat(i)}\u256F`)),e.children.forEach((l,u)=>{let d=u===e.children.length-1,g=Ut(l,!0),p=l.notes.length+1;g.forEach((f,h)=>{let m;h===p?m=d?" \u2570\u2500\u2500":" \u251C\u2500\u2500":h<p?m=" \u2502 ":m=d?" ":" \u2502 ",c.push($.default.dim(m)+f)})}),c}function ve(e){let t=Ut(e.root,!1);return e.looseNotes.length&&(t.push(""),t.push(...e.looseNotes.map(Bt))),t}var Se=U(D(),1);var ee=class{rows=0;beat=0;bornAt=Date.now();ticker;live=!!process.stdout.isTTY;content=[];headline="";open(){this.live&&!this.ticker&&(this.ticker=setInterval(()=>this.pulse(),100))}draw(t,n){this.content=t,this.headline=n,this.repaint()}close(){this.ticker&&(clearInterval(this.ticker),this.ticker=void 0),this.live&&this.rows>0&&(process.stdout.write(`\x1B[${this.rows}A\r\x1B[0J`),this.rows=0)}banner(){let t=Se.default.cyan(Z[this.beat%Z.length]),n=Math.floor((Date.now()-this.bornAt)/1e3),r=`${this.headline} ${n}s`,o=Math.max(10,(process.stdout.columns??80)-6),i=r.length>o?`${r.slice(0,o-1)}\u2026`:r;return` ${t} ${Se.default.bold(i)}`}clamp(t){let n=Math.max(2,(process.stdout.rows??24)-3);if(t.length<=n)return t;let r=n-1,o=t.length-r;return[Se.default.dim(` \u22EF ${o} earlier line${o===1?"":"s"}`),...t.slice(-r)]}repaint(){if(!this.live)return;let t=[this.banner(),"",...this.clamp(this.content)],n=this.rows>0?`\x1B[${this.rows}A`:"";for(let r of t)n+=`\x1B[2K${r}
33
- `;t.length<this.rows&&(n+="\x1B[0J"),this.rows=t.length,process.stdout.write(n)}pulse(){!this.live||this.rows===0||(this.beat++,process.stdout.write(`\x1B[${this.rows}A\r\x1B[2K${this.banner()}\x1B[${this.rows}B\r`))}};var B={OK:0,RUN_FAILED:1,USAGE:2,API:3},co="public caps: 100 runs/24h per target \xB7 200 runs/24h per IP",lo="keyed caps: 1000 runs/24h per key \xB7 no per-target cap",uo={id:"cas-haiku",label:"Claude Code",variant:"Haiku 4.5",harness:"claude-agent-sdk",model:"claude-haiku-4-5",blurb:"Fast, frugal navigator \u2014 the CLI default."};function Ve(e){return console.error(w.default.red(`ax deep-journey: ${e}`)),B.API}function po(e,t){if(t==="failed")return w.default.red("\u2717 run failed");switch(e){case"satisfied":return w.default.green("\u2713 task satisfied");case"partial":return w.default.yellow("\u25D0 partially satisfied");case"unsatisfied":return w.default.red("\u2717 task not satisfied");default:return w.default.dim("\xB7 not gradable")}}function Ye(e){return`${e.label} \xB7 ${e.variant}`}function Jt(e){let n=e.action==="search"?e.search_query:e.url_host||e.url_path?`https://${e.url_host??""}${e.url_path??""}`:e.url;return{id:e.id,turn:e.turn??0,type:e.type,kind:e.type==="text"?"reasoning":void 0,text:e.text,thinking:e.text,tool:e.tool,action:e.action,input_display:n,status:e.status,duration_ms:e.duration_ms,attribution:e.attribution?{kind:e.attribution.kind,referrer:{step_id:e.attribution.referrer?.step_id??e.parent_id}}:void 0}}function Ft(e,t,n){return[` ${we(e)}`,"",...ve(be(e,t,n)).map(r=>` ${r}`)]}var mo=e=>e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e);function go(e){return e<.01?`$${e.toFixed(4)}`:e<1?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function ho(e){if(!e)return;let{input_tokens:t,output_tokens:n}=e;if(!(t==null&&n==null))return(t??0)+(n??0)}function fo(e){return(e?.trajectory?.steps??[]).filter(t=>t.action==="search").length}function Xe(e,t,n){return e>=t?w.default.green:e>=n?w.default.yellow:w.default.red}function yo(e){let t=e.run_signals,r=(e.trajectory?.steps??[]).filter(i=>i.type==="tool_call"&&(i.action==="fetch"||i.action==="api_call")),o=[];if(t?.answer_basis!=null){let i=Math.round(t.answer_basis.site_share*100);o.push({label:"answer from your site",pct:i,paint:Xe(i,70,40)})}if(t?.answer_efficiency!=null){let i=Math.round(t.answer_efficiency*100);o.push({label:"answer efficiency",pct:i,paint:Xe(i,70,30)})}if(r.length){let i=t?.link_following_rate??r.filter(a=>a.attribution?.kind==="previous_artifact").length/r.length,s=Math.round(i*100);o.push({label:"followed site links",pct:s,paint:Xe(s,70,35)})}return o}function bo(e,t=20,n=21){let r=Math.max(0,Math.min(t,Math.round(e.pct/100*t))),o=`${e.paint("\u25B0".repeat(r))}${w.default.dim("\u25B1".repeat(t-r))}`,i=`${e.pct}%`.padStart(4);return` ${w.default.dim(e.label.padEnd(n))} ${o} ${e.paint(w.default.bold(i))}`}function ze(e,t,n){let r=Math.max(0,t-e.length),o=Math.floor(r/2);return`${" ".repeat(o)}${n(e)}${" ".repeat(r-o)}`}function wo(e,t){let n=e.length;if(n===0)return null;let r=4,o=Math.min(t,100)-2,i=Math.floor((o-r*(n-1))/n);if(i<18)return null;let s=[],a=[],c=[],l=1;for(let g of e){s.push(ze(`${g.pct}%`,i,m=>g.paint(w.default.bold(m))));let p=i-2,f=Math.max(1,Math.min(p,Math.round(g.pct/100*p)));a.push(` ${g.paint("\u2594".repeat(f))}${w.default.dim("\u2594".repeat(p-f))} `);let h=T(g.label.toUpperCase(),i).map(m=>ze(m,i,w.default.dim));c.push(h),l=Math.max(l,h.length)}let u=g=>` ${g.join(" ".repeat(r))}`,d=["",u(s),u(a)];for(let g=0;g<l;g++)d.push(u(c.map(p=>p[g]??ze("",i,w.default.dim))));return d}function Ht(e,t){let n=t.filter(s=>s.n>0),r=n.reduce((s,a)=>s+a.n,0);if(!n.length||!r)return[];let o=Math.max(...n.map(s=>s.label.length)),i=["",` ${w.default.dim(e)}`];for(let s of n){let a=Math.round(s.n/r*100),c=Math.max(0,Math.min(20,Math.round(a/100*20))),l=`${w.default.dim("\u25B0".repeat(c))}${w.default.dim("\u25B1".repeat(20-c))}`;i.push(` ${w.default.dim(s.label.padEnd(o))} ${l} ${w.default.dim(`${a}%`.padStart(4))}`)}return i}function vo(e){return w.default.dim(` ${"\u2500".repeat(Math.min(e-4,52))}`)}function So(e,t){let n=e.run_signals,r=[];if(n?.reached_anchor!=null){let c=n.reached_anchor?w.default.green("\u2713 reached the site"):w.default.red("\u2717 never reached the site");r.push("",` ${c}`)}let o=yo(e);if(o.length){let c=wo(o,t);if(c)r.push(...c);else{r.push("");for(let l of o)r.push(bo(l))}}let i=n?.answer_basis;i&&i.sections_total>0&&r.push(...Ht("answer sources",[{label:"from this site",n:i.from_site},{label:"from external pages",n:i.from_external},{label:"from search results",n:i.from_search},{label:"from agent knowledge",n:i.from_memory}]));let a=(e.trajectory?.steps??[]).filter(c=>c.type==="tool_call"&&(c.action==="fetch"||c.action==="api_call"));if(a.length){let c=u=>{let d=u.attribution?.kind;return d==="previous_step"||d==="previous_artifact"?"previous_artifact":d==="web_search"?"web_search":d==="prior_knowledge"&&u.anchor_relation==="exact"&&(!u.url_path||u.url_path==="/")?"task_input":"prior_knowledge"},l={};for(let u of a){let d=c(u);l[d]=(l[d]??0)+1}r.push(...Ht("url discovery",[{label:"given in the task",n:l.task_input??0},{label:"followed a link",n:l.previous_artifact??0},{label:"found via web search",n:l.web_search??0},{label:"guessed the URL",n:l.prior_knowledge??0}]))}return r}function ko(e,t){let n=G(60,120),{detail:r}=e,o=r.result,i=["",vo(n),""];i.push(` ${po(r.verdict,r.status)} ${w.default.dim("\xB7")} ${w.default.dim(r.domain??t)}`);let s=[];r.step_count!=null&&s.push(`${r.step_count} steps`);let a=o?.run_signals?.search_count??fo(o);a&&s.push(`${a} search${a===1?"":"es"}`),o?.duration_ms!=null&&s.push(`${(o.duration_ms/1e3).toFixed(1)}s`);let c=ho(o);if(c!=null&&s.push(`${mo(c)} tokens`),o?.cost_usd!=null&&s.push(go(o.cost_usd)),s.length&&i.push(` ${w.default.dim(s.join(" \xB7 "))}`),o&&i.push(...So(o,n)),o?.insight?.summary){i.push("");for(let u of T(_(o.insight.summary),n-4))i.push(` ${u}`)}let l=o?.insight?.key_observations??[];if(l.length){i.push("",` ${w.default.bold("Observations")}`);for(let u of l){let[d,...g]=T(_(u),n-6);i.push(` ${w.default.cyan("\xB7")} ${d}`);for(let p of g)i.push(` ${p}`)}}return r.status==="failed"&&i.push("",w.default.dim(e.engineError?` Engine error: ${e.engineError} \u2014 re-running is free to try.`:" The run ended in an engine error; re-running is free to try.")),i.push("",w.default.dim(` For the 4-layer readiness audit, run: ax audit ${t}`)),i}async function Gt(e){let t=e.url.trim();if(!t)return console.error("ax deep-journey: a target URL or domain is required"),B.USAGE;let n=!e.json&&process.stderr.isTTY,r=e.task?.trim()||void 0,o=e.apiKey||process.env.ORA_PARTNER_API_KEY||process.env.ORA_SCAN_API_KEY||void 0;if(r&&e.intent!==void 0)return console.error("ax deep-journey: --task and --intent are mutually exclusive \u2014 a free-text task replaces the curated intent"),B.USAGE;if(r&&!o)return console.error("ax deep-journey: --task needs an ora partner API key \u2014 set ORA_PARTNER_API_KEY or pass --api-key (keys are issued by ora on request)"),B.USAGE;let i=e.intent,s,a=r??"journey";try{let[m,y]=await Promise.all([r?void 0:Lt(),Wt()]);if(m){if(i===void 0)i=m.defaultId;else if(!m.intents.some(z=>z.id===i))return console.error(`ax deep-journey: unknown intent "${i}". Available intents:
34
- ${m.intents.map(z=>` ${z.id.padEnd(12)} ${z.hint}`).join(`
35
- `)}`),B.USAGE;let M=m.intents.find(z=>z.id===i);a=(M?.template||M?.hint||M?.label||i||"journey").replace(/\{domain\}/g,t)}let C=y.agents.some(M=>M.harness==="claude-agent-sdk"&&/haiku/i.test(M.model))?y.agents:[uo,...y.agents],se=C.find(M=>M.harness==="claude-agent-sdk"&&/haiku/i.test(M.model))?.id??y.defaultId,ae=e.agent??se,ut=C.find(M=>M.id===ae);if(!ut)return console.error(`ax deep-journey: unknown agent "${ae}". Available agents:
36
- ${C.map(M=>` ${M.id.padEnd(12)} ${Ye(M)}`).join(`
37
- `)}`),B.USAGE;s=ut}catch(m){return Ve(m instanceof Error?m.message:String(m))}e.json||console.error(w.default.dim(o?lo:co));let c=n&&!e.noStream,l=new ee,u=[],d=`waking ${s.label}`,g=()=>l.draw(Ft(u,a,!1),d);c?(console.log(),console.log(` ${w.default.cyan("\u25B6")} ${w.default.bold(t)} ${w.default.dim("\xB7")} ${w.default.dim(Ye(s))} ${w.default.dim("\xB7")} ${w.default.dim(r?"custom task":i??"default")}`),console.log(),l.open(),g()):n&&k.start(`Sending ${Ye(s)} to ${t} (${r?`"${r}"`:i})`);let p=m=>{c?(d=m,g()):n&&k.update(m)},f;try{f=await Dt(t,{intentId:r?void 0:i,task:r,apiKey:o,harness:s.harness,model:s.model,noStream:e.noStream,progress:n?p:void 0,onTrajectory:c?m=>{u=m.map(Jt),g()}:void 0})}catch(m){return c?l.close():n&&k.stop(),m instanceof R?Ve(m.message):Ve(m instanceof Error?m.message:String(m))}if(c?l.close():n&&k.stop(),e.json)return console.log(JSON.stringify(f.detail,null,2)),f.detail.status==="failed"?B.RUN_FAILED:B.OK;f.cached?console.error(w.default.yellow(`This target hit its 24h cap \u2014 showing the most recent stored run${f.retryAfterMs?` (fresh run in ${qe(f.retryAfterMs)})`:""}.`)):f.allowance.remaining!==void 0&&f.allowance.limit!==void 0&&console.error(w.default.dim(`allowance: ${f.allowance.remaining} of ${f.allowance.limit} target runs left in the 24h window`));let h=(f.detail.result?.trajectory?.steps??[]).map(Jt);if(h.length){console.log();for(let m of Ft(h,a,!0))console.log(m)}for(let m of ko(f,t))console.log(m);return f.detail.status==="failed"?B.RUN_FAILED:B.OK}var S=U(D(),1);var ke=()=>G(60,120);function xo(e){if(e.type==="tool_call"){let t=e.input_display??e.summary??"";if(Y(e))return t?`searching ${V(t,40)}`:"searching\u2026";let{host:n}=Ke(t);return n?`fetching ${n}`:"fetching\u2026"}return e.type==="text"&&e.kind==="reasoning"?"deciding next step\u2026":e.type==="text"?"writing the answer\u2026":"working\u2026"}var Ao=e=>e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e);function $o(e){return e<.01?`$${e.toFixed(4)}`:e<1?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function _o(e,t){let n=e.outcome==="success",r=[];return e.num_turns!=null&&r.push(`${e.num_turns} turns`),e.duration_ms!=null&&r.push(`${(e.duration_ms/1e3).toFixed(1)}s`),t?.totalTokens!=null&&r.push(`${Ao(t.totalTokens)} tokens`),t?.costUsd!=null&&r.push($o(t.costUsd)),["",` ${S.default.dim("\u2500".repeat(Math.min(ke()-4,52)))}`,` ${n?S.default.green("\u2713"):S.default.red("\u2717")} ${S.default.bold(n?"completed":e.outcome)}${r.length?` ${S.default.dim(r.join(" \xB7 "))}`:""}`]}function Ro(e,t=22){let n=Math.min(100,Math.max(0,e)),r=Math.round(n/100*t);return(n>=70?S.default.green:n>=50?S.default.yellow:S.default.red)("\u2588".repeat(r))+S.default.dim("\u2591".repeat(t-r))}function Co(e){return e==="high"?S.default.red("\u25CF high "):e==="medium"?S.default.yellow("\u25CF medium"):e==="low"?S.default.dim("\u25CF low "):S.default.dim("\u25CF ")}function Eo(e){let t=[""];if(e.visibility_score!=null){let n=e.visibility_score,r=n>=70?S.default.green:n>=50?S.default.yellow:S.default.red,o=e.intent_satisfied?S.default.green("\u2713 intent satisfied"):S.default.yellow("\u2717 intent not satisfied");t.push(` ${S.default.bold("Visibility")} ${Ro(n)} ${r(S.default.bold(`${n}/100`))} ${o}`)}if(e.summary){t.push("");for(let n of T(e.summary,ke()-4))t.push(` ${S.default.dim(n)}`)}if(e.friction_points?.length){t.push("",` ${S.default.bold("Friction")}`);for(let n of e.friction_points){let[r,...o]=T(n,ke()-6);t.push(` ${S.default.yellow("\xB7")} ${r}`);for(let i of o)t.push(` ${i}`)}}if(e.recommendations?.length){t.push("",` ${S.default.bold("Recommendations")}`);for(let n of e.recommendations){t.push(` ${Co(n.priority)} ${S.default.bold(n.title)}`);for(let r of T(n.detail,ke()-8))t.push(` ${S.default.dim(r)}`)}}return t.push(""),t}function To(e){let t=e.insight??{};return JSON.stringify({runId:e.runId,intent:e.intent,domain:e.domain,harness:e.harness,model:e.result?.effective_model??e.result?.model,outcome:e.result?.outcome,durationMs:e.result?.duration_ms,numTurns:e.result?.num_turns,totalTokens:e.usage?.totalTokens,inputTokens:e.usage?.inputTokens,outputTokens:e.usage?.outputTokens,costUsd:e.usage?.costUsd,visibilityScore:t.visibility_score,intentSatisfied:t.intent_satisfied,taskSatisfied:t.task_satisfied,summary:t.summary,keyObservations:t.key_observations,frictionPoints:t.friction_points,recommendations:t.recommendations,journeyLayers:t.journey_layers,intentCategory:t.intent_category,steps:e.trajectory},null,2)}async function qt(e){let t={intent:e.intent,domain:e.domain,harness:e.harness,model:e.model};if(e.json)try{let s=await Fe(t);return process.stdout.write(`${To(s)}
38
- `),s.result?.outcome==="success"?0:1}catch(s){return console.error(`Journey failed: ${s instanceof Error?s.message:String(s)}`),2}let n=new ee,r=[],o=!1,i=()=>[` ${we(r)}`,"",...ve(be(r,e.intent,o)).map(s=>` ${s}`)];console.log(),console.log(` ${S.default.cyan("\u25B6")} ${e.domain?S.default.bold(e.domain):S.default.dim("(no domain)")} ${S.default.dim("\xB7")} ${S.default.dim(e.harness)}`),console.log(),n.open(),n.draw(i(),"waking the agent");try{let s=await Fe(t,{snapshot:a=>{r=a;let c=a[a.length-1];n.draw(i(),c?xo(c):"working")},finished:()=>{o=!0,n.draw(i(),"scoring the journey")}});n.close(),o=!0,s.trajectory.length&&(r=s.trajectory);for(let a of i())console.log(a);if(s.result)for(let a of _o(s.result,s.usage))console.log(a);if(s.insight)for(let a of Eo(s.insight))console.log(a);else s.result&&(console.log(S.default.dim(" (insight not available for this run)")),console.log());return s.result?.outcome==="success"?0:1}catch(s){return n.close(),console.error(`Journey failed: ${s instanceof Error?s.message:String(s)}`),2}}var xe=require("fs"),Ze=require("path"),te=U(D(),1);var Vt=require("crypto"),Po="https://ora.ai",L=class extends Error{};function Yt(e){return(e??process.env.ORA_API_URL??Po).replace(/\/+$/,"")}async function Qe(e){let t=Yt(e),n;try{n=await fetch(`${t}/.well-known/agent-skills/index.json`,{headers:{accept:"application/json"},signal:AbortSignal.timeout(15e3)})}catch(o){throw new L(`could not reach the skill registry at ${t}: ${o instanceof Error?o.message:String(o)}`)}if(!n.ok)throw new L(`skill registry answered HTTP ${n.status}`);let r=await n.json();if(!Array.isArray(r.skills))throw new L("skill registry index has no skills[]");return r.skills}function Kt(e){return`sha256:${(0,Vt.createHash)("sha256").update(e).digest("hex")}`}async function Xt(e,t){let n=Yt(t),r=await Qe(n),o=r.find(c=>c.name===e);if(!o){let c=r.map(l=>l.name).join(", ");throw new L(`unknown skill ${JSON.stringify(e)} - the registry has: ${c}`)}let i=o.url.startsWith("http")?o.url:`${n}${o.url}`,s;try{s=await fetch(i,{signal:AbortSignal.timeout(15e3)})}catch(c){throw new L(`could not fetch ${i}: ${c instanceof Error?c.message:String(c)}`)}if(!s.ok)throw new L(`skill fetch answered HTTP ${s.status} for ${i}`);let a=new Uint8Array(await s.arrayBuffer());if(o.digest&&Kt(a)!==o.digest)throw new L(`digest mismatch for ${e}: index says ${o.digest}, served bytes hash to ${Kt(a)} - refusing to use them`);return{entry:o,bytes:a}}var Io=".claude/skills";function Mo(e,t,n){let r=[],o="";for(let i of e.split(/\s+/))o&&`${o} ${i}`.length>t?(r.push(n+o),o=i):o=o?`${o} ${i}`:i;return o&&r.push(n+o),r}async function zt(e){try{if(!e.name){let r=await Qe();if(e.json)return process.stdout.write(`${JSON.stringify(r,null,2)}
39
- `),P.OK;console.log("");for(let o of r){let i=o.digest?te.default.dim(` ${o.digest.slice(0,19)}\u2026`):"";if(console.log(` ${te.default.bold(o.name)}${i}`),o.description)for(let s of Mo(o.description,76," "))console.log(te.default.dim(s));console.log("")}return console.log(te.default.dim(" Install one with: ax skill <name> --install")),console.log(""),P.OK}let{entry:t,bytes:n}=await Xt(e.name);if(e.install){let r=(0,Ze.join)(e.dir??Io,t.name);(0,xe.mkdirSync)(r,{recursive:!0});let o=(0,Ze.join)(r,"SKILL.md");return(0,xe.writeFileSync)(o,n),console.log(`Installed ${t.name} to ${o}`),t.digest&&console.log(te.default.dim(`verified ${t.digest}`)),P.OK}return process.stdout.write(n),P.OK}catch(t){let n=t instanceof Error?t.message:String(t);return console.error(`Skill command failed: ${n}`),t instanceof L&&n.includes("unknown skill")?P.USAGE:P.API}}var x=class extends Error{constructor(t,n){super(t,n),this.name="CdpError"}},Qt=1e4,Zt=5e3,tt=class e{socket;nextId=1;pending=new Map;handlers=new Map;closed=!1;closeReason=null;constructor(t){this.socket=t,t.addEventListener("message",n=>{this.dispatch(String(n.data))}),t.addEventListener("close",()=>{this.fail("the browser closed the DevTools connection")}),t.addEventListener("error",()=>{this.fail("the DevTools connection errored")})}static async open(t){let n=new WebSocket(t);return await new Promise((r,o)=>{let i=setTimeout(()=>{o(new x(`timed out connecting to ${t}`))},Zt);n.addEventListener("open",()=>{clearTimeout(i),r()},{once:!0}),n.addEventListener("error",()=>{clearTimeout(i),o(new x(`could not connect to ${t}`))},{once:!0})}),new e(n)}dispatch(t){let n;try{n=JSON.parse(t)}catch{return}let r=n.id;if(typeof r=="number"){let a=this.pending.get(r);if(!a)return;this.pending.delete(r),clearTimeout(a.timer);let c=n.error;c?a.reject(new x(c.message??"CDP call failed")):a.resolve(n.result??{});return}let o=n.method;if(typeof o!="string")return;let i=typeof n.sessionId=="string"?n.sessionId:"",s=n.params??{};for(let a of this.handlers.get(`${i}\0${o}`)??[])try{a(s)}catch{}}fail(t){if(!this.closed){this.closed=!0,this.closeReason=t;for(let[,n]of this.pending)clearTimeout(n.timer),n.reject(new x(t));this.pending.clear()}}send(t,n={},r={}){if(this.closed)return Promise.reject(new x(this.closeReason??"the connection is closed"));let o=this.nextId++,i=r.timeoutMs??Qt;return new Promise((s,a)=>{let c=setTimeout(()=>{this.pending.delete(o),a(new x(`${t} timed out after ${i}ms`))},i);this.pending.set(o,{resolve:s,reject:a,timer:c});let l={id:o,method:t,params:n};r.sessionId&&(l.sessionId=r.sessionId);try{this.socket.send(JSON.stringify(l))}catch(u){this.pending.delete(o),clearTimeout(c),a(new x(`could not send ${t}`,{cause:u}))}})}on(t,n,r){let o=`${t}\0${n}`,i=this.handlers.get(o)??new Set;return i.add(r),this.handlers.set(o,i),()=>{i.delete(r)}}close(){this.closed=!0;try{this.socket.close()}catch{}}};async function rt(e,t=Zt){if(e.startsWith("ws://")||e.startsWith("wss://"))return{webSocketDebuggerUrl:e,product:""};let n=e.startsWith("http://")||e.startsWith("https://")?e.replace(/\/+$/,""):`http://${e.replace(/\/+$/,"")}`,r;try{r=await fetch(`${n}/json/version`,{signal:AbortSignal.timeout(t)})}catch(i){throw new x(`no debuggable Chrome answered at ${n}`,{cause:i})}if(!r.ok)throw new x(`${n}/json/version returned HTTP ${r.status}`);let o=await r.json().catch(()=>null);if(!o?.webSocketDebuggerUrl)throw new x(`${n}/json/version carried no webSocketDebuggerUrl`);return{webSocketDebuggerUrl:o.webSocketDebuggerUrl,product:o.Browser??""}}var Ae=class e{connection;product;constructor(t,n){this.connection=t,this.product=n}static async connect(t){let n=await tt.open(t.webSocketDebuggerUrl),r=t.product;if(!r){let o=await n.send("Browser.getVersion").catch(()=>({}));r=typeof o.product=="string"?o.product:""}return new e(n,r.replace(/^(?:Headless)?Chrome\//i,""))}async newContext(t){let{browserContextId:n}=await this.connection.send("Target.createBrowserContext",{disposeOnDetach:!0}),{targetId:r}=await this.connection.send("Target.createTarget",{url:"about:blank",browserContextId:n}),{sessionId:o}=await this.connection.send("Target.attachToTarget",{targetId:r,flatten:!0}),i=new nt(this.connection,o,n,t.entryUrl);return await i.prepare(t.initScripts??[],t.viewport),i}close(){this.connection.close()}},Oo=8,No=1024*1024,jo=new Set(["Image","Media","Font"]),nt=class{connection;sessionId;browserContextId;entryHost;currentUrl="about:blank";viewport=null;domContentFired=!1;loadFired=!1;documentResponses=new Map;scripts=[];scriptsStarted=0;pendingScriptRequests=new Map;constructor(t,n,r,o){this.connection=t,this.sessionId=n,this.browserContextId=r,this.entryHost=et(o)}async prepare(t,n){await this.send("Page.enable"),await this.send("Runtime.enable"),await this.send("Network.enable"),await this.send("Fetch.enable",{patterns:[{urlPattern:"*"}]}),this.connection.on(this.sessionId,"Fetch.requestPaused",r=>{this.onRequestPaused(r)}),n&&(this.viewport=n,await this.send("Emulation.setDeviceMetricsOverride",{width:n.width,height:n.height,deviceScaleFactor:1,mobile:!1})),this.connection.on(this.sessionId,"Page.domContentEventFired",()=>{this.domContentFired=!0}),this.connection.on(this.sessionId,"Page.loadEventFired",()=>{this.loadFired=!0}),this.connection.on(this.sessionId,"Page.frameNavigated",r=>{let o=r.frame;!o||o.parentId||typeof o.url=="string"&&(this.currentUrl=o.url)}),this.connection.on(this.sessionId,"Network.responseReceived",r=>{this.onResponse(r)}),this.connection.on(this.sessionId,"Network.loadingFinished",r=>{this.onLoadingFinished(r)});for(let r of t)await this.send("Page.addScriptToEvaluateOnNewDocument",{source:r})}send(t,n={},r){return this.connection.send(t,n,{sessionId:this.sessionId,timeoutMs:r})}onRequestPaused(t){let n=t.requestId;if(typeof n!="string")return;(jo.has(String(t.resourceType))?this.send("Fetch.failRequest",{requestId:n,errorReason:"BlockedByClient"}):this.send("Fetch.continueRequest",{requestId:n})).catch(()=>{})}onResponse(t){let n=t.type,r=t.requestId,o=t.response;if(typeof r!="string"||!o)return;if(n==="Document"){let a=typeof t.frameId=="string"?t.frameId:"";this.documentResponses.set(a,{status:typeof o.status=="number"?o.status:0,headers:Lo(o.headers??{})});return}if(n!=="Script"||this.scriptsStarted>=Oo)return;let i=typeof o.url=="string"?o.url:"",s=et(i);s&&(s!==this.entryHost&&s!==et(this.currentUrl)||(this.scriptsStarted++,this.pendingScriptRequests.set(r,i)))}onLoadingFinished(t){let n=t.requestId;if(typeof n!="string")return;let r=this.pendingScriptRequests.get(n);r!==void 0&&(this.pendingScriptRequests.delete(n),this.send("Network.getResponseBody",{requestId:n}).then(o=>{let i=typeof o.body=="string"?o.body:"",s=o.base64Encoded===!0?Buffer.from(i,"base64").toString("utf8"):i;this.scripts.push({url:r,body:s.slice(0,No)})}).catch(()=>{}))}async goto(t,n){this.domContentFired=!1,this.loadFired=!1;let r=await this.send("Page.navigate",{url:t},n),o=r.errorText;if(typeof o=="string"&&o.length>0)throw new x(`navigating to ${t} failed: ${o}`);let i=typeof r.frameId=="string"?r.frameId:"";return await this.waitFor(()=>this.domContentFired,n,`${t} never reached DOMContentLoaded`),this.currentUrl=await this.readLocation(t),this.documentResponses.get(i)??this.documentResponses.get("")??null}async waitForLoad(t){await this.waitFor(()=>this.loadFired,t,"load").catch(()=>{})}async waitFor(t,n,r){let o=Date.now()+n;for(;!t();){if(Date.now()>=o)throw new x(`timed out waiting for ${r}`);await new Promise(i=>setTimeout(i,25))}}async readLocation(t){let n=await this.evaluate("location.href",2e3).catch(()=>null);return typeof n=="string"&&n.length>0?n:t}async evaluate(t,n=Qt){let r=await this.send("Runtime.evaluate",{expression:t,awaitPromise:!0,returnByValue:!0},n),o=r.exceptionDetails;if(o)throw new x(o.exception?.description??o.text??"evaluation threw");return r.result?.value}async content(){return await this.evaluate("document.documentElement ? document.documentElement.outerHTML : ''").catch(()=>"")??""}async inlineScripts(){return await this.evaluate('Array.from(document.querySelectorAll("script:not([src])")).map(function (s) { return s.textContent || ""; }).join("\\n")').catch(()=>"")??""}url(){return this.currentUrl}collectedScripts(){return this.scripts.slice()}viewportSize(){return this.viewport}async screenshot(t,n){try{let o=(await this.send("Page.captureScreenshot",{format:"jpeg",quality:t,captureBeyondViewport:!1},n)).data;return typeof o!="string"||o.length===0?null:Buffer.from(o,"base64")}catch{return null}}async close(){await this.connection.send("Target.disposeBrowserContext",{browserContextId:this.browserContextId}).catch(()=>{})}};function Lo(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.toLowerCase(),i=r.split(`
40
- `).map(s=>s.trim()).filter(s=>s.length>0).join(", ");t[o]=t[o]===void 0?i:`${t[o]}, ${i}`}return t}function et(e){try{return new URL(e).host}catch{return""}}var Wo=new Set([2,3]),Do=8192,Bo=864e10;function Uo(e){if(typeof e!="string")return null;let t=e.trim();if(t.length===0||t.length>Do)return null;let n;try{n=Buffer.from(t,"base64")}catch{return null}if(n.length<=69||!Wo.has(n[0])||n.readUInt32BE(65)!==n.length-69)return null;let o;try{o=JSON.parse(n.subarray(69).toString("utf8"))}catch{return null}if(!o||typeof o!="object")return null;let i=o,s=i.origin,a=i.feature,c=i.expiry;return typeof s!="string"||typeof a!="string"||typeof c!="number"||!Number.isFinite(c)||c<0||c>Bo?null:{origin:s,feature:a,expiry:c,isSubdomain:i.isSubdomain===!0,isThirdParty:i.isThirdParty===!0}}function Jo(e){return e.toLowerCase().replace(/[^a-z]/g,"").includes("modelcontext")}function Fo(e,t,n){let r,o;try{r=new URL(e),o=new URL(t)}catch{return!1}if(r.protocol!==o.protocol)return!1;let i=r.hostname.toLowerCase(),s=o.hostname.toLowerCase();return i===s?!0:n&&s.endsWith(`.${i}`)}function en(e,t,n){let r=e.map(i=>i.trim()).filter(i=>i.length>0);if(r.length===0)return null;let o=null;for(let i of r){let s=Uo(i);if(!s)continue;let a=Jo(s.feature),c=s.expiry*1e3>n.getTime(),l=Fo(s.origin,t,s.isSubdomain),u=a&&c&&l,d=u?3:a?2:1;(!o||d>o.rank)&&(o={parsed:s,valid:u,rank:d})}return o?{present:!0,valid:o.valid,origin:o.parsed.origin,feature:o.parsed.feature,expiresAt:new Date(o.parsed.expiry*1e3).toISOString()}:{present:!0,valid:!1}}function tn(e){return e?e.split(",").map(t=>t.trim()).filter(t=>t.length>0):[]}var ot="capture-incomplete:";function Ho(e){return e.imperative!==null||e.polyfillPackages.length>0}function nn(e){return e.blocked?"blocked":e.loadError?"load-error":e.toolCount>0?e.nativeApi||e.originTrialValid||e.declarativeToolCount>0?"active":"testing-only":e.nativeApi?"api-empty":e.shimTakenOver||Ho(e.staticSignals)?"declared-inactive":"absent"}function rn(e,t){switch(e){case"blocked":return"waf-blocked";case"load-error":return"unreachable";case"active":case"testing-only":{let n=t.filter(r=>r.via==="imperative");return n.length>0&&n.every(r=>!r.hasExecute)?"stub-only":"ok"}case"api-empty":case"declared-inactive":case"absent":return"no-tools";default:return e}}var on={"shared-experience":30,"task-completion":25,"tool-quality":25,trust:20},it={"page-experience":{title:"Page experience",category:"shared-experience",weight:20,docSlug:"page-experience"},"human-parity":{title:"Human parity",category:"shared-experience",weight:10,docSlug:"human-parity"},"tool-selection":{title:"Tool selection",category:"task-completion",weight:15,docSlug:"tool-selection"},"coverage-vs-site-type":{title:"Coverage vs. site type",category:"task-completion",weight:10,docSlug:"coverage-vs-site-type"},"schema-validity":{title:"Schema validity",category:"tool-quality",weight:4,docSlug:"schema-validity"},"schema-quality":{title:"Schema quality",category:"tool-quality",weight:4,docSlug:"schema-quality"},"description-quality":{title:"Description quality",category:"tool-quality",weight:5,docSlug:"description-quality"},"stub-detection":{title:"Stub detection",category:"tool-quality",weight:4,docSlug:"stub-detection"},"canonical-entry-point":{title:"Canonical entry point",category:"tool-quality",weight:3,docSlug:"canonical-entry-point"},"naming-quality":{title:"Naming quality",category:"tool-quality",weight:2,docSlug:"naming-quality"},"registration-errors":{title:"Registration errors",category:"tool-quality",weight:2,docSlug:"registration-errors"},"registration-timing":{title:"Registration timing",category:"tool-quality",weight:1,docSlug:"registration-timing"},"annotations-present":{title:"Annotations present",category:"trust",weight:6,docSlug:"annotations-present"},"annotation-mismatch":{title:"Annotation mismatch",category:"trust",weight:6,docSlug:"annotation-mismatch"},"injection-surface":{title:"Injection surface",category:"trust",weight:4,docSlug:"injection-surface"},"untrusted-content-hint":{title:"Untrusted content hint",category:"trust",weight:4,docSlug:"untrusted-content-hint"}},X="1";function Go(e,t,n){return!!(t["cf-mitigated"]==="challenge"||e===403&&n.includes("cf-browser-verification")||e===503&&n.includes("challenge-platform"))}function sn(e,t,n){return!!(Go(e,t,n)||t["x-vercel-mitigated"]==="challenge"||"x-vercel-challenge-token"in t||n.includes("Vercel Security Checkpoint")||n.includes("vercel-challenge")||e===429&&n.length<2e3||e===403&&(n.includes("Access Denied")||n.includes("Bot Protection")))}var qo=100,cn=4096,Ko=32768,Vo=50,Yo=200,an="__oraWebmcpCapture",ln=`(function () {
18
+ `)}:null}async function Po(e,t,n,r,o){let s=n.startsWith("http")?n:`${e}${n}`,i=Y(o),a=await fetch(s,{headers:{authorization:`Bearer ${t}`,accept:"text/event-stream"},signal:i.signal});if(!a.ok||!a.body)throw i.disarm(),new Error(`ora run stream failed (${a.status})`);let c=new TextDecoder,l={steps:[],trajectory:[]},u="";try{e:for await(let d of a.body){i.poke(),u=`${u}${c.decode(d,{stream:!0})}`.replace(/\r\n?/g,`
19
+ `);let h=u.indexOf(`
20
+
21
+ `);for(;h!==-1;){let m=ot(u.slice(0,h));if(u=u.slice(h+2),h=u.indexOf(`
22
+
23
+ `),!m)continue;let f;try{f=JSON.parse(m.data)}catch{continue}if(Oo(l,m.event,f,r),l.summary&&l.insight)break e}}}catch(d){throw i.tripped()?new Error(`ora run stream timed out after ${o}ms of silence`):d}finally{i.disarm(),a.body.cancel().catch(()=>{})}return l}function Oo(e,t,n,r){switch(t){case"trajectory":{let o=n.steps;Array.isArray(o)&&(e.trajectory=o,r.snapshot?.(e.trajectory));return}case"step":{let o=n.step;o&&(e.steps.push(o),r.step?.(o,Number(n.seq??e.steps.length)));return}case"result":{let o=n.result;o&&(e.summary=o,r.finished?.(o));return}case"insight":{let o=n.insight;o&&(e.insight=o,r.scored?.(o));return}default:return}}async function Io(e,t,n){for(let r=0;;r++){let o;try{let s=await fetch(`${e}/experiment/v1/runs?pageSize=50`,{headers:{authorization:`Bearer ${t}`}});if(!s.ok)return;o=(await s.json()).results?.find(a=>a.id===n)}catch{return}if(!o)return;if(o.total_tokens!=null||o.cost_usd!=null)return{totalTokens:o.total_tokens??void 0,inputTokens:o.input_tokens??void 0,outputTokens:o.output_tokens??void 0,cacheReadTokens:o.cache_read_tokens??void 0,cacheCreationTokens:o.cache_creation_tokens??void 0,costUsd:o.cost_usd??void 0};if(r>0)return;await z(1200)}}async function st(e,t={}){let n=(e.baseUrl??process.env.ORA_PLATFORM_URL??tn).replace(/\/+$/,""),r=e.apiKey??process.env.ORA_API_KEY;if(!r)throw new Error("Missing ORA_API_KEY. Set it in your environment or a local .env file (see .env.example).");let o=await Ce(n,r),s=await Co(n,o,e),i={runId:s.runId,intent:e.intent,domain:e.domain,harness:e.harness};if(s.status==="succeeded"&&!s.streamUrl)return{...i,steps:[],trajectory:[]};t.opened?.(s.runId);let a=await Po(n,o,s.streamUrl??`/experiment/v1/runs/${s.runId}/stream`,t,e.idleMs??_o),c=a.summary?await Io(n,o,s.runId):void 0;return{...i,result:a.summary,insight:a.insight,usage:c,steps:a.steps,trajectory:a.trajectory}}var k=class extends Error{constructor(n,r){super(r);this.code=n;this.name="ProtocolError"}code},S={frameTooShort:"FRAME_TOO_SHORT",frameTooLarge:"FRAME_TOO_LARGE",frameLengthMismatch:"FRAME_LENGTH_MISMATCH",unknownFrameType:"UNKNOWN_FRAME_TYPE",badJson:"BAD_JSON",badPayload:"BAD_PAYLOAD",handshakeTimeout:"HANDSHAKE_TIMEOUT",handshakeProtocol:"HANDSHAKE_PROTOCOL",maxStreams:"MAX_STREAMS",streamClosed:"STREAM_CLOSED",streamReset:"STREAM_RESET",forwardError:"FORWARD_ERROR",connectionClosed:"CONNECTION_CLOSED",superseded:"SUPERSEDED",timeout:"TIMEOUT"};var Z=9,fe=64*1024,Q=0,ie=(c=>(c[c.Hello=1]="Hello",c[c.HelloAck=2]="HelloAck",c[c.Open=16]="Open",c[c.Headers=17]="Headers",c[c.Data=18]="Data",c[c.End=19]="End",c[c.Reset=20]="Reset",c[c.Goaway=32]="Goaway",c))(ie||{}),Mo=new Set(Object.values(ie).filter(e=>typeof e=="number"));function rn(e,t=fe){if(e.payload.byteLength>t)throw new k(S.frameTooLarge,`frame payload ${e.payload.byteLength} exceeds max ${t}`);let n=new Uint8Array(Z+e.payload.byteLength),r=new DataView(n.buffer);return r.setUint8(0,e.type),r.setUint32(1,e.streamId,!1),r.setUint32(5,e.payload.byteLength,!1),n.set(e.payload,Z),n}function on(e,t=fe){if(e.byteLength<Z)throw new k(S.frameTooShort,`frame is ${e.byteLength} bytes, header alone is ${Z}`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=n.getUint8(0);if(!Mo.has(r))throw new k(S.unknownFrameType,`unknown frame type 0x${r.toString(16)}`);let o=n.getUint32(1,!1),s=n.getUint32(5,!1);if(s>t)throw new k(S.frameTooLarge,`declared payload ${s} exceeds max ${t}`);if(e.byteLength!==Z+s)throw new k(S.frameLengthMismatch,`declared payload ${s} but message carries ${e.byteLength-Z}`);return{type:r,streamId:o,payload:e.subarray(Z)}}var an="ora-tunnel.v1",sn=fe,Lo=new TextEncoder,No=new TextDecoder,ye=class{constructor(t=fe){this.maxFrame=t}maxFrame;subprotocol=an;encode(t){return rn(t,this.capFor(t.type))}decode(t){let n=on(t,Math.max(this.maxFrame,sn)),r=this.capFor(n.type);if(n.payload.byteLength>r)throw new k(S.frameTooLarge,`payload ${n.payload.byteLength} exceeds max ${r} for frame type 0x${n.type.toString(16)}`);return n}encodeJson(t,n,r){return this.encode({type:t,streamId:n,payload:Lo.encode(JSON.stringify(r))})}decodeJson(t,n){let r;try{r=JSON.parse(No.decode(t.payload))}catch{throw new k(S.badJson,"frame payload is not valid JSON")}let o=n.safeParse(r);if(!o.success)throw new k(S.badPayload,o.error.message);return o.data}capFor(t){return t===18?this.maxFrame:sn}};var cn=1e4;function ln(e,t,n,r,o){return new Promise((s,i)=>{let a=!1,c=u=>{a||(a=!0,clearTimeout(l),u())},l=setTimeout(()=>{c(()=>{e.close(1002,S.handshakeTimeout),i(new k(S.handshakeTimeout,`no handshake frame within ${o}ms`))})},o);l.unref?.(),e.onError(u=>c(()=>i(u))),e.onClose((u,d)=>c(()=>i(new k(S.connectionClosed,`connection closed during handshake (${u}${d?`: ${d}`:""})`)))),e.onMessage(u=>{c(()=>{try{let d=t.decode(u);if(d.streamId!==Q||d.type!==n)throw new k(S.handshakeProtocol,`expected handshake frame 0x${n.toString(16)}, got 0x${d.type.toString(16)} on stream ${d.streamId}`);s(t.decodeJson(d,r))}catch(d){e.close(1002,S.handshakeProtocol),i(d)}})})})}var U=class extends Error{};function te(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new U(`${t}: expected object`);return e}function ee(e,t,n=0,r=Number.POSITIVE_INFINITY){if(typeof e!="string")throw new U(`${t}: expected string`);if(e.length<n)throw new U(`${t}: expected at least ${n} characters`);if(e.length>r)throw new U(`${t}: expected at most ${r} characters`);return e}function ae(e,t,n,r=Number.POSITIVE_INFINITY){if(typeof e!="number"||!Number.isInteger(e))throw new U(`${t}: expected integer`);if(e<n||e>r)throw new U(`${t}: expected ${n}..${r}`);return e}function un(e,t){if(e===void 0)return{};let n={};for(let[r,o]of Object.entries(te(e,t)))if(typeof o=="string")n[r]=o;else if(Array.isArray(o)&&o.every(s=>typeof s=="string"))n[r]=o;else throw new U(`${t}.${r}: expected string or string[]`);return n}function ce(e){return{safeParse(t){try{return{success:!0,data:e(t)}}catch(n){if(n instanceof U)return{success:!1,error:{message:n.message}};throw n}}}}function dn(e,t){let n=te(e,t);if(n.protocol!=="http")throw new U(`${t}.protocol: expected "http"`);return{protocol:"http",host:ee(n.host,`${t}.host`,1),port:ae(n.port,`${t}.port`,1,65535)}}var Ka=ce(e=>dn(e,"target")),Ya=ce(e=>{let t=te(e,"hello");return{agentVersion:ee(t.agentVersion,"hello.agentVersion",1,64),target:dn(t.target,"hello.target"),maxStreams:t.maxStreams===void 0?32:ae(t.maxStreams,"hello.maxStreams",1,256)}}),pn=ce(e=>{let t=te(e,"helloAck");return{tunnelId:ee(t.tunnelId,"helloAck.tunnelId",1),heartbeatMs:ae(t.heartbeatMs,"helloAck.heartbeatMs",1),maxStreams:ae(t.maxStreams,"helloAck.maxStreams",1),maxFrame:ae(t.maxFrame,"helloAck.maxFrame",1)}}),mn=ce(e=>{let t=te(e,"open"),n=ee(t.path,"open.path");if(!n.startsWith("/"))throw new U('open.path: expected a path starting with "/"');return{method:ee(t.method,"open.method",1,16),path:n,headers:un(t.headers,"open.headers")}}),hn=ce(e=>{let t=te(e,"responseHeaders");return{status:ae(t.status,"responseHeaders.status",100,599),headers:un(t.headers,"responseHeaders.headers")}});function gn(e){return ce(t=>{let n=te(t,e);return{code:ee(n.code,`${e}.code`,1,64),message:n.message===void 0?"":ee(n.message,`${e}.message`,0,1024)}})}var fn=gn("reset"),yn=gn("goaway");var Pe=class{constructor(t,n,r,o){this.id=t;this.codec=n;this.writer=r;this.onFinalized=o}id;codec;writer;onFinalized;localEnded=!1;remoteEnded=!1;resetPayload=null;handlers={};get isFinalized(){return this.resetPayload!==null||this.localEnded&&this.remoteEnded}setHandlers(t){Object.assign(this.handlers,t)}sendData(t){this.assertWritable();let n=this.codec.maxFrame;for(let r=0;r<t.byteLength;r+=n)this.writer.writeFrame(this.codec.encode({type:18,streamId:this.id,payload:t.subarray(r,Math.min(r+n,t.byteLength))}))}sendHeaders(t){this.assertWritable(),this.writer.writeFrame(this.codec.encodeJson(17,this.id,t))}sendEnd(){this.localEnded||this.resetPayload||(this.localEnded=!0,this.writer.writeFrame(this.codec.encode({type:19,streamId:this.id,payload:new Uint8Array(0)})),this.maybeFinalize())}sendReset(t,n=""){if(this.resetPayload)return;let r={code:t,message:n};this.resetPayload=r,this.writer.writeFrame(this.codec.encodeJson(20,this.id,r)),this.handlers.onReset?.(r),this.onFinalized(this)}receive(t){if(!this.resetPayload)switch(t.type){case 17:this.handlers.onHeaders?.(this.codec.decodeJson(t,hn));return;case 18:if(this.remoteEnded)return;this.handlers.onData?.(t.payload);return;case 19:if(this.remoteEnded)return;this.remoteEnded=!0,this.handlers.onEnd?.(),this.maybeFinalize();return;case 20:{let n=this.codec.decodeJson(t,fn);this.resetPayload=n,this.handlers.onReset?.(n),this.onFinalized(this);return}default:throw new k(S.badPayload,`frame type 0x${t.type.toString(16)} is not valid on an open stream`)}}failLocally(t){this.resetPayload||(this.resetPayload=t,this.handlers.onReset?.(t),this.onFinalized(this))}assertWritable(){if(this.resetPayload)throw new k(S.streamReset,`stream ${this.id} was reset (${this.resetPayload.code})`);if(this.localEnded)throw new k(S.streamClosed,`stream ${this.id} already ended locally`)}maybeFinalize(){this.localEnded&&this.remoteEnded&&this.onFinalized(this)}};var Oe=class{constructor(t,n){this.socket=t;this.opts=n}socket;opts;streams=new Map;nextStreamId=1;goingAway=!1;closed=!1;start(){this.socket.onMessage(t=>this.handleMessage(t)),this.socket.onClose((t,n)=>this.teardown(new k(S.connectionClosed,`connection closed (${t}${n?`: ${n}`:""})`))),this.socket.onError(t=>this.teardown(new k(S.connectionClosed,t.message)))}get activeStreamCount(){return this.streams.size}openStream(t){if(this.closed||this.goingAway)throw new k(S.connectionClosed,"connection is closed or draining");if(this.streams.size>=this.opts.maxStreams)throw new k(S.maxStreams,`stream cap ${this.opts.maxStreams} reached`);let n=this.createStream(this.nextStreamId);return this.nextStreamId+=2,this.socket.send(this.opts.codec.encodeJson(16,n.id,t)),n}goaway(t,n=""){this.closed||this.goingAway||(this.goingAway=!0,this.socket.send(this.opts.codec.encodeJson(32,Q,{code:t,message:n})))}close(t,n){this.socket.close(t,n)}handleMessage(t){let n;try{n=this.opts.codec.decode(t),this.dispatch(n)}catch(r){if(r instanceof k){this.goaway(r.code,r.message),this.close(1002,r.code),this.teardown(r);return}throw r}}dispatch(t){if(t.streamId===Q){t.type===32&&(this.goingAway=!0,this.opts.onGoaway?.(this.opts.codec.decodeJson(t,yn)));return}if(t.type===16){this.handleOpen(t);return}let n=this.streams.get(t.streamId);if(!n){t.type!==19&&t.type!==20&&this.socket.send(this.opts.codec.encodeJson(20,t.streamId,{code:S.streamClosed,message:"unknown stream"}));return}n.receive(t)}handleOpen(t){if(!this.opts.onOpen){this.socket.send(this.opts.codec.encodeJson(20,t.streamId,{code:S.badPayload,message:"this side does not accept streams"}));return}if(this.goingAway)return;let n=this.opts.codec.decodeJson(t,mn);if(this.streams.size>=this.opts.maxStreams){this.socket.send(this.opts.codec.encodeJson(20,t.streamId,{code:S.maxStreams,message:`stream cap ${this.opts.maxStreams} reached`}));return}let r=this.createStream(t.streamId);this.opts.onOpen(r,n)}createStream(t){let n={writeFrame:o=>this.socket.send(o)},r=new Pe(t,this.opts.codec,n,o=>this.streams.delete(o.id));return this.streams.set(t,r),r}teardown(t){if(!this.closed){this.closed=!0;for(let n of[...this.streams.values()])n.failLocally({code:t.code,message:t.message});this.streams.clear(),this.opts.onConnectionClosed?.(t)}}};var Ie=class{buffered=[];pending=null;ended=!1;error=null;push(t){if(!(this.ended||this.error)){if(this.pending){let n=this.pending;this.pending=null,n.resolve({value:t,done:!1});return}this.buffered.push(t)}}end(){if(!(this.ended||this.error)&&(this.ended=!0,this.pending&&this.buffered.length===0)){let t=this.pending;this.pending=null,t.resolve({value:void 0,done:!0})}}fail(t){if(!(this.ended||this.error)&&(this.error=t,this.pending)){let n=this.pending;this.pending=null,n.reject(t)}}[Symbol.asyncIterator](){return{next:()=>this.buffered.length>0?Promise.resolve({value:this.buffered.shift(),done:!1}):this.error?Promise.reject(this.error):this.ended?Promise.resolve({value:void 0,done:!0}):new Promise((t,n)=>{this.pending={resolve:t,reject:n}})}}};function bn(e){let t=new Ie;return e.setHandlers({onData:n=>t.push(Uint8Array.from(n)),onEnd:()=>t.end(),onReset:n=>t.fail(new k(S.streamReset,`${n.code}: ${n.message}`))}),t}async function wn(e,t){try{for await(let n of t)e.sendData(n);e.sendEnd()}catch(n){throw e.sendReset(S.forwardError,n instanceof Error?n.message:String(n)),n}}var be=class{constructor(t){this.opts=t}opts;mux=null;async start(){if(this.mux)throw new Error("connector already started");let{socket:t,codec:n,hello:r}=this.opts,o=ln(t,n,2,pn,this.opts.handshakeTimeoutMs??cn);t.send(n.encodeJson(1,Q,r));let s=await o;return this.mux=new Oe(t,{codec:n,maxStreams:s.maxStreams,onOpen:(i,a)=>{this.serve(i,a)},onGoaway:this.opts.onGoaway,onConnectionClosed:this.opts.onConnectionClosed}),this.mux.start(),s}get activeStreamCount(){return this.mux?.activeStreamCount??0}close(t,n){(this.mux??this.opts.socket).close(t,n)}async serve(t,n){try{let r=await this.opts.forwarder.forward({method:n.method,path:n.path,headers:n.headers,body:bn(t)});t.sendHeaders({status:r.status,headers:r.headers}),await wn(t,r.body)}catch(r){try{t.sendReset(S.forwardError,r instanceof Error?r.message:String(r))}catch{}}}};var at="tunnels:write + tunnels:connect",ct=[`--tunnel ora needs ORA_API_KEY: an ora platform key (ora_sk_...) with the ${at} scopes.`,"Create one at https://agentfront.sh (API keys), export it or put it in a local .env,","or bring your own tunnel instead: --tunnel-cmd 'ngrok http 3000 --log stdout'"].join(`
24
+ `),jo=1,Uo=32,it=()=>new E("interrupted before the tunnel was ready");function Do(e){let t;try{t=new URL(e.includes("://")?e:`http://${e}`)}catch{throw new E(`not a local target: ${JSON.stringify(e)}`)}if(t.protocol!=="http:")throw new E(`--tunnel ora forwards plain http only; ${t.protocol}// targets are not supported`);let n=t.hostname.replace(/^\[(.*)\]$/,"$1"),r=n==="localhost"?"127.0.0.1":n,o=t.port?Number(t.port):80;return{host:r,port:o}}async function An(e,t={}){let n=Do(e),r=t.apiKey??process.env.ORA_API_KEY;if(!r)throw new E(ct);let o=nn(t.platformUrl),s;try{s=await Ce(o,r)}catch(A){throw new E(`${A instanceof Error?A.message:String(A)}
25
+ (--tunnel ora needs a platform key with the ${at} scopes)`)}if(t.signal?.aborted)throw it();let i=await Fo(o,s),a=()=>Jo(o,s,i.id,()=>Ce(o,r)),c,l,u=!1,d=()=>{},h=new Promise(A=>{d=A}),m=new Promise((A,T)=>{t.signal?.aborted&&T(it()),t.signal?.addEventListener("abort",()=>T(it()),{once:!0})}),f;try{f=Wo(i),c=await Promise.race([Ho(f,s),m]),l=new be({socket:Go(c),codec:new ye,hello:{agentVersion:`ax/${he.version}`,target:{protocol:"http",host:n.host,port:n.port},maxStreams:Uo},forwarder:Ko(n.host,n.port),onConnectionClosed:A=>{u||d(new E(`ora tunnel connection dropped: ${A.message}`))}}),await Promise.race([l.start(),m]),await rt(f.publicUrl,t.routableMs,t.probeEveryMs,t.signal)}catch(A){u=!0;try{l?l.close(1e3,"ax setup failed"):c?.close()}catch{}throw await a(),A}let g=l,p,y=()=>(p||(u=!0,p=(async()=>{try{g.close(1e3,"ax exit")}catch{}await a()})()),p);return{url:f.publicUrl,close:y,dropped:h}}function Wo(e){if(!e.publicUrl||!e.connection?.url||!e.connection.subprotocol)throw new E("ora created a tunnel but returned no public URL to connect to");if(e.connection.kind!=="ora-ws")throw new E(`ora returned a "${e.connection.kind}" tunnel, which this version of ax cannot connect; upgrade ax`);return e}async function Fo(e,t){let n=await fetch(`${e}/tunnels/v1`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({name:`ax-${(0,vn.randomBytes)(4).toString("hex")}`,access:"public"})}),r=await n.text(),o={};try{o=JSON.parse(r)}catch{}if(!n.ok){let s=o.error??o.message??r.trim().slice(0,200);throw new E(`${Bo(n.status)}${s?`: ${s}`:""}`)}if(!o.id)throw new E("ora created a tunnel but returned no id");return o}function Bo(e){switch(e){case 401:return"ora rejected the platform key (401). Check ORA_API_KEY";case 403:return`the platform key lacks the ${at} scopes (403). Issue one with both and retry`;case 429:return"ora rate-limited the tunnel request (429). Wait a moment and retry";default:return`ora could not create a tunnel (${e})`}}async function Jo(e,t,n,r){let o=s=>fetch(`${e}/tunnels/v1/${n}`,{method:"DELETE",headers:{authorization:`Bearer ${s}`},signal:AbortSignal.timeout(1e4)});try{let s=await o(t);s.status===401&&(s=await o(await r())),!s.ok&&s.status!==404&&console.error(`could not delete ora tunnel ${n} (${s.status}); remove it with: ora tunnels delete ${n}`)}catch(s){console.error(`could not delete ora tunnel ${n} (${s instanceof Error?s.message:String(s)}); remove it with: ora tunnels delete ${n}`)}}function Ho(e,t){let n=new URL(e.connection.url);return n.searchParams.set("tunnelId",e.id),n.searchParams.set("token",t),new Promise((r,o)=>{let s=new WebSocket(n,[e.connection.subprotocol]);s.binaryType="arraybuffer";let i=u=>{s.removeEventListener("open",a),s.removeEventListener("error",c),s.removeEventListener("close",l),u()},a=()=>i(()=>r(s)),c=()=>i(()=>o(new E(["ora refused the tunnel connection.","Either the platform key lacks the tunnels:connect scope, the bearer expired (401/403),","or the account's active-tunnel limit is reached (429): check `ora tunnels list`."].join(`
26
+ `)))),l=u=>{let{code:d,reason:h}=u;i(()=>o(new E(`ora closed the tunnel connection (${d??"?"} ${h??""})`)))};s.addEventListener("open",a),s.addEventListener("error",c),s.addEventListener("close",l)})}function Go(e){let t,n,r;return e.addEventListener("message",o=>{let s=o.data;s instanceof ArrayBuffer?t?.(new Uint8Array(s)):ArrayBuffer.isView(s)&&t?.(new Uint8Array(s.buffer,s.byteOffset,s.byteLength))}),e.addEventListener("close",o=>{let{code:s,reason:i}=o;n?.(s??1006,i??"")}),e.addEventListener("error",()=>r?.(new Error("tunnel socket error"))),{get bufferedAmount(){return e.bufferedAmount},send(o){e.readyState===jo&&e.send(o)},close(o,s){try{e.close(o,s)}catch{}},onMessage:o=>{t=o},onClose:o=>{n=o},onError:o=>{r=o}}}var qo=new Set(["host","connection","keep-alive","transfer-encoding","upgrade","te"]);function Ko(e,t){return{forward:n=>new Promise((r,o)=>{let s=(0,xn.request)({host:e,port:t,path:n.path,method:n.method,headers:Vo(n.headers)},i=>r({status:i.statusCode??502,headers:Xo(i),body:i}));s.on("error",o),Yo(n.body,s).catch(i=>{s.destroy(i instanceof Error?i:new Error(String(i))),o(i)})})}}async function Yo(e,t){try{for await(let n of e)t.write(n)||await(0,Sn.once)(t,"drain")}finally{t.end()}}function Vo(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!qo.has(t.toLowerCase())))}function Xo(e){let t={};for(let[n,r]of Object.entries(e.headers))r!==void 0&&(t[n]=r);return t}var lt=G(J(),1);function X(e,t){let n=process.stdout.columns??100;return Math.min(t,Math.max(e,n))}function ne(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function M(e,t){let n=[],r="";for(let o of e.replace(/\s+/g," ").trim().split(" "))r&&r.length+1+o.length>t?(n.push(r),r=o):r=r?`${r} ${o}`:o;return r&&n.push(r),n}var le=["\u25C7","\u25C7","\u25C8","\u25C8","\u25C6","\u25C6","\u25C8","\u25C8"];function C(e){return e.replace(/[\u0000-\u001f\u007f-\u009f]/g," ")}var zo=80,Me,ut=0,we="";function Zo(){let e=lt.default.cyan(le[ut%le.length]),t=Math.max(10,(process.stderr.columns??80)-2),n=we.length>t?`${we.slice(0,t-1)}\u2026`:we;process.stderr.write(`\r\x1B[K${e} ${lt.default.dim(n)}`),ut++}var $={start(e){$.stop(),ut=0,we=e,process.stderr.isTTY&&(Me=setInterval(Zo,zo))},update(e){we=e},stop(){Me&&(clearInterval(Me),Me=void 0,process.stderr.write("\r\x1B[K"))}};var P={OK:0,BELOW_MIN_SCORE:1,USAGE:2,API:3};function kn(e,t,n,r){if(e===void 0)return{};let o=Number(e);return e.trim()===""||!Number.isInteger(o)||o<n||o>r?{error:`${t} must be an integer between ${n} and ${r}, got ${JSON.stringify(e)}`}:{value:o}}function Qo(e){let t=e.trim().replace(/\/+$/,"");if(!(!t||/\s/.test(t)))try{let n=new URL(t.includes("://")?t:`https://${t}`);return!n.hostname.includes(".")&&n.hostname!=="localhost"?void 0:t}catch{return}}function es(e){let t=e.tunnelCmd?.trim();if(t)return{kind:"cmd",command:t};let n=e.tunnel?.trim();if(n!==void 0)return n!=="ora"?{error:`--tunnel must be "ora" (ora's own tunnel), got ${JSON.stringify(e.tunnel)}`}:{kind:"ora"};let r=process.env.ORA_TUNNEL_CMD?.trim();if(r)return{kind:"cmd",command:r};let o=process.env.ORA_TUNNEL?.trim();return o?o!=="ora"?{error:`ORA_TUNNEL must be "ora" (ora's own tunnel), got ${JSON.stringify(o)}`}:{kind:"ora"}:{kind:"none"}}async function $n(e){let t=Qo(e.url);if(!t)return console.error(`Not a scannable URL or domain: ${JSON.stringify(e.url)}`),P.USAGE;let n=kn(e.minScore,"--min-score",0,100),r=kn(e.maxAge,"--max-age",0,86400);for(let g of[n,r])if(g.error)return console.error(g.error),P.USAGE;let o=es(e);if("error"in o)return console.error(o.error),P.USAGE;let s=o.kind!=="none";if(!s&&nt(t))return console.error([`${t} only exists on this machine, and ora audits public URLs.`,"Either audit a publicly reachable deployment of this site (e.g. a preview URL),","or run it through a tunnel:"," ax audit localhost:3000 --tunnel ora # ora's own tunnel; needs ORA_API_KEY"," ax audit localhost:3000 --tunnel-cmd 'ora tunnel 3000 --access public'"," ax audit localhost:3000 --tunnel-cmd 'ngrok http 3000 --log stdout'","Any command that prints a public https URL works; the result is stored as","ephemeral (excluded from rankings, deleted after a few days)."].join(`
27
+ `)),P.USAGE;if(o.kind==="ora"&&!process.env.ORA_API_KEY)return console.error(ct),P.USAGE;let i=!e.json;i&&$.start(`Auditing ${t} with ora`);let a,c,l=new AbortController,u=async()=>{await a?.close()},d=g=>{process.removeListener("SIGINT",d),process.removeListener("SIGTERM",d),l.abort(),(async()=>{await c?.catch(()=>{}),await u()})().finally(()=>process.exit(g==="SIGINT"?130:143))},h=t;if(o.kind!=="none"){i&&$.update(`Opening a tunnel to ${t}`),process.on("SIGINT",d),process.on("SIGTERM",d);try{c=o.kind==="ora"?An(t,{signal:l.signal}):en(o.command),a=await c}catch(g){return $.stop(),process.removeListener("SIGINT",d),process.removeListener("SIGTERM",d),console.error(g instanceof Error?g.message:String(g)),P.USAGE}h=a.url}let m;try{let g=qt(h,{progress:i?p=>$.update(p):void 0,maxAgeSeconds:r.value,force:e.force,ephemeral:s||void 0,apiKey:e.apiKey?.trim()||void 0});m=a?.dropped?await Promise.race([g,a.dropped.then(p=>Promise.reject(p))]):await g}catch(g){return $.stop(),console.error(`Audit failed: ${g instanceof Error?g.message:String(g)}`),g instanceof j?P.API:P.USAGE}finally{await u(),process.removeListener("SIGINT",d),process.removeListener("SIGTERM",d)}$.stop();let{result:f}=m;if(e.json)process.stdout.write(`${JSON.stringify(f,null,2)}
28
+ `);else for(let g of zt(Yt(m,t),{showSkipped:e.showSkipped,showPassing:e.showPassing,tunnel:s}))console.log(g);if(n.value!==void 0){if(f.mcpAuthRequired)return process.stderr.write(`--min-score skipped: the MCP handshake requires credentials, so the target is unscored
29
+ `),P.OK;if(f.score<n.value)return e.json||console.log(` Score ${f.score} is below the required minimum ${n.value}
30
+ `),P.BELOW_MIN_SCORE}return P.OK}var w=G(J(),1);var ts="https://ora.ai",ns=12e4,rs=5e3,os=180,O=class extends Error{};function dt(e){return(e??process.env.ORA_API_URL??ts).replace(/\/+$/,"")}async function pt(e){let t;try{t=await fetch(e,{headers:{accept:"application/json"},signal:AbortSignal.timeout(15e3)})}catch(n){let r=n instanceof Error?n.message:String(n);throw new O(`ora request failed: ${r}`)}if(!t.ok)throw new O(`ora request failed: ${await V(t)}`);return await t.json()}function Tn(e){return pt(`${dt(e)}/api/journey/intents`)}function _n(e){return pt(`${dt(e)}/api/journey/agents`)}function ss(e){let t=r=>{let o=e.headers.get(r);if(o===null)return;let s=Number.parseInt(o,10);return Number.isFinite(s)?s:void 0},n=t("x-ratelimit-reset");return{limit:t("x-ratelimit-limit"),remaining:t("x-ratelimit-remaining"),resetAtMs:n!==void 0?n*1e3:void 0}}async function is(e,t,n){let r={intent:n.task?{custom:n.task,domain:t}:{...n.intentId?{intent_id:n.intentId}:{},domain:t},harness:n.harness,model:n.model},o;try{o=await fetch(`${e}/api/journey/runs`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json",...n.apiKey?{authorization:`Bearer ${n.apiKey}`}:{}},body:JSON.stringify(r),signal:AbortSignal.timeout(3e4)})}catch(i){let a=i instanceof Error?i.message:String(i);throw new O(`ora journey request failed: ${a}`)}if(o.status===401)throw new O("free-text tasks need an ora partner API key \u2014 set ORA_PARTNER_API_KEY or pass --api-key (keys are issued by ora on request)");if(o.status===429){let i=o.headers.get("retry-after"),a=n.apiKey?"keyed allowance: 1000 runs per 24h per key":"burst: 20/min/IP; daily: 200 runs per 24h per IP \u2014 an ora partner API key raises this to 1000/24h per key: set ORA_PARTNER_API_KEY or pass --api-key";throw new O(`ora journey caller limit exceeded${i?` \u2014 retry after ${mt(Number(i)*1e3)}`:""} (${a})`)}if(o.status===503)throw new O("ora's run engine is unavailable right now \u2014 try again shortly");if(!o.ok)throw new O(`ora journey request failed: ${await V(o)}`);let s=await o.json();return ge(s.contractVersion),{record:s,cached:s.rate_limited===!0,allowance:ss(o)}}function mt(e){if(!Number.isFinite(e)||e<=0)return"soon";let t=e/36e5;if(t>=1)return`${Math.ceil(t)}h`;let n=e/6e4;return n>=1?`${Math.ceil(n)}m`:`${Math.ceil(e/1e3)}s`}function as(e){if(!e)return"starting\u2026";if(e.type==="text")return"thinking\u2026";if(e.action==="search")return e.search_query?`searching \u201C${Rn(e.search_query,40)}\u201D`:"searching\u2026";let t=e.label??`${e.url_host??""}${e.url_path??""}`,n=e.completed===!1?"fetching":"fetched";return t?`${n} ${Rn(t,48)}`:`${n}\u2026`}function Rn(e,t){return e.length>t?`${e.slice(0,t-1)}\u2026`:e}async function cs(e,t,n){let r=t.startsWith("http")?t:`${e}${t}`,o=n.idleMs??ns,s=Y(o),i=()=>new O(`ora journey stream timed out \u2014 no frames for ${Math.round(o/1e3)}s`),a;try{a=await fetch(r,{headers:{accept:"text/event-stream"},signal:s.signal})}catch(d){if(s.disarm(),s.tripped())throw i();let h=d instanceof Error?d.message:String(d);throw new O(`ora journey stream failed: ${h}`)}if(!a.ok||!a.body)throw s.disarm(),new O(`ora journey stream failed: ${await V(a)}`);let c=new TextDecoder,l={},u="";try{e:for await(let d of a.body){s.poke(),u=`${u}${c.decode(d,{stream:!0})}`.replace(/\r\n?/g,`
31
+ `);let h=u.indexOf(`
32
+
33
+ `);for(;h!==-1;){let m=ot(u.slice(0,h));if(u=u.slice(h+2),h=u.indexOf(`
34
+
35
+ `),!m)continue;let f;try{f=JSON.parse(m.data)}catch{continue}if(m.event==="trajectory"){let g=f.steps??[],p=g.filter(y=>y.type==="tool_call").at(-1);n.progress?.(`step ${g.length} \xB7 ${as(p??g.at(-1))}`),n.onTrajectory?.(g)}else if(m.event==="processing")n.progress?.(typeof f.message=="string"?f.message:"generating insights\u2026");else if(m.event==="result"){l.result=f;break e}else if(m.event==="error"){l.errorMessage=typeof f.message=="string"?f.message:"unknown engine error";break e}}}}catch(d){if(s.tripped())throw i();if(d instanceof O)throw d;let h=d instanceof Error?d.message:String(d);throw new O(`ora journey stream error: ${h}`)}finally{s.disarm(),a.body.cancel().catch(()=>{})}return l}function Le(e,t){return pt(`${e}/api/journey/runs/${encodeURIComponent(t)}`)}async function En(e,t,n){let r=n.pollEveryMs??rs,o=n.pollLimit??os,s=await Le(e,t);for(let i=0;i<o&&s.status==="running";i++){n.progress?.("agent working\u2026 (polling)"),await z(r);try{s=await Le(e,t)}catch{}}return s}async function Cn(e,t){let n=dt(t.baseUrl);t={...t,apiKey:t.apiKey||process.env.ORA_PARTNER_API_KEY||process.env.ORA_SCAN_API_KEY||void 0};let r=await is(n,e,t),{record:o}=r;r.cached&&t.progress?.("target at its 24h cap \u2014 fetching the most recent stored run");let s;if(!t.noStream&&o.status==="running")try{s=(await cs(n,o.stream_url,t)).errorMessage}catch{t.progress?.("stream went quiet \u2014 switching to polling"),await En(n,o.id,t)}else t.noStream&&o.status==="running"&&await En(n,o.id,t);let i=await ls(n,o.id,t);if(i.status==="running")throw s?new O(`ora journey run failed: ${s}`):new O(`run ${o.id} is still executing \u2014 the ${t.noStream?"poll budget ran out":"stream ended"} before a terminal result. Check ${n}/api/journey/runs/${o.id} shortly`);return ge(i.contractVersion),{record:o,cached:r.cached,retryAfterMs:r.record.retry_after_ms,allowance:r.allowance,detail:i,engineError:s}}async function ls(e,t,n){let r=await Le(e,t);for(let o=0;o<3&&r.status==="running";o++)n.progress?.("finalizing\u2026"),await z(1500),r=await Le(e,t);return r}var _=G(J(),1);function ht(e){if(!e)return{};let t=e.match(/https?:\/\/([^/\s]+)(\/\S*)?/i);return t?{host:t[1],path:t[2]??"/"}:{}}function re(e){return/search/i.test(`${e.tool??""} ${e.action??""}`)}function us(e){if(re(e))return"\u{1F50D}";let t=`${e.tool??""} ${e.action??""}`.toLowerCase();return/fetch|http|get/.test(t)?"\u{1F310}":/read|open|view/.test(t)?"\u{1F4C4}":"\u{1F310}"}function ds(e,t){if(re(e)){let c=e.input_display??String(e.input?.query??"search"),l=e.output_structured?.links?.length;return{id:e.id,kind:"search",icon:"\u{1F50D}",label:ne(`"${c}"`,t),meta:l?`${l} results`:void 0,tone:"ok",notes:[],children:[]}}let{host:n,path:r}=ht(e.input_display??String(e.input?.url??"")),o=e.status,s=o!=null&&o>=300&&o<400,i=!!e.is_error||o!=null&&o>=400,a;if(s)a=`\u21B3 ${o}`;else if(i)a=`\u2717 ${o??"error"}`;else{let c=["\u2713"];o&&c.push(String(o)),e.duration_ms&&c.push(`${(e.duration_ms/1e3).toFixed(1)}s`),a=c.join(" ")}return{id:e.id,kind:"fetch",icon:us(e),label:ne(`${n??"?"}${r??""}`,t),meta:a,tone:s?"redirect":i?"error":"ok",notes:[],children:[]}}function Ne(e,t,n){let r=X(60,120),o=Math.min(52,Math.max(24,r-40)),s=Math.max(30,r-24),i={id:-1,kind:"intent",icon:"\u25C6",label:ne(t,s),tone:"root",notes:[],children:[]},a=new Map,c=[],l,u,d;for(let h of e){if(h.type==="text"&&h.kind==="reasoning"){let g=(h.thinking??h.text??"").trim();g&&c.push(ne(g,s));continue}if(h.type!=="tool_call")continue;let m=ds(h,o);m.notes=c,c=[],a.set(h.id,m);let f=i;if(!re(h)){let g=h.attribution?.referrer?.step_id,p=h.attribution?.kind,y=g!=null?a.get(g):void 0;y&&y!==m?f=y:p==="web_search"&&l?f=l:p==="previous_artifact"&&u&&(f=u)}f.children.push(m),re(h)?l=m:u=m,d=m}return d&&!n&&(d.tone="active",d.meta="\u2026"),{root:i,looseNotes:c}}function je(e){let t=e.filter(o=>o.kind==="reasoning").length,n=e.filter(o=>o.type==="tool_call"&&re(o)).length,r=[`${_.default.bold(String(e.length))} steps`];return t&&r.push(`${_.default.bold(String(t))} reasoning`),n&&r.push(`${_.default.bold(String(n))} search${n===1?"":"es"}`),r.join(_.default.dim(" \xB7 "))}function ps(e){switch(e){case"root":return{frame:_.default.dim,ink:t=>_.default.bold(t)};case"active":return{frame:_.default.cyan,ink:t=>_.default.cyan(_.default.bold(t))};case"redirect":return{frame:_.default.yellow,ink:_.default.yellow};case"error":return{frame:_.default.red,ink:_.default.red};default:return{frame:_.default.green,ink:_.default.green}}}var Pn=e=>_.default.dim(`(\u2026) ${e}`);function On(e,t){let{frame:n,ink:r}=ps(e.tone),s=`${e.icon} ${e.label}${e.meta?` ${e.meta}`:""}`.length+2,i=`${e.icon} ${r(e.label)}${e.meta?` ${_.default.dim(e.meta)}`:""}`,a=e.children.length>0,c=e.notes.map(Pn);return c.push(n(`\u256D${"\u2500".repeat(s)}\u256E`)),c.push(`${n(t?"\u2524":"\u2502")} ${i} ${n("\u2502")}`),c.push(n(a?`\u2570\u2500\u252C${"\u2500".repeat(s-2)}\u256F`:`\u2570${"\u2500".repeat(s)}\u256F`)),e.children.forEach((l,u)=>{let d=u===e.children.length-1,h=On(l,!0),m=l.notes.length+1;h.forEach((f,g)=>{let p;g===m?p=d?" \u2570\u2500\u2500":" \u251C\u2500\u2500":g<m?p=" \u2502 ":p=d?" ":" \u2502 ",c.push(_.default.dim(p)+f)})}),c}function Ue(e){let t=On(e.root,!1);return e.looseNotes.length&&(t.push(""),t.push(...e.looseNotes.map(Pn))),t}var De=G(J(),1);var ue=class{rows=0;beat=0;bornAt=Date.now();ticker;live=!!process.stdout.isTTY;content=[];headline="";open(){this.live&&!this.ticker&&(this.ticker=setInterval(()=>this.pulse(),100))}draw(t,n){this.content=t,this.headline=n,this.repaint()}close(){this.ticker&&(clearInterval(this.ticker),this.ticker=void 0),this.live&&this.rows>0&&(process.stdout.write(`\x1B[${this.rows}A\r\x1B[0J`),this.rows=0)}banner(){let t=De.default.cyan(le[this.beat%le.length]),n=Math.floor((Date.now()-this.bornAt)/1e3),r=`${this.headline} ${n}s`,o=Math.max(10,(process.stdout.columns??80)-6),s=r.length>o?`${r.slice(0,o-1)}\u2026`:r;return` ${t} ${De.default.bold(s)}`}clamp(t){let n=Math.max(2,(process.stdout.rows??24)-3);if(t.length<=n)return t;let r=n-1,o=t.length-r;return[De.default.dim(` \u22EF ${o} earlier line${o===1?"":"s"}`),...t.slice(-r)]}repaint(){if(!this.live)return;let t=[this.banner(),"",...this.clamp(this.content)],n=this.rows>0?`\x1B[${this.rows}A`:"";for(let r of t)n+=`\x1B[2K${r}
36
+ `;t.length<this.rows&&(n+="\x1B[0J"),this.rows=t.length,process.stdout.write(n)}pulse(){!this.live||this.rows===0||(this.beat++,process.stdout.write(`\x1B[${this.rows}A\r\x1B[2K${this.banner()}\x1B[${this.rows}B\r`))}};var H={OK:0,RUN_FAILED:1,USAGE:2,API:3},ms="public caps: 100 runs/24h per target \xB7 200 runs/24h per IP",hs="keyed caps: 1000 runs/24h per key \xB7 no per-target cap",gs={id:"cas-haiku",label:"Claude Code",variant:"Haiku 4.5",harness:"claude-agent-sdk",model:"claude-haiku-4-5",blurb:"Fast, frugal navigator \u2014 the CLI default."};function gt(e){return console.error(w.default.red(`ax deep-journey: ${e}`)),H.API}function fs(e,t){if(t==="failed")return w.default.red("\u2717 run failed");switch(e){case"satisfied":return w.default.green("\u2713 task satisfied");case"partial":return w.default.yellow("\u25D0 partially satisfied");case"unsatisfied":return w.default.red("\u2717 task not satisfied");default:return w.default.dim("\xB7 not gradable")}}function ft(e){return`${e.label} \xB7 ${e.variant}`}function In(e){let n=e.action==="search"?e.search_query:e.url_host||e.url_path?`https://${e.url_host??""}${e.url_path??""}`:e.url;return{id:e.id,turn:e.turn??0,type:e.type,kind:e.type==="text"?"reasoning":void 0,text:e.text,thinking:e.text,tool:e.tool,action:e.action,input_display:n,status:e.status,duration_ms:e.duration_ms,attribution:e.attribution?{kind:e.attribution.kind,referrer:{step_id:e.attribution.referrer?.step_id??e.parent_id}}:void 0}}function Mn(e,t,n){return[` ${je(e)}`,"",...Ue(Ne(e,t,n)).map(r=>` ${r}`)]}var ys=e=>e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e);function bs(e){return e<.01?`$${e.toFixed(4)}`:e<1?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function ws(e){if(!e)return;let{input_tokens:t,output_tokens:n}=e;if(!(t==null&&n==null))return(t??0)+(n??0)}function vs(e){return(e?.trajectory?.steps??[]).filter(t=>t.action==="search").length}function yt(e,t,n){return e>=t?w.default.green:e>=n?w.default.yellow:w.default.red}function Ss(e){let t=e.run_signals,r=(e.trajectory?.steps??[]).filter(s=>s.type==="tool_call"&&(s.action==="fetch"||s.action==="api_call")),o=[];if(t?.answer_basis!=null){let s=Math.round(t.answer_basis.site_share*100);o.push({label:"answer from your site",pct:s,paint:yt(s,70,40)})}if(t?.answer_efficiency!=null){let s=Math.round(t.answer_efficiency*100);o.push({label:"answer efficiency",pct:s,paint:yt(s,70,30)})}if(r.length){let s=t?.link_following_rate??r.filter(a=>a.attribution?.kind==="previous_artifact").length/r.length,i=Math.round(s*100);o.push({label:"followed site links",pct:i,paint:yt(i,70,35)})}return o}function xs(e,t=20,n=21){let r=Math.max(0,Math.min(t,Math.round(e.pct/100*t))),o=`${e.paint("\u25B0".repeat(r))}${w.default.dim("\u25B1".repeat(t-r))}`,s=`${e.pct}%`.padStart(4);return` ${w.default.dim(e.label.padEnd(n))} ${o} ${e.paint(w.default.bold(s))}`}function bt(e,t,n){let r=Math.max(0,t-e.length),o=Math.floor(r/2);return`${" ".repeat(o)}${n(e)}${" ".repeat(r-o)}`}function As(e,t){let n=e.length;if(n===0)return null;let r=4,o=Math.min(t,100)-2,s=Math.floor((o-r*(n-1))/n);if(s<18)return null;let i=[],a=[],c=[],l=1;for(let h of e){i.push(bt(`${h.pct}%`,s,p=>h.paint(w.default.bold(p))));let m=s-2,f=Math.max(1,Math.min(m,Math.round(h.pct/100*m)));a.push(` ${h.paint("\u2594".repeat(f))}${w.default.dim("\u2594".repeat(m-f))} `);let g=M(h.label.toUpperCase(),s).map(p=>bt(p,s,w.default.dim));c.push(g),l=Math.max(l,g.length)}let u=h=>` ${h.join(" ".repeat(r))}`,d=["",u(i),u(a)];for(let h=0;h<l;h++)d.push(u(c.map(m=>m[h]??bt("",s,w.default.dim))));return d}function Ln(e,t){let n=t.filter(i=>i.n>0),r=n.reduce((i,a)=>i+a.n,0);if(!n.length||!r)return[];let o=Math.max(...n.map(i=>i.label.length)),s=["",` ${w.default.dim(e)}`];for(let i of n){let a=Math.round(i.n/r*100),c=Math.max(0,Math.min(20,Math.round(a/100*20))),l=`${w.default.dim("\u25B0".repeat(c))}${w.default.dim("\u25B1".repeat(20-c))}`;s.push(` ${w.default.dim(i.label.padEnd(o))} ${l} ${w.default.dim(`${a}%`.padStart(4))}`)}return s}function ks(e){return w.default.dim(` ${"\u2500".repeat(Math.min(e-4,52))}`)}function $s(e,t){let n=e.run_signals,r=[];if(n?.reached_anchor!=null){let c=n.reached_anchor?w.default.green("\u2713 reached the site"):w.default.red("\u2717 never reached the site");r.push("",` ${c}`)}let o=Ss(e);if(o.length){let c=As(o,t);if(c)r.push(...c);else{r.push("");for(let l of o)r.push(xs(l))}}let s=n?.answer_basis;s&&s.sections_total>0&&r.push(...Ln("answer sources",[{label:"from this site",n:s.from_site},{label:"from external pages",n:s.from_external},{label:"from search results",n:s.from_search},{label:"from agent knowledge",n:s.from_memory}]));let a=(e.trajectory?.steps??[]).filter(c=>c.type==="tool_call"&&(c.action==="fetch"||c.action==="api_call"));if(a.length){let c=u=>{let d=u.attribution?.kind;return d==="previous_step"||d==="previous_artifact"?"previous_artifact":d==="web_search"?"web_search":d==="prior_knowledge"&&u.anchor_relation==="exact"&&(!u.url_path||u.url_path==="/")?"task_input":"prior_knowledge"},l={};for(let u of a){let d=c(u);l[d]=(l[d]??0)+1}r.push(...Ln("url discovery",[{label:"given in the task",n:l.task_input??0},{label:"followed a link",n:l.previous_artifact??0},{label:"found via web search",n:l.web_search??0},{label:"guessed the URL",n:l.prior_knowledge??0}]))}return r}function Rs(e,t){let n=X(60,120),{detail:r}=e,o=r.result,s=["",ks(n),""];s.push(` ${fs(r.verdict,r.status)} ${w.default.dim("\xB7")} ${w.default.dim(r.domain??t)}`);let i=[];r.step_count!=null&&i.push(`${r.step_count} steps`);let a=o?.run_signals?.search_count??vs(o);a&&i.push(`${a} search${a===1?"":"es"}`),o?.duration_ms!=null&&i.push(`${(o.duration_ms/1e3).toFixed(1)}s`);let c=ws(o);if(c!=null&&i.push(`${ys(c)} tokens`),o?.cost_usd!=null&&i.push(bs(o.cost_usd)),i.length&&s.push(` ${w.default.dim(i.join(" \xB7 "))}`),o&&s.push(...$s(o,n)),o?.insight?.summary){s.push("");for(let u of M(C(o.insight.summary),n-4))s.push(` ${u}`)}let l=o?.insight?.key_observations??[];if(l.length){s.push("",` ${w.default.bold("Observations")}`);for(let u of l){let[d,...h]=M(C(u),n-6);s.push(` ${w.default.cyan("\xB7")} ${d}`);for(let m of h)s.push(` ${m}`)}}return r.status==="failed"&&s.push("",w.default.dim(e.engineError?` Engine error: ${e.engineError} \u2014 re-running is free to try.`:" The run ended in an engine error; re-running is free to try.")),s.push("",w.default.dim(` For the 4-layer readiness audit, run: ax audit ${t}`)),s}async function Nn(e){let t=e.url.trim();if(!t)return console.error("ax deep-journey: a target URL or domain is required"),H.USAGE;let n=!e.json&&process.stderr.isTTY,r=e.task?.trim()||void 0,o=e.apiKey||process.env.ORA_PARTNER_API_KEY||process.env.ORA_SCAN_API_KEY||void 0;if(r&&e.intent!==void 0)return console.error("ax deep-journey: --task and --intent are mutually exclusive \u2014 a free-text task replaces the curated intent"),H.USAGE;if(r&&!o)return console.error("ax deep-journey: --task needs an ora partner API key \u2014 set ORA_PARTNER_API_KEY or pass --api-key (keys are issued by ora on request)"),H.USAGE;let s=e.intent,i,a=r??"journey";try{let[p,y]=await Promise.all([r?void 0:Tn(),_n()]);if(p){if(s===void 0)s=p.defaultId;else if(!p.intents.some(se=>se.id===s))return console.error(`ax deep-journey: unknown intent "${s}". Available intents:
37
+ ${p.intents.map(se=>` ${se.id.padEnd(12)} ${se.hint}`).join(`
38
+ `)}`),H.USAGE;let N=p.intents.find(se=>se.id===s);a=(N?.template||N?.hint||N?.label||s||"journey").replace(/\{domain\}/g,t)}let T=y.agents.some(N=>N.harness==="claude-agent-sdk"&&/haiku/i.test(N.model))?y.agents:[gs,...y.agents],ve=T.find(N=>N.harness==="claude-agent-sdk"&&/haiku/i.test(N.model))?.id??y.defaultId,Se=e.agent??ve,Pt=T.find(N=>N.id===Se);if(!Pt)return console.error(`ax deep-journey: unknown agent "${Se}". Available agents:
39
+ ${T.map(N=>` ${N.id.padEnd(12)} ${ft(N)}`).join(`
40
+ `)}`),H.USAGE;i=Pt}catch(p){return gt(p instanceof Error?p.message:String(p))}e.json||console.error(w.default.dim(o?hs:ms));let c=n&&!e.noStream,l=new ue,u=[],d=`waking ${i.label}`,h=()=>l.draw(Mn(u,a,!1),d);c?(console.log(),console.log(` ${w.default.cyan("\u25B6")} ${w.default.bold(t)} ${w.default.dim("\xB7")} ${w.default.dim(ft(i))} ${w.default.dim("\xB7")} ${w.default.dim(r?"custom task":s??"default")}`),console.log(),l.open(),h()):n&&$.start(`Sending ${ft(i)} to ${t} (${r?`"${r}"`:s})`);let m=p=>{c?(d=p,h()):n&&$.update(p)},f;try{f=await Cn(t,{intentId:r?void 0:s,task:r,apiKey:o,harness:i.harness,model:i.model,noStream:e.noStream,progress:n?m:void 0,onTrajectory:c?p=>{u=p.map(In),h()}:void 0})}catch(p){return c?l.close():n&&$.stop(),p instanceof O?gt(p.message):gt(p instanceof Error?p.message:String(p))}if(c?l.close():n&&$.stop(),e.json)return console.log(JSON.stringify(f.detail,null,2)),f.detail.status==="failed"?H.RUN_FAILED:H.OK;f.cached?console.error(w.default.yellow(`This target hit its 24h cap \u2014 showing the most recent stored run${f.retryAfterMs?` (fresh run in ${mt(f.retryAfterMs)})`:""}.`)):f.allowance.remaining!==void 0&&f.allowance.limit!==void 0&&console.error(w.default.dim(`allowance: ${f.allowance.remaining} of ${f.allowance.limit} target runs left in the 24h window`));let g=(f.detail.result?.trajectory?.steps??[]).map(In);if(g.length){console.log();for(let p of Mn(g,a,!0))console.log(p)}for(let p of Rs(f,t))console.log(p);return f.detail.status==="failed"?H.RUN_FAILED:H.OK}var x=G(J(),1);var We=()=>X(60,120);function Es(e){if(e.type==="tool_call"){let t=e.input_display??e.summary??"";if(re(e))return t?`searching ${ne(t,40)}`:"searching\u2026";let{host:n}=ht(t);return n?`fetching ${n}`:"fetching\u2026"}return e.type==="text"&&e.kind==="reasoning"?"deciding next step\u2026":e.type==="text"?"writing the answer\u2026":"working\u2026"}var Ts=e=>e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e);function _s(e){return e<.01?`$${e.toFixed(4)}`:e<1?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function Cs(e,t){let n=e.outcome==="success",r=[];return e.num_turns!=null&&r.push(`${e.num_turns} turns`),e.duration_ms!=null&&r.push(`${(e.duration_ms/1e3).toFixed(1)}s`),t?.totalTokens!=null&&r.push(`${Ts(t.totalTokens)} tokens`),t?.costUsd!=null&&r.push(_s(t.costUsd)),["",` ${x.default.dim("\u2500".repeat(Math.min(We()-4,52)))}`,` ${n?x.default.green("\u2713"):x.default.red("\u2717")} ${x.default.bold(n?"completed":e.outcome)}${r.length?` ${x.default.dim(r.join(" \xB7 "))}`:""}`]}function Ps(e,t=22){let n=Math.min(100,Math.max(0,e)),r=Math.round(n/100*t);return(n>=70?x.default.green:n>=50?x.default.yellow:x.default.red)("\u2588".repeat(r))+x.default.dim("\u2591".repeat(t-r))}function Os(e){return e==="high"?x.default.red("\u25CF high "):e==="medium"?x.default.yellow("\u25CF medium"):e==="low"?x.default.dim("\u25CF low "):x.default.dim("\u25CF ")}function Is(e){let t=[""];if(e.visibility_score!=null){let n=e.visibility_score,r=n>=70?x.default.green:n>=50?x.default.yellow:x.default.red,o=e.intent_satisfied?x.default.green("\u2713 intent satisfied"):x.default.yellow("\u2717 intent not satisfied");t.push(` ${x.default.bold("Visibility")} ${Ps(n)} ${r(x.default.bold(`${n}/100`))} ${o}`)}if(e.summary){t.push("");for(let n of M(e.summary,We()-4))t.push(` ${x.default.dim(n)}`)}if(e.friction_points?.length){t.push("",` ${x.default.bold("Friction")}`);for(let n of e.friction_points){let[r,...o]=M(n,We()-6);t.push(` ${x.default.yellow("\xB7")} ${r}`);for(let s of o)t.push(` ${s}`)}}if(e.recommendations?.length){t.push("",` ${x.default.bold("Recommendations")}`);for(let n of e.recommendations){t.push(` ${Os(n.priority)} ${x.default.bold(n.title)}`);for(let r of M(n.detail,We()-8))t.push(` ${x.default.dim(r)}`)}}return t.push(""),t}function Ms(e){let t=e.insight??{};return JSON.stringify({runId:e.runId,intent:e.intent,domain:e.domain,harness:e.harness,model:e.result?.effective_model??e.result?.model,outcome:e.result?.outcome,durationMs:e.result?.duration_ms,numTurns:e.result?.num_turns,totalTokens:e.usage?.totalTokens,inputTokens:e.usage?.inputTokens,outputTokens:e.usage?.outputTokens,costUsd:e.usage?.costUsd,visibilityScore:t.visibility_score,intentSatisfied:t.intent_satisfied,taskSatisfied:t.task_satisfied,summary:t.summary,keyObservations:t.key_observations,frictionPoints:t.friction_points,recommendations:t.recommendations,journeyLayers:t.journey_layers,intentCategory:t.intent_category,steps:e.trajectory},null,2)}async function jn(e){let t={intent:e.intent,domain:e.domain,harness:e.harness,model:e.model};if(e.json)try{let i=await st(t);return process.stdout.write(`${Ms(i)}
41
+ `),i.result?.outcome==="success"?0:1}catch(i){return console.error(`Journey failed: ${i instanceof Error?i.message:String(i)}`),2}let n=new ue,r=[],o=!1,s=()=>[` ${je(r)}`,"",...Ue(Ne(r,e.intent,o)).map(i=>` ${i}`)];console.log(),console.log(` ${x.default.cyan("\u25B6")} ${e.domain?x.default.bold(e.domain):x.default.dim("(no domain)")} ${x.default.dim("\xB7")} ${x.default.dim(e.harness)}`),console.log(),n.open(),n.draw(s(),"waking the agent");try{let i=await st(t,{snapshot:a=>{r=a;let c=a[a.length-1];n.draw(s(),c?Es(c):"working")},finished:()=>{o=!0,n.draw(s(),"scoring the journey")}});n.close(),o=!0,i.trajectory.length&&(r=i.trajectory);for(let a of s())console.log(a);if(i.result)for(let a of Cs(i.result,i.usage))console.log(a);if(i.insight)for(let a of Is(i.insight))console.log(a);else i.result&&(console.log(x.default.dim(" (insight not available for this run)")),console.log());return i.result?.outcome==="success"?0:1}catch(i){return n.close(),console.error(`Journey failed: ${i instanceof Error?i.message:String(i)}`),2}}var Fe=require("fs"),vt=require("path"),de=G(J(),1);var Dn=require("crypto"),Ls="https://ora.ai",F=class extends Error{};function Wn(e){return(e??process.env.ORA_API_URL??Ls).replace(/\/+$/,"")}async function wt(e){let t=Wn(e),n;try{n=await fetch(`${t}/.well-known/agent-skills/index.json`,{headers:{accept:"application/json"},signal:AbortSignal.timeout(15e3)})}catch(o){throw new F(`could not reach the skill registry at ${t}: ${o instanceof Error?o.message:String(o)}`)}if(!n.ok)throw new F(`skill registry answered HTTP ${n.status}`);let r=await n.json();if(!Array.isArray(r.skills))throw new F("skill registry index has no skills[]");return r.skills}function Un(e){return`sha256:${(0,Dn.createHash)("sha256").update(e).digest("hex")}`}async function Fn(e,t){let n=Wn(t),r=await wt(n),o=r.find(c=>c.name===e);if(!o){let c=r.map(l=>l.name).join(", ");throw new F(`unknown skill ${JSON.stringify(e)} - the registry has: ${c}`)}let s=o.url.startsWith("http")?o.url:`${n}${o.url}`,i;try{i=await fetch(s,{signal:AbortSignal.timeout(15e3)})}catch(c){throw new F(`could not fetch ${s}: ${c instanceof Error?c.message:String(c)}`)}if(!i.ok)throw new F(`skill fetch answered HTTP ${i.status} for ${s}`);let a=new Uint8Array(await i.arrayBuffer());if(o.digest&&Un(a)!==o.digest)throw new F(`digest mismatch for ${e}: index says ${o.digest}, served bytes hash to ${Un(a)} - refusing to use them`);return{entry:o,bytes:a}}var Ns=".claude/skills";function js(e,t,n){let r=[],o="";for(let s of e.split(/\s+/))o&&`${o} ${s}`.length>t?(r.push(n+o),o=s):o=o?`${o} ${s}`:s;return o&&r.push(n+o),r}async function Bn(e){try{if(!e.name){let r=await wt();if(e.json)return process.stdout.write(`${JSON.stringify(r,null,2)}
42
+ `),P.OK;console.log("");for(let o of r){let s=o.digest?de.default.dim(` ${o.digest.slice(0,19)}\u2026`):"";if(console.log(` ${de.default.bold(o.name)}${s}`),o.description)for(let i of js(o.description,76," "))console.log(de.default.dim(i));console.log("")}return console.log(de.default.dim(" Install one with: ax skill <name> --install")),console.log(""),P.OK}let{entry:t,bytes:n}=await Fn(e.name);if(e.install){let r=(0,vt.join)(e.dir??Ns,t.name);(0,Fe.mkdirSync)(r,{recursive:!0});let o=(0,vt.join)(r,"SKILL.md");return(0,Fe.writeFileSync)(o,n),console.log(`Installed ${t.name} to ${o}`),t.digest&&console.log(de.default.dim(`verified ${t.digest}`)),P.OK}return process.stdout.write(n),P.OK}catch(t){let n=t instanceof Error?t.message:String(t);return console.error(`Skill command failed: ${n}`),t instanceof F&&n.includes("unknown skill")?P.USAGE:P.API}}var R=class extends Error{constructor(t,n){super(t,n),this.name="CdpError"}},Jn=1e4,Hn=5e3,xt=class e{socket;nextId=1;pending=new Map;handlers=new Map;closed=!1;closeReason=null;constructor(t){this.socket=t,t.addEventListener("message",n=>{this.dispatch(String(n.data))}),t.addEventListener("close",()=>{this.fail("the browser closed the DevTools connection")}),t.addEventListener("error",()=>{this.fail("the DevTools connection errored")})}static async open(t){let n=new WebSocket(t);return await new Promise((r,o)=>{let s=setTimeout(()=>{o(new R(`timed out connecting to ${t}`))},Hn);n.addEventListener("open",()=>{clearTimeout(s),r()},{once:!0}),n.addEventListener("error",()=>{clearTimeout(s),o(new R(`could not connect to ${t}`))},{once:!0})}),new e(n)}dispatch(t){let n;try{n=JSON.parse(t)}catch{return}let r=n.id;if(typeof r=="number"){let a=this.pending.get(r);if(!a)return;this.pending.delete(r),clearTimeout(a.timer);let c=n.error;c?a.reject(new R(c.message??"CDP call failed")):a.resolve(n.result??{});return}let o=n.method;if(typeof o!="string")return;let s=typeof n.sessionId=="string"?n.sessionId:"",i=n.params??{};for(let a of this.handlers.get(`${s}\0${o}`)??[])try{a(i)}catch{}}fail(t){if(!this.closed){this.closed=!0,this.closeReason=t;for(let[,n]of this.pending)clearTimeout(n.timer),n.reject(new R(t));this.pending.clear()}}send(t,n={},r={}){if(this.closed)return Promise.reject(new R(this.closeReason??"the connection is closed"));let o=this.nextId++,s=r.timeoutMs??Jn;return new Promise((i,a)=>{let c=setTimeout(()=>{this.pending.delete(o),a(new R(`${t} timed out after ${s}ms`))},s);this.pending.set(o,{resolve:i,reject:a,timer:c});let l={id:o,method:t,params:n};r.sessionId&&(l.sessionId=r.sessionId);try{this.socket.send(JSON.stringify(l))}catch(u){this.pending.delete(o),clearTimeout(c),a(new R(`could not send ${t}`,{cause:u}))}})}on(t,n,r){let o=`${t}\0${n}`,s=this.handlers.get(o)??new Set;return s.add(r),this.handlers.set(o,s),()=>{s.delete(r)}}close(){this.closed=!0;try{this.socket.close()}catch{}}};async function kt(e,t=Hn){if(e.startsWith("ws://")||e.startsWith("wss://"))return{webSocketDebuggerUrl:e,product:""};let n=e.startsWith("http://")||e.startsWith("https://")?e.replace(/\/+$/,""):`http://${e.replace(/\/+$/,"")}`,r;try{r=await fetch(`${n}/json/version`,{signal:AbortSignal.timeout(t)})}catch(s){throw new R(`no debuggable Chrome answered at ${n}`,{cause:s})}if(!r.ok)throw new R(`${n}/json/version returned HTTP ${r.status}`);let o=await r.json().catch(()=>null);if(!o?.webSocketDebuggerUrl)throw new R(`${n}/json/version carried no webSocketDebuggerUrl`);return{webSocketDebuggerUrl:o.webSocketDebuggerUrl,product:o.Browser??""}}var Be=class e{connection;product;constructor(t,n){this.connection=t,this.product=n}static async connect(t){let n=await xt.open(t.webSocketDebuggerUrl),r=t.product;if(!r){let o=await n.send("Browser.getVersion").catch(()=>({}));r=typeof o.product=="string"?o.product:""}return new e(n,r.replace(/^(?:Headless)?Chrome\//i,""))}async newContext(t){let{browserContextId:n}=await this.connection.send("Target.createBrowserContext",{disposeOnDetach:!0}),{targetId:r}=await this.connection.send("Target.createTarget",{url:"about:blank",browserContextId:n}),{sessionId:o}=await this.connection.send("Target.attachToTarget",{targetId:r,flatten:!0}),s=new At(this.connection,o,n,t.entryUrl);return await s.prepare(t.initScripts??[],t.viewport),s}close(){this.connection.close()}},Us=8,Ds=1024*1024,Ws=new Set(["Image","Media","Font"]),At=class{connection;sessionId;browserContextId;entryHost;currentUrl="about:blank";viewport=null;domContentFired=!1;loadFired=!1;documentResponses=new Map;scripts=[];scriptsStarted=0;pendingScriptRequests=new Map;constructor(t,n,r,o){this.connection=t,this.sessionId=n,this.browserContextId=r,this.entryHost=St(o)}async prepare(t,n){await this.send("Page.enable"),await this.send("Runtime.enable"),await this.send("Network.enable"),await this.send("Fetch.enable",{patterns:[{urlPattern:"*"}]}),this.connection.on(this.sessionId,"Fetch.requestPaused",r=>{this.onRequestPaused(r)}),n&&(this.viewport=n,await this.send("Emulation.setDeviceMetricsOverride",{width:n.width,height:n.height,deviceScaleFactor:1,mobile:!1})),this.connection.on(this.sessionId,"Page.domContentEventFired",()=>{this.domContentFired=!0}),this.connection.on(this.sessionId,"Page.loadEventFired",()=>{this.loadFired=!0}),this.connection.on(this.sessionId,"Page.frameNavigated",r=>{let o=r.frame;!o||o.parentId||typeof o.url=="string"&&(this.currentUrl=o.url)}),this.connection.on(this.sessionId,"Network.responseReceived",r=>{this.onResponse(r)}),this.connection.on(this.sessionId,"Network.loadingFinished",r=>{this.onLoadingFinished(r)});for(let r of t)await this.send("Page.addScriptToEvaluateOnNewDocument",{source:r})}send(t,n={},r){return this.connection.send(t,n,{sessionId:this.sessionId,timeoutMs:r})}onRequestPaused(t){let n=t.requestId;if(typeof n!="string")return;(Ws.has(String(t.resourceType))?this.send("Fetch.failRequest",{requestId:n,errorReason:"BlockedByClient"}):this.send("Fetch.continueRequest",{requestId:n})).catch(()=>{})}onResponse(t){let n=t.type,r=t.requestId,o=t.response;if(typeof r!="string"||!o)return;if(n==="Document"){let a=typeof t.frameId=="string"?t.frameId:"";this.documentResponses.set(a,{status:typeof o.status=="number"?o.status:0,headers:Fs(o.headers??{})});return}if(n!=="Script"||this.scriptsStarted>=Us)return;let s=typeof o.url=="string"?o.url:"",i=St(s);i&&(i!==this.entryHost&&i!==St(this.currentUrl)||(this.scriptsStarted++,this.pendingScriptRequests.set(r,s)))}onLoadingFinished(t){let n=t.requestId;if(typeof n!="string")return;let r=this.pendingScriptRequests.get(n);r!==void 0&&(this.pendingScriptRequests.delete(n),this.send("Network.getResponseBody",{requestId:n}).then(o=>{let s=typeof o.body=="string"?o.body:"",i=o.base64Encoded===!0?Buffer.from(s,"base64").toString("utf8"):s;this.scripts.push({url:r,body:i.slice(0,Ds)})}).catch(()=>{}))}async goto(t,n){this.domContentFired=!1,this.loadFired=!1;let r=await this.send("Page.navigate",{url:t},n),o=r.errorText;if(typeof o=="string"&&o.length>0)throw new R(`navigating to ${t} failed: ${o}`);let s=typeof r.frameId=="string"?r.frameId:"";return await this.waitFor(()=>this.domContentFired,n,`${t} never reached DOMContentLoaded`),this.currentUrl=await this.readLocation(t),this.documentResponses.get(s)??this.documentResponses.get("")??null}async waitForLoad(t){await this.waitFor(()=>this.loadFired,t,"load").catch(()=>{})}async waitFor(t,n,r){let o=Date.now()+n;for(;!t();){if(Date.now()>=o)throw new R(`timed out waiting for ${r}`);await new Promise(s=>setTimeout(s,25))}}async readLocation(t){let n=await this.evaluate("location.href",2e3).catch(()=>null);return typeof n=="string"&&n.length>0?n:t}async evaluate(t,n=Jn){let r=await this.send("Runtime.evaluate",{expression:t,awaitPromise:!0,returnByValue:!0},n),o=r.exceptionDetails;if(o)throw new R(o.exception?.description??o.text??"evaluation threw");return r.result?.value}async content(){return await this.evaluate("document.documentElement ? document.documentElement.outerHTML : ''").catch(()=>"")??""}async inlineScripts(){return await this.evaluate('Array.from(document.querySelectorAll("script:not([src])")).map(function (s) { return s.textContent || ""; }).join("\\n")').catch(()=>"")??""}url(){return this.currentUrl}collectedScripts(){return this.scripts.slice()}viewportSize(){return this.viewport}async screenshot(t,n){try{let o=(await this.send("Page.captureScreenshot",{format:"jpeg",quality:t,captureBeyondViewport:!1},n)).data;return typeof o!="string"||o.length===0?null:Buffer.from(o,"base64")}catch{return null}}async close(){await this.connection.send("Target.disposeBrowserContext",{browserContextId:this.browserContextId}).catch(()=>{})}};function Fs(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.toLowerCase(),s=r.split(`
43
+ `).map(i=>i.trim()).filter(i=>i.length>0).join(", ");t[o]=t[o]===void 0?s:`${t[o]}, ${s}`}return t}function St(e){try{return new URL(e).host}catch{return""}}var Bs=new Set([2,3]),Js=8192,Hs=864e10;function Gs(e){if(typeof e!="string")return null;let t=e.trim();if(t.length===0||t.length>Js)return null;let n;try{n=Buffer.from(t,"base64")}catch{return null}if(n.length<=69||!Bs.has(n[0])||n.readUInt32BE(65)!==n.length-69)return null;let o;try{o=JSON.parse(n.subarray(69).toString("utf8"))}catch{return null}if(!o||typeof o!="object")return null;let s=o,i=s.origin,a=s.feature,c=s.expiry;return typeof i!="string"||typeof a!="string"||typeof c!="number"||!Number.isFinite(c)||c<0||c>Hs?null:{origin:i,feature:a,expiry:c,isSubdomain:s.isSubdomain===!0,isThirdParty:s.isThirdParty===!0}}function qs(e){return e.toLowerCase().replace(/[^a-z]/g,"").includes("modelcontext")}function Ks(e,t,n){let r,o;try{r=new URL(e),o=new URL(t)}catch{return!1}if(r.protocol!==o.protocol)return!1;let s=r.hostname.toLowerCase(),i=o.hostname.toLowerCase();return s===i?!0:n&&i.endsWith(`.${s}`)}function Gn(e,t,n){let r=e.map(s=>s.trim()).filter(s=>s.length>0);if(r.length===0)return null;let o=null;for(let s of r){let i=Gs(s);if(!i)continue;let a=qs(i.feature),c=i.expiry*1e3>n.getTime(),l=Ks(i.origin,t,i.isSubdomain),u=a&&c&&l,d=u?3:a?2:1;(!o||d>o.rank)&&(o={parsed:i,valid:u,rank:d})}return o?{present:!0,valid:o.valid,origin:o.parsed.origin,feature:o.parsed.feature,expiresAt:new Date(o.parsed.expiry*1e3).toISOString()}:{present:!0,valid:!1}}function qn(e){return e?e.split(",").map(t=>t.trim()).filter(t=>t.length>0):[]}var $t="capture-incomplete:";function Ys(e){return e.imperative!==null||e.polyfillPackages.length>0}function Kn(e){return e.blocked?"blocked":e.loadError?"load-error":e.toolCount>0?e.nativeApi||e.originTrialValid||e.declarativeToolCount>0?"active":"testing-only":e.nativeApi?"api-empty":e.shimTakenOver||Ys(e.staticSignals)?"declared-inactive":"absent"}function Yn(e,t){switch(e){case"blocked":return"waf-blocked";case"load-error":return"unreachable";case"active":case"testing-only":{let n=t.filter(r=>r.via==="imperative");return n.length>0&&n.every(r=>!r.hasExecute)?"stub-only":"ok"}case"api-empty":case"declared-inactive":case"absent":return"no-tools";default:return e}}var Vn={"shared-experience":30,"task-completion":25,"tool-quality":25,trust:20},Rt={"page-experience":{title:"Page experience",category:"shared-experience",weight:20,docSlug:"page-experience"},"human-parity":{title:"Human parity",category:"shared-experience",weight:10,docSlug:"human-parity"},"tool-selection":{title:"Tool selection",category:"task-completion",weight:15,docSlug:"tool-selection"},"coverage-vs-site-type":{title:"Coverage vs. site type",category:"task-completion",weight:10,docSlug:"coverage-vs-site-type"},"schema-validity":{title:"Schema validity",category:"tool-quality",weight:4,docSlug:"schema-validity"},"schema-quality":{title:"Schema quality",category:"tool-quality",weight:4,docSlug:"schema-quality"},"description-quality":{title:"Description quality",category:"tool-quality",weight:5,docSlug:"description-quality"},"stub-detection":{title:"Stub detection",category:"tool-quality",weight:4,docSlug:"stub-detection"},"canonical-entry-point":{title:"Canonical entry point",category:"tool-quality",weight:3,docSlug:"canonical-entry-point"},"naming-quality":{title:"Naming quality",category:"tool-quality",weight:2,docSlug:"naming-quality"},"registration-errors":{title:"Registration errors",category:"tool-quality",weight:2,docSlug:"registration-errors"},"registration-timing":{title:"Registration timing",category:"tool-quality",weight:1,docSlug:"registration-timing"},"annotations-present":{title:"Annotations present",category:"trust",weight:6,docSlug:"annotations-present"},"annotation-mismatch":{title:"Annotation mismatch",category:"trust",weight:6,docSlug:"annotation-mismatch"},"injection-surface":{title:"Injection surface",category:"trust",weight:4,docSlug:"injection-surface"},"untrusted-content-hint":{title:"Untrusted content hint",category:"trust",weight:4,docSlug:"untrusted-content-hint"}},oe="1";function Vs(e,t,n){return!!(t["cf-mitigated"]==="challenge"||e===403&&n.includes("cf-browser-verification")||e===503&&n.includes("challenge-platform"))}function Xn(e,t,n){return!!(Vs(e,t,n)||t["x-vercel-mitigated"]==="challenge"||"x-vercel-challenge-token"in t||n.includes("Vercel Security Checkpoint")||n.includes("vercel-challenge")||e===429&&n.length<2e3||e===403&&(n.includes("Access Denied")||n.includes("Bot Protection")))}var Xs=100,Zn=4096,zs=32768,Zs=50,Qs=200,zn="__oraWebmcpCapture",Qn=`(function () {
41
44
  "use strict";
42
45
  try {
43
46
  var W = typeof globalThis !== "undefined" ? globalThis : window;
44
- if (W.${an}) return;
47
+ if (W.${zn}) return;
45
48
 
46
- var SHIM_VERSION = ${JSON.stringify(X)};
47
- var MAX_TOOLS = ${qo};
48
- var MAX_DESCRIPTION_CHARS = ${cn};
49
- var MAX_SCHEMA_CHARS = ${Ko};
50
- var MAX_ERRORS = ${Vo};
49
+ var SHIM_VERSION = ${JSON.stringify(oe)};
50
+ var MAX_TOOLS = ${Xs};
51
+ var MAX_DESCRIPTION_CHARS = ${Zn};
52
+ var MAX_SCHEMA_CHARS = ${zs};
53
+ var MAX_ERRORS = ${Zs};
51
54
  // Internal bound only: a page looping on addEventListener must not grow
52
55
  // the shim's retained set without limit.
53
56
  var MAX_LISTENERS = 50;
@@ -501,7 +504,7 @@ ${C.map(M=>` ${M.id.padEnd(12)} ${Ye(M)}`).join(`
501
504
  // Non-writable and non-configurable: the capture payload is the audit's
502
505
  // evidence, so a page must not be able to replace snapshot() and report
503
506
  // whatever tools it wishes it had.
504
- nativeDefineProperty(W, ${JSON.stringify(an)}, {
507
+ nativeDefineProperty(W, ${JSON.stringify(zn)}, {
505
508
  value: {
506
509
  shimVersion: SHIM_VERSION,
507
510
  installedAt: now(),
@@ -518,9 +521,9 @@ ${C.map(M=>` ${M.id.padEnd(12)} ${Ye(M)}`).join(`
518
521
  // Nothing left to report to; never let the shim break the page.
519
522
  }
520
523
  }
521
- })();`,un=`(function () {
522
- var MAX_FORMS = ${Yo};
523
- var MAX_DESCRIPTION_CHARS = ${cn};
524
+ })();`,er=`(function () {
525
+ var MAX_FORMS = ${Qs};
526
+ var MAX_DESCRIPTION_CHARS = ${Zn};
524
527
  var forms = [];
525
528
  var nodes = document.querySelectorAll("form[toolname], [toolname]");
526
529
  for (var i = 0; i < nodes.length && forms.length < MAX_FORMS; i++) {
@@ -536,8 +539,8 @@ ${C.map(M=>` ${M.id.padEnd(12)} ${Ye(M)}`).join(`
536
539
  });
537
540
  }
538
541
  return { forms: forms };
539
- })()`;var pn=["@mcp-b/global","@mcp-b/react-webmcp","usewebmcp"];function Xo(e){let t=e.toLowerCase(),n=/document\.modelcontext/.test(t),r=/navigator\.modelcontext/.test(t),o=/modelcontext\??\.(registertool|providecontext)/.test(t),i=pn.find(a=>t.includes(a));return!n&&!r&&!o&&!i?null:{marker:n?"document.modelContext":r?"navigator.modelContext":o?"modelContext.registerTool/provideContext":`${i} package`,deprecatedAliasOnly:r&&!n}}var zo=["webmcp","web model context protocol"];function dn(e){let t=e.toLowerCase();return zo.some(n=>t.includes(n))}function mn(e,t,n){let r=[t,...n.map(a=>a.body)],o=Xo(r.join(`
540
- `)),i=new Set;for(let a of r){let c=a.toLowerCase();for(let l of pn)c.includes(l)&&i.add(l)}let s=dn(e)||r.some(dn);return{imperative:o,polyfillPackages:[...i],keywordMention:s}}var fn=15e3,Qo=3e4,Zo=2e3,ei=250,ti={fast:12e3,deep:2e4},ni=2*1024*1024,yn=512,ri=512,oi=60,ii=15e5,bn={width:1280,height:720},gn={imperative:null,polyfillPackages:[],keywordMention:!1},si=`(function () {
542
+ })()`;var nr=["@mcp-b/global","@mcp-b/react-webmcp","usewebmcp"];function ei(e){let t=e.toLowerCase(),n=/document\.modelcontext/.test(t),r=/navigator\.modelcontext/.test(t),o=/modelcontext\??\.(registertool|providecontext)/.test(t),s=nr.find(a=>t.includes(a));return!n&&!r&&!o&&!s?null:{marker:n?"document.modelContext":r?"navigator.modelContext":o?"modelContext.registerTool/provideContext":`${s} package`,deprecatedAliasOnly:r&&!n}}var ti=["webmcp","web model context protocol"];function tr(e){let t=e.toLowerCase();return ti.some(n=>t.includes(n))}function rr(e,t,n){let r=[t,...n.map(a=>a.body)],o=ei(r.join(`
543
+ `)),s=new Set;for(let a of r){let c=a.toLowerCase();for(let l of nr)c.includes(l)&&s.add(l)}let i=tr(e)||r.some(tr);return{imperative:o,polyfillPackages:[...s],keywordMention:i}}var ir=15e3,ni=3e4,ri=2e3,oi=250,si={fast:12e3,deep:2e4},ii=2*1024*1024,ar=512,ai=512,ci=60,li=15e5,cr={width:1280,height:720},or={imperative:null,polyfillPackages:[],keywordMention:!1},ui=`(function () {
541
544
  var tokens = [];
542
545
  try {
543
546
  var metas = document.querySelectorAll('meta[http-equiv="origin-trial" i]');
@@ -555,14 +558,14 @@ ${C.map(M=>` ${M.id.padEnd(12)} ${Ye(M)}`).join(`
555
558
  // A hostile getter on either global; absence is the honest answer.
556
559
  }
557
560
  return { nativeApi: nativeApi, metaTokens: tokens };
558
- })()`,wn=`(function () {
561
+ })()`,lr=`(function () {
559
562
  try {
560
563
  var g = window.__oraWebmcpCapture;
561
564
  return g ? g.snapshot() : null;
562
565
  } catch (e) {
563
566
  return null;
564
567
  }
565
- })()`,ai=`(function () {
568
+ })()`,di=`(function () {
566
569
  try {
567
570
  var g = window.__oraWebmcpCapture;
568
571
  if (!g) return "none";
@@ -572,26 +575,26 @@ ${C.map(M=>` ${M.id.padEnd(12)} ${Ye(M)}`).join(`
572
575
  } catch (e) {
573
576
  return "error";
574
577
  }
575
- })()`;function vn(e,t){return e.filter(n=>!n.unregistered).map(n=>({name:n.name.slice(0,yn),description:n.description,via:"imperative",entryPoint:n.source==="provideContext"?"provideContext":n.entryPoint,pageUrl:t,inputSchema:n.inputSchema,annotations:li(n.annotations),hasExecute:n.hasExecute,registrationMs:n.registrationMs}))}function ci(e,t){return e.map(n=>({name:n.toolName.slice(0,yn),description:n.toolDescription,via:"declarative",entryPoint:"form",pageUrl:t,inputSchema:null,annotations:{},hasExecute:!0,registrationMs:null}))}function li(e){if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e,n={};for(let r of["readOnlyHint","destructiveHint","idempotentHint","openWorldHint","untrustedContentHint"])typeof t[r]=="boolean"&&(n[r]=t[r]);return typeof t.title=="string"&&(n.title=t.title.slice(0,ri)),n}function ui(e){if(!e)return[];let t=[...e.registrationErrors];return e.takenOver.length>0&&t.push(`${ot} the page replaced modelContext on ${e.takenOver.join(", ")}, so imperative tools may be under-reported`),e.extraToolCount>0&&t.push(`${ot} the capture's tool cap was reached and ${e.extraToolCount} further registration attempts were not stored`),t}function di(e){if(!e)return null;for(let t of e.split(",")){let n=/^\s*([a-z0-9-]+)\s*=\s*(.*)$/i.exec(t);if(!n||!n[1].toLowerCase().replace(/-/g,"").includes("modelcontext"))continue;let r=n[2].trim().replace(/^\(|\)$/g,"").trim();return r==="*"?!0:r===""||r.toLowerCase()==="self"?!1:r.split(/\s+/).some(o=>o.toLowerCase()!=="self"&&o.length>0)}return null}async function pi(e,t,n,r){let o=Date.now(),i={finalUrl:t,navMs:0,blocked:!1,nativeApi:!1,originTrialTokens:[],permissionsPolicy:null,html:"",inlineJs:"",scripts:[],screenshot:null,loadError:null},s=null;try{s=await e.newContext({entryUrl:t,viewport:bn});let a;try{a=await s.goto(t,_e(n,fn))}catch(h){return{...i,navMs:Date.now()-o,loadError:$e(h)}}let c=Date.now()-o;await s.waitForLoad(_e(n,5e3));let l=a?.headers??{},u=a?.status??0,d=(await s.content()).slice(0,ni),g=await s.inlineScripts(),p=await s.evaluate(si).catch(()=>null)??{},f=r?await yi(s,n):null;return{finalUrl:s.url(),navMs:c,blocked:sn(u,l,d),nativeApi:p.nativeApi===!0,originTrialTokens:[...tn(l["origin-trial"]),...Array.isArray(p.metaTokens)?p.metaTokens:[]],permissionsPolicy:l["permissions-policy"]??null,html:d,inlineJs:g,scripts:s.collectedScripts(),screenshot:f,loadError:null}}catch(a){return{...i,navMs:Date.now()-o,loadError:$e(a)}}finally{await s?.close()}}async function mi(e,t,n,r,o){let i=null;try{i=await e.newContext({initScripts:[ln],entryUrl:t,viewport:bn});try{await i.goto(t,_e(r,fn))}catch(l){return{snapshot:null,declarative:null,quietMs:0,loadError:$e(l)}}let s=await gi(i,n,r,o),a=await i.evaluate(wn).catch(()=>null),c=await i.evaluate(un).catch(()=>null);return{snapshot:a,declarative:c,quietMs:s,loadError:null}}catch(s){return{snapshot:null,declarative:null,quietMs:0,loadError:$e(s)}}finally{await i?.close()}}async function gi(e,t,n,r){let o=Date.now(),i=Math.min(ti[t],Math.max(0,n-o)),s=null,a=o;for(;Date.now()-o<i;){let c=await e.evaluate(ai).catch(()=>null);if(c!==s)s=typeof c=="string"?c:null,a=Date.now(),r&&await hi(e,r);else if(Date.now()-a>=Zo)break;if(await wi(Math.min(ei,Math.max(0,n-Date.now()))),Date.now()>=n)break}return Date.now()-o}async function hi(e,t){let n=await e.evaluate(wn).catch(()=>null);n&&t(vn(n.tools,e.url()))}async function fi(e,t,n,r,o){let i=Date.now(),s=i+Qo,a=await pi(e,t,s,r),l=a.loadError!==null||a.blocked?{snapshot:null,declarative:null,quietMs:0,loadError:null}:await mi(e,t,n,s,o),u=a.loadError??l.loadError,d=l.snapshot,g=(l.declarative?.forms??[]).filter(ae=>ae.toolName.trim()!==""),p=a.finalUrl||t,f=d?vn(d.tools,p):[],h=ci(g,p),m=[...f,...h],y=bi(a.html,a.inlineJs,a.scripts),A=en(a.originTrialTokens,hn(p)??hn(t)??"",new Date),C={loadError:u,blocked:a.blocked,nativeApi:a.nativeApi,originTrialValid:A?.valid===!0,declarativeToolCount:h.length,toolCount:m.length,shimTakenOver:(d?.takenOver.length??0)>0,staticSignals:y},se=nn(C);return{page:{url:t,finalUrl:p,verdict:se,status:rn(se,m),tools:m,declarativeFormCount:h.length,consumer:{nativeApi:a.nativeApi,originTrial:A,permissionsPolicy:a.permissionsPolicy,iframeAllow:di(a.permissionsPolicy)},staticSignals:y,apiSurface:{toolchangeEvents:d?.toolchangeEvents??0,provideContextCalls:d?.provideContextCalls??0,registrationErrors:ui(d)},timing:{navMs:a.navMs,quietMs:l.quietMs,totalMs:Date.now()-i},error:u},screenshot:a.blocked?null:a.screenshot}}async function Sn(e){let{url:t,endpoint:n,mode:r="fast",screenshot:o=!0,onTools:i}=e,s=Date.now(),a=new Date().toISOString(),c=await Ae.connect(n);try{let l=await fi(c,t,r,o,i);return{url:t,pages:[l.page],chromeVersion:c.product,shimVersion:X,capturedAt:a,durationMs:Date.now()-s,screenshot:l.screenshot}}finally{c.close()}}async function yi(e,t){let n=await e.screenshot(oi,_e(t,5e3));if(!n||n.byteLength===0||n.byteLength>ii)return null;let r=e.viewportSize();return{data:n.toString("base64"),mimeType:"image/jpeg",width:r?.width??0,height:r?.height??0}}function bi(e,t,n){if(!e)return gn;try{return mn(e,t,n)}catch{return gn}}function hn(e){try{return new URL(e).origin}catch{return null}}function $e(e){return(e instanceof Error?e.message:String(e)).split(`
576
- `)[0].slice(0,300)}function _e(e,t){return Math.max(250,Math.min(t,e-Date.now()))}function wi(e){return new Promise(t=>setTimeout(t,e))}var xn=require("child_process"),W=require("fs"),An=require("os"),at=require("path");var $n=9222;async function _n(e){if(e)try{return{ok:!0,endpoint:await rt(e),close:async()=>{},launched:!1}}catch(t){let n=st(t);return{ok:!1,message:[`No debuggable Chrome answered at ${e}.`,...n.startsWith("no debuggable Chrome answered")?[]:[n],"",...vi($n)].join(`
577
- `)}}try{let t=await Ei();return{ok:!0,endpoint:t.endpoint,close:t.close,launched:!0}}catch(t){return{ok:!1,message:st(t)}}}function Rn(e){return e.pages.some(t=>t.consumer.nativeApi)?["This Chrome provides WebMCP itself. ora captures with a browser that does not,","so anything that depended on the browser rather than on your page can read","differently there.","","Where that actually changed a result, ora says so in the availability reason","above - read that rather than this. This notice only reports what the browser","did, because deciding whether it changed the outcome is ora's job, not the","CLI's.","","If you started Chrome with --enable-features=WebMCPTesting, drop the flag (or","omit --chrome-endpoint and let this command start its own).","","Keep a flag-enabled Chrome for `npx @ora-ai/webmcp-verify`, which needs the API","present in order to call your tools."].join(`
578
- `):null}function vi(e){return["The audit drives a Chrome you already have; it never downloads one.","Start one with a debugging port and a scratch profile:","",` ${Cn(e)}`,"","Then re-run this command. Point at a different one with --chrome-endpoint.","","Do not add --enable-features=WebMCPTesting: the audit measures whether a","real browser gives an agent WebMCP on your page, and a browser that","provides it itself answers yes for every site."]}function Cn(e){let t=process.platform==="darwin"?'"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"':process.platform==="win32"?'"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"':"google-chrome",n=process.platform==="win32"?"%TEMP%\\ax-webmcp":"/tmp/ax-webmcp";return`${t} --remote-debugging-port=${e} --user-data-dir=${n}`}function st(e){return e instanceof x||e instanceof Error?e.message:String(e)}function Si(){let e=process.env.CHROME_PATH;return e?[e]:process.platform==="darwin"?["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium","/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary"]:process.platform==="win32"?[process.env.PROGRAMFILES,process.env["PROGRAMFILES(X86)"],process.env.LOCALAPPDATA].filter(n=>!!n).map(n=>`${n}\\Google\\Chrome\\Application\\chrome.exe`):["/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/usr/bin/chromium","/usr/bin/chromium-browser","/opt/google/chrome/chrome","/snap/bin/chromium"]}function ki(){for(let e of Si())try{if((0,W.statSync)(e).isFile())return e}catch{}return null}var xi=["--headless=new","--disable-gpu","--mute-audio","--no-first-run","--no-default-browser-check","--disable-background-networking","--disable-sync","--disable-extensions","--force-webrtc-ip-handling-policy=disable_non_proxied_udp"];function Ai(){return process.env.AX_WEBMCP_NO_SANDBOX==="1"}var kn=2e4,$i=3e3,_i=4,Ri=150;function Ci(e,t){return e.exitCode!==null||e.signalCode!==null?Promise.resolve():new Promise(n=>{let r=()=>{clearTimeout(o),e.off("exit",r),n()},o=setTimeout(r,t);e.once("exit",r)})}async function Ei(){let e=ki();if(!e)throw new x(Ii());let t=(0,W.mkdtempSync)((0,at.join)((0,An.tmpdir)(),"ax-webmcp-")),n=(0,xn.spawn)(e,[...xi,...Ai()?["--no-sandbox"]:[],"--remote-debugging-port=0",`--user-data-dir=${t}`,"about:blank"],{stdio:"ignore",detached:!0}),r=i=>{o().finally(()=>{process.removeListener("SIGINT",r),process.removeListener("SIGTERM",r),process.kill(process.pid,i)})},o=async()=>{process.removeListener("SIGINT",r),process.removeListener("SIGTERM",r);let i=n.pid;try{i!==void 0?process.kill(-i,"SIGTERM"):n.kill("SIGTERM")}catch{try{n.kill("SIGTERM")}catch{}}await Ci(n,$i),await Pi(t)};process.once("SIGINT",r),process.once("SIGTERM",r);try{let i=await Ti(t,n);return{endpoint:await rt(`127.0.0.1:${i}`),close:o}}catch(i){throw await o(),i instanceof x?i:new x(st(i))}}async function Ti(e,t){let n=(0,at.join)(e,"DevToolsActivePort"),r=Date.now()+kn;for(;Date.now()<r;){if(t.exitCode!==null)throw new x(`Chrome exited with code ${t.exitCode} before it was ready.`);try{let o=(0,W.readFileSync)(n,"utf8").split(`
579
- `)[0]?.trim(),i=Number(o);if(Number.isInteger(i)&&i>0)return i}catch{}await new Promise(o=>setTimeout(o,100))}throw new x(`Chrome did not publish a debugging port within ${kn/1e3}s.`)}async function Pi(e){for(let t=0;t<_i;t++){try{if((0,W.rmSync)(e,{recursive:!0,force:!0}),!(0,W.existsSync)(e))return}catch{}await new Promise(n=>setTimeout(n,Ri))}try{(0,W.rmSync)(e,{recursive:!0,force:!0})}catch{}}function Ii(){return["No Chrome found on this machine.","","The audit opens your page in a real browser, because WebMCP tools only","exist inside a live page. This package never downloads one.","","Install Chrome (https://google.com/chrome), or point at one you already","have with CHROME_PATH=/path/to/chrome, or start one yourself and pass","--chrome-endpoint:","",` ${Cn($n)}`].join(`
580
- `)}var Mi="https://ora.ai",Oi=12e4,I=class extends Error{code;retryAfterMs;constructor(t,n={}){super(t),this.name="WebmcpIngestError",this.code=n.code??null,this.retryAfterMs=n.retryAfterMs??null}},En=4*1024*1024,Tn=10,Pn=100,In=32768,Mn=4096,On=512;function Nn(e){if(e.shimVersion!==X)return`this build captures with shim version ${e.shimVersion}, which is not the version it was built against (${X})`;if(e.pages.length>Tn)return`capture covers ${e.pages.length} pages; the limit is ${Tn}`;for(let t of e.pages){if(t.tools.length>Pn)return`${t.url} registered ${t.tools.length} tools; the limit is ${Pn} per page`;for(let n of t.tools){if(n.name.length>On)return`tool name on ${t.url} is ${n.name.length} characters; the limit is ${On}`;if(n.description.length>Mn)return`description for "${n.name}" is ${n.description.length} characters; the limit is ${Mn}`;for(let[r,o]of[["inputSchema",n.inputSchema],["annotations",n.annotations]]){let i=Ni(o);if(i===null)return`${r} for "${n.name}" could not be serialized (a cycle, or a value JSON cannot carry)`;if(i.length>In)return`${r} for "${n.name}" serializes to ${i.length} characters; the limit is ${In}`}}}return null}function jn(e){let t=e.screenshot;if(!t)return{capture:e,droppedScreenshot:!1};let n=t.data.length>2*1024*1024,r=t.mimeType!=="image/jpeg";return!n&&!r?{capture:e,droppedScreenshot:!1}:{capture:{...e,screenshot:null},droppedScreenshot:!0}}function Ni(e){try{return JSON.stringify(e)??"null"}catch{return null}}async function Ln(e,t,n={}){let r=(n.baseUrl??process.env.ORA_API_URL??Mi).replace(/\/+$/,""),o=n.idleMs??Oi,i=F(o),s=()=>new I(`ora scoring timed out \u2014 no progress for ${Math.round(o/1e3)}s`),a=JSON.stringify({url:e,capture:t});if(Buffer.byteLength(a,"utf8")>En)throw i.disarm(),new I(`this capture serializes to ${Math.round(Buffer.byteLength(a,"utf8")/1024)} KB; the ingest limit is ${En/1024/1024} MB`,{code:"BODY_TOO_LARGE"});let c;try{c=await fetch(`${r}/api/webmcp/audit/ingest`,{method:"POST",headers:{accept:"text/event-stream","content-type":"application/json",...n.apiKey?{authorization:`Bearer ${n.apiKey}`}:{}},body:a,signal:i.signal})}catch(l){throw i.disarm(),i.tripped()?s():new I(`ora ingest request failed: ${l instanceof Error?l.message:String(l)}`)}if(!c.ok||!c.body)throw i.disarm(),await ji(c);return Li(c,i,n,s)}async function ji(e){let t=await e.clone().json().catch(()=>null),n=t?.code??null;if(e.status===429){let r=Number(e.headers.get("retry-after")),o=t?.retry_after_ms??(Number.isFinite(r)&&r>0?r*1e3:null),i=o?` \u2014 retry in ${Math.ceil(o/1e3)}s`:"";return new I(`ora rate limit exceeded${i} (10/min and 20 per 24h per IP). An ora API key lifts these limits: set ORA_API_KEY or pass --api-key.`,{code:n??"RATE_LIMITED",retryAfterMs:o})}return n==="SHIM_VERSION_MISMATCH"?new I(`This ax build captures with a shim ora no longer scores, so the audit was refused.
578
+ })()`;function ur(e,t){return e.filter(n=>!n.unregistered).map(n=>({name:n.name.slice(0,ar),description:n.description,via:"imperative",entryPoint:n.source==="provideContext"?"provideContext":n.entryPoint,pageUrl:t,inputSchema:n.inputSchema,annotations:mi(n.annotations),hasExecute:n.hasExecute,registrationMs:n.registrationMs}))}function pi(e,t){return e.map(n=>({name:n.toolName.slice(0,ar),description:n.toolDescription,via:"declarative",entryPoint:"form",pageUrl:t,inputSchema:null,annotations:{},hasExecute:!0,registrationMs:null}))}function mi(e){if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e,n={};for(let r of["readOnlyHint","destructiveHint","idempotentHint","openWorldHint","untrustedContentHint"])typeof t[r]=="boolean"&&(n[r]=t[r]);return typeof t.title=="string"&&(n.title=t.title.slice(0,ai)),n}function hi(e){if(!e)return[];let t=[...e.registrationErrors];return e.takenOver.length>0&&t.push(`${$t} the page replaced modelContext on ${e.takenOver.join(", ")}, so imperative tools may be under-reported`),e.extraToolCount>0&&t.push(`${$t} the capture's tool cap was reached and ${e.extraToolCount} further registration attempts were not stored`),t}function gi(e){if(!e)return null;for(let t of e.split(",")){let n=/^\s*([a-z0-9-]+)\s*=\s*(.*)$/i.exec(t);if(!n||!n[1].toLowerCase().replace(/-/g,"").includes("modelcontext"))continue;let r=n[2].trim().replace(/^\(|\)$/g,"").trim();return r==="*"?!0:r===""||r.toLowerCase()==="self"?!1:r.split(/\s+/).some(o=>o.toLowerCase()!=="self"&&o.length>0)}return null}async function fi(e,t,n,r){let o=Date.now(),s={finalUrl:t,navMs:0,blocked:!1,nativeApi:!1,originTrialTokens:[],permissionsPolicy:null,html:"",inlineJs:"",scripts:[],screenshot:null,loadError:null},i=null;try{i=await e.newContext({entryUrl:t,viewport:cr});let a;try{a=await i.goto(t,He(n,ir))}catch(g){return{...s,navMs:Date.now()-o,loadError:Je(g)}}let c=Date.now()-o;await i.waitForLoad(He(n,5e3));let l=a?.headers??{},u=a?.status??0,d=(await i.content()).slice(0,ii),h=await i.inlineScripts(),m=await i.evaluate(ui).catch(()=>null)??{},f=r?await Si(i,n):null;return{finalUrl:i.url(),navMs:c,blocked:Xn(u,l,d),nativeApi:m.nativeApi===!0,originTrialTokens:[...qn(l["origin-trial"]),...Array.isArray(m.metaTokens)?m.metaTokens:[]],permissionsPolicy:l["permissions-policy"]??null,html:d,inlineJs:h,scripts:i.collectedScripts(),screenshot:f,loadError:null}}catch(a){return{...s,navMs:Date.now()-o,loadError:Je(a)}}finally{await i?.close()}}async function yi(e,t,n,r,o){let s=null;try{s=await e.newContext({initScripts:[Qn],entryUrl:t,viewport:cr});try{await s.goto(t,He(r,ir))}catch(l){return{snapshot:null,declarative:null,quietMs:0,loadError:Je(l)}}let i=await bi(s,n,r,o),a=await s.evaluate(lr).catch(()=>null),c=await s.evaluate(er).catch(()=>null);return{snapshot:a,declarative:c,quietMs:i,loadError:null}}catch(i){return{snapshot:null,declarative:null,quietMs:0,loadError:Je(i)}}finally{await s?.close()}}async function bi(e,t,n,r){let o=Date.now(),s=Math.min(si[t],Math.max(0,n-o)),i=null,a=o;for(;Date.now()-o<s;){let c=await e.evaluate(di).catch(()=>null);if(c!==i)i=typeof c=="string"?c:null,a=Date.now(),r&&await wi(e,r);else if(Date.now()-a>=ri)break;if(await Ai(Math.min(oi,Math.max(0,n-Date.now()))),Date.now()>=n)break}return Date.now()-o}async function wi(e,t){let n=await e.evaluate(lr).catch(()=>null);n&&t(ur(n.tools,e.url()))}async function vi(e,t,n,r,o){let s=Date.now(),i=s+ni,a=await fi(e,t,i,r),l=a.loadError!==null||a.blocked?{snapshot:null,declarative:null,quietMs:0,loadError:null}:await yi(e,t,n,i,o),u=a.loadError??l.loadError,d=l.snapshot,h=(l.declarative?.forms??[]).filter(Se=>Se.toolName.trim()!==""),m=a.finalUrl||t,f=d?ur(d.tools,m):[],g=pi(h,m),p=[...f,...g],y=xi(a.html,a.inlineJs,a.scripts),A=Gn(a.originTrialTokens,sr(m)??sr(t)??"",new Date),T={loadError:u,blocked:a.blocked,nativeApi:a.nativeApi,originTrialValid:A?.valid===!0,declarativeToolCount:g.length,toolCount:p.length,shimTakenOver:(d?.takenOver.length??0)>0,staticSignals:y},ve=Kn(T);return{page:{url:t,finalUrl:m,verdict:ve,status:Yn(ve,p),tools:p,declarativeFormCount:g.length,consumer:{nativeApi:a.nativeApi,originTrial:A,permissionsPolicy:a.permissionsPolicy,iframeAllow:gi(a.permissionsPolicy)},staticSignals:y,apiSurface:{toolchangeEvents:d?.toolchangeEvents??0,provideContextCalls:d?.provideContextCalls??0,registrationErrors:hi(d)},timing:{navMs:a.navMs,quietMs:l.quietMs,totalMs:Date.now()-s},error:u},screenshot:a.blocked?null:a.screenshot}}async function dr(e){let{url:t,endpoint:n,mode:r="fast",screenshot:o=!0,onTools:s}=e,i=Date.now(),a=new Date().toISOString(),c=await Be.connect(n);try{let l=await vi(c,t,r,o,s);return{url:t,pages:[l.page],chromeVersion:c.product,shimVersion:oe,capturedAt:a,durationMs:Date.now()-i,screenshot:l.screenshot}}finally{c.close()}}async function Si(e,t){let n=await e.screenshot(ci,He(t,5e3));if(!n||n.byteLength===0||n.byteLength>li)return null;let r=e.viewportSize();return{data:n.toString("base64"),mimeType:"image/jpeg",width:r?.width??0,height:r?.height??0}}function xi(e,t,n){if(!e)return or;try{return rr(e,t,n)}catch{return or}}function sr(e){try{return new URL(e).origin}catch{return null}}function Je(e){return(e instanceof Error?e.message:String(e)).split(`
579
+ `)[0].slice(0,300)}function He(e,t){return Math.max(250,Math.min(t,e-Date.now()))}function Ai(e){return new Promise(t=>setTimeout(t,e))}var mr=require("child_process"),B=require("fs"),hr=require("os"),Tt=require("path");var gr=9222;async function fr(e){if(e)try{return{ok:!0,endpoint:await kt(e),close:async()=>{},launched:!1}}catch(t){let n=Et(t);return{ok:!1,message:[`No debuggable Chrome answered at ${e}.`,...n.startsWith("no debuggable Chrome answered")?[]:[n],"",...ki(gr)].join(`
580
+ `)}}try{let t=await Ii();return{ok:!0,endpoint:t.endpoint,close:t.close,launched:!0}}catch(t){return{ok:!1,message:Et(t)}}}function yr(e){return e.pages.some(t=>t.consumer.nativeApi)?["This Chrome provides WebMCP itself. ora captures with a browser that does not,","so anything that depended on the browser rather than on your page can read","differently there.","","Where that actually changed a result, ora says so in the availability reason","above - read that rather than this. This notice only reports what the browser","did, because deciding whether it changed the outcome is ora's job, not the","CLI's.","","If you started Chrome with --enable-features=WebMCPTesting, drop the flag (or","omit --chrome-endpoint and let this command start its own).","","Keep a flag-enabled Chrome for `npx @ora-ai/webmcp-verify`, which needs the API","present in order to call your tools."].join(`
581
+ `):null}function ki(e){return["The audit drives a Chrome you already have; it never downloads one.","Start one with a debugging port and a scratch profile:","",` ${br(e)}`,"","Then re-run this command. Point at a different one with --chrome-endpoint.","","Do not add --enable-features=WebMCPTesting: the audit measures whether a","real browser gives an agent WebMCP on your page, and a browser that","provides it itself answers yes for every site."]}function br(e){let t=process.platform==="darwin"?'"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"':process.platform==="win32"?'"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"':"google-chrome",n=process.platform==="win32"?"%TEMP%\\ax-webmcp":"/tmp/ax-webmcp";return`${t} --remote-debugging-port=${e} --user-data-dir=${n}`}function Et(e){return e instanceof R||e instanceof Error?e.message:String(e)}function $i(){let e=process.env.CHROME_PATH;return e?[e]:process.platform==="darwin"?["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium","/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary"]:process.platform==="win32"?[process.env.PROGRAMFILES,process.env["PROGRAMFILES(X86)"],process.env.LOCALAPPDATA].filter(n=>!!n).map(n=>`${n}\\Google\\Chrome\\Application\\chrome.exe`):["/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/usr/bin/chromium","/usr/bin/chromium-browser","/opt/google/chrome/chrome","/snap/bin/chromium"]}function Ri(){for(let e of $i())try{if((0,B.statSync)(e).isFile())return e}catch{}return null}var Ei=["--headless=new","--disable-gpu","--mute-audio","--no-first-run","--no-default-browser-check","--disable-background-networking","--disable-sync","--disable-extensions","--force-webrtc-ip-handling-policy=disable_non_proxied_udp"];function Ti(){return process.env.AX_WEBMCP_NO_SANDBOX==="1"}var pr=2e4,_i=3e3,Ci=4,Pi=150;function Oi(e,t){return e.exitCode!==null||e.signalCode!==null?Promise.resolve():new Promise(n=>{let r=()=>{clearTimeout(o),e.off("exit",r),n()},o=setTimeout(r,t);e.once("exit",r)})}async function Ii(){let e=Ri();if(!e)throw new R(Ni());let t=(0,B.mkdtempSync)((0,Tt.join)((0,hr.tmpdir)(),"ax-webmcp-")),n=(0,mr.spawn)(e,[...Ei,...Ti()?["--no-sandbox"]:[],"--remote-debugging-port=0",`--user-data-dir=${t}`,"about:blank"],{stdio:"ignore",detached:!0}),r=s=>{o().finally(()=>{process.removeListener("SIGINT",r),process.removeListener("SIGTERM",r),process.kill(process.pid,s)})},o=async()=>{process.removeListener("SIGINT",r),process.removeListener("SIGTERM",r);let s=n.pid;try{s!==void 0?process.kill(-s,"SIGTERM"):n.kill("SIGTERM")}catch{try{n.kill("SIGTERM")}catch{}}await Oi(n,_i),await Li(t)};process.once("SIGINT",r),process.once("SIGTERM",r);try{let s=await Mi(t,n);return{endpoint:await kt(`127.0.0.1:${s}`),close:o}}catch(s){throw await o(),s instanceof R?s:new R(Et(s))}}async function Mi(e,t){let n=(0,Tt.join)(e,"DevToolsActivePort"),r=Date.now()+pr;for(;Date.now()<r;){if(t.exitCode!==null)throw new R(`Chrome exited with code ${t.exitCode} before it was ready.`);try{let o=(0,B.readFileSync)(n,"utf8").split(`
582
+ `)[0]?.trim(),s=Number(o);if(Number.isInteger(s)&&s>0)return s}catch{}await new Promise(o=>setTimeout(o,100))}throw new R(`Chrome did not publish a debugging port within ${pr/1e3}s.`)}async function Li(e){for(let t=0;t<Ci;t++){try{if((0,B.rmSync)(e,{recursive:!0,force:!0}),!(0,B.existsSync)(e))return}catch{}await new Promise(n=>setTimeout(n,Pi))}try{(0,B.rmSync)(e,{recursive:!0,force:!0})}catch{}}function Ni(){return["No Chrome found on this machine.","","The audit opens your page in a real browser, because WebMCP tools only","exist inside a live page. This package never downloads one.","","Install Chrome (https://google.com/chrome), or point at one you already","have with CHROME_PATH=/path/to/chrome, or start one yourself and pass","--chrome-endpoint:","",` ${br(gr)}`].join(`
583
+ `)}var ji="https://ora.ai",Ui=12e4,L=class extends Error{code;retryAfterMs;constructor(t,n={}){super(t),this.name="WebmcpIngestError",this.code=n.code??null,this.retryAfterMs=n.retryAfterMs??null}},wr=4*1024*1024,vr=10,Sr=100,xr=32768,Ar=4096,kr=512;function $r(e){if(e.shimVersion!==oe)return`this build captures with shim version ${e.shimVersion}, which is not the version it was built against (${oe})`;if(e.pages.length>vr)return`capture covers ${e.pages.length} pages; the limit is ${vr}`;for(let t of e.pages){if(t.tools.length>Sr)return`${t.url} registered ${t.tools.length} tools; the limit is ${Sr} per page`;for(let n of t.tools){if(n.name.length>kr)return`tool name on ${t.url} is ${n.name.length} characters; the limit is ${kr}`;if(n.description.length>Ar)return`description for "${n.name}" is ${n.description.length} characters; the limit is ${Ar}`;for(let[r,o]of[["inputSchema",n.inputSchema],["annotations",n.annotations]]){let s=Di(o);if(s===null)return`${r} for "${n.name}" could not be serialized (a cycle, or a value JSON cannot carry)`;if(s.length>xr)return`${r} for "${n.name}" serializes to ${s.length} characters; the limit is ${xr}`}}}return null}function Rr(e){let t=e.screenshot;if(!t)return{capture:e,droppedScreenshot:!1};let n=t.data.length>2*1024*1024,r=t.mimeType!=="image/jpeg";return!n&&!r?{capture:e,droppedScreenshot:!1}:{capture:{...e,screenshot:null},droppedScreenshot:!0}}function Di(e){try{return JSON.stringify(e)??"null"}catch{return null}}async function Er(e,t,n={}){let r=(n.baseUrl??process.env.ORA_API_URL??ji).replace(/\/+$/,""),o=n.idleMs??Ui,s=Y(o),i=()=>new L(`ora scoring timed out \u2014 no progress for ${Math.round(o/1e3)}s`),a=JSON.stringify({url:e,capture:t});if(Buffer.byteLength(a,"utf8")>wr)throw s.disarm(),new L(`this capture serializes to ${Math.round(Buffer.byteLength(a,"utf8")/1024)} KB; the ingest limit is ${wr/1024/1024} MB`,{code:"BODY_TOO_LARGE"});let c;try{c=await fetch(`${r}/api/webmcp/audit/ingest`,{method:"POST",headers:{accept:"text/event-stream","content-type":"application/json",...n.apiKey?{authorization:`Bearer ${n.apiKey}`}:{}},body:a,signal:s.signal})}catch(l){throw s.disarm(),s.tripped()?i():new L(`ora ingest request failed: ${l instanceof Error?l.message:String(l)}`)}if(!c.ok||!c.body)throw s.disarm(),await Wi(c);return Fi(c,s,n,i)}async function Wi(e){let t=await e.clone().json().catch(()=>null),n=t?.code??null;if(e.status===429){let r=Number(e.headers.get("retry-after")),o=t?.retry_after_ms??(Number.isFinite(r)&&r>0?r*1e3:null),s=o?` \u2014 retry in ${Math.ceil(o/1e3)}s`:"";return new L(`ora rate limit exceeded${s} (10/min and 20 per 24h per IP). An ora API key lifts these limits: set ORA_API_KEY or pass --api-key.`,{code:n??"RATE_LIMITED",retryAfterMs:o})}return n==="SHIM_VERSION_MISMATCH"?new L(`This ax build captures with a shim ora no longer scores, so the audit was refused.
581
584
  Upgrade with \`npm i -g ax@latest\` (or \`npx ax@latest webmcp-audit \u2026\`) and run it again.
582
585
 
583
- ora said: ${t?.error??"shim version mismatch"}`,{code:n}):e.status===503?new I(`ora cannot score right now: ${Wi(t?.error??"scoring is unavailable")} Nothing was spent against your rate limit; try again shortly.`,{code:n??"SCORING_UNAVAILABLE"}):new I(`ora ingest failed: ${t?.error??await H(e)}`,{code:n})}async function Li(e,t,n,r){let o=new TextDecoder,i="",s;try{e:for await(let a of e.body){t.poke(),i=`${i}${o.decode(a,{stream:!0})}`.replace(/\r\n?/g,`
584
- `);let c=i.indexOf(`
586
+ ora said: ${t?.error??"shim version mismatch"}`,{code:n}):e.status===503?new L(`ora cannot score right now: ${Bi(t?.error??"scoring is unavailable")} Nothing was spent against your rate limit; try again shortly.`,{code:n??"SCORING_UNAVAILABLE"}):new L(`ora ingest failed: ${t?.error??await V(e)}`,{code:n})}async function Fi(e,t,n,r){let o=new TextDecoder,s="",i;try{e:for await(let a of e.body){t.poke(),s=`${s}${o.decode(a,{stream:!0})}`.replace(/\r\n?/g,`
587
+ `);let c=s.indexOf(`
585
588
 
586
- `);for(;c!==-1;){let l=Di(i.slice(0,c));if(i=i.slice(c+2),c=i.indexOf(`
589
+ `);for(;c!==-1;){let l=Ji(s.slice(0,c));if(s=s.slice(c+2),c=s.indexOf(`
587
590
 
588
- `),!l)continue;let u;try{u=JSON.parse(l)}catch{continue}if(n.onEvent?.(u),u.type==="error")throw new I(`ora audit failed: ${u.message}`,{code:u.status});if(u.type==="done"){s=u.audit;break e}}}}catch(a){throw t.tripped()?r():a instanceof I?a:new I(`ora ingest stream failed: ${a instanceof Error?a.message:String(a)}`)}finally{t.disarm()}if(!s)throw new I("ora ingest stream ended before the audit completed");return s}function Wi(e){let t=e.trim();return/[.!?]$/.test(t)?t:`${t}.`}function Di(e){let t=[];for(let n of e.split(`
591
+ `),!l)continue;let u;try{u=JSON.parse(l)}catch{continue}if(n.onEvent?.(u),u.type==="error")throw new L(`ora audit failed: ${u.message}`,{code:u.status});if(u.type==="done"){i=u.audit;break e}}}}catch(a){throw t.tripped()?r():a instanceof L?a:new L(`ora ingest stream failed: ${a instanceof Error?a.message:String(a)}`)}finally{t.disarm()}if(!i)throw new L("ora ingest stream ended before the audit completed");return i}function Bi(e){let t=e.trim();return/[.!?]$/.test(t)?t:`${t}.`}function Ji(e){let t=[];for(let n of e.split(`
589
592
  `))n.startsWith("data:")&&t.push(n.slice(5).replace(/^ /,""));return t.join(`
590
- `)}var b=U(D(),1);var ct=12,Bi=["fail","warning","unmeasured","na","pass"],lt={fail:["\u2716",b.default.red],warning:["\u25B2",b.default.yellow],unmeasured:["?",b.default.magenta],na:["\u2013",b.default.dim],pass:["\u2714",b.default.green]},Ui={fail:"Failing",warning:"Warnings",unmeasured:"Not measured",na:"Not applicable",pass:"Passing"},Ji=["shared-experience","task-completion","tool-quality","trust"],Fi={"shared-experience":"Shared experience","task-completion":"Task completion","tool-quality":"Tool quality",trust:"Trust"};function Wn(e,t={}){let n=G(80,120),r=e.availability.status==="ready";return["",...Hi(e,n),"",...qi(e.availability,n),...r?["",...Ki(e,n),"",...Yi(e)]:[],"",...zi(e.findings,n,t.showPassing===!0),...es(e.simulation,n),"",...ts(e,n)]}function Hi(e,t){let n=[` ${b.default.bold(_(e.url))}`],r=`${e.toolCount} tool${e.toolCount===1?"":"s"}`,o=[Gi(e.verdict),r,`Chrome ${_(e.chromeVersion)}`];return e.error&&o.push(b.default.red(_(e.error))),n.push(` ${b.default.dim(o.join(" \xB7 "))}`),n.map(i=>Dn(i,t))}function Gi(e){switch(e){case"active":return b.default.green("active");case"testing-only":case"declared-inactive":case"api-empty":return b.default.yellow(e);case"blocked":case"load-error":return b.default.red(e);default:return b.default.dim(e)}}function qi(e,t){let[n,r]=e.status==="ready"?["agent-ready",b.default.green]:e.status==="not-ready"?["not agent-ready",b.default.red]:["availability unknown",b.default.yellow],o=[` ${r(b.default.bold(n))}`];for(let i of e.reasons)o.push(...T(_(i.detail),t-4).map(s=>` ${b.default.dim(s)}`));return e.status==="not-ready"&&o.push(...T("No score is reported for a page an agent cannot use yet: the reasons above are what to fix first.",t-4).map(i=>` ${b.default.dim(i)}`)),o}function Ki(e,t){let n=e.score===null?"\u2014":String(e.score),r=[` ${b.default.bold(`${n}/100`)} ${Vi(e)}`];return e.grade===null&&e.score!==null&&r.push(...T(`The grade is withheld because only ${e.evidenceCoverage}% of the applicable check weight was actually measured. The score above still stands; the "Not measured" checks below are what is missing.`,t-4).map(o=>` ${b.default.dim(o)}`)),r}function Vi(e){return e.grade!==null?b.default.bold(b.default.green(`grade ${e.grade}`)):b.default.dim("grade withheld")}function Yi(e){let t=[` ${b.default.bold("Pillars")}`];for(let n of Ji){let r=e.categoryScores[n]??0,o=on[n],i=e.findings.some(c=>it[c.checkId]?.category===n&&c.status!=="na"&&c.status!=="unmeasured"),s=i?Xi(r):b.default.dim("\u2591".repeat(ct)),a=i?`weight ${o}`:`weight ${o} \xB7 nothing measured`;t.push(` ${Fi[n].padEnd(18)} ${s} ${String(r).padStart(3)}% ${b.default.dim(a)}`)}return t}function Xi(e){let t=Math.round(Math.min(100,Math.max(0,e))/100*ct);return`${(e>=75?b.default.green:e>=40?b.default.yellow:b.default.red)("\u2588".repeat(t))}${b.default.dim("\u2591".repeat(ct-t))}`}function zi(e,t,n){let r=[` ${b.default.bold("Checks")}`];for(let o of Bi){let i=e.filter(s=>s.status===o);if(i.length!==0){if(o==="pass"&&!n){r.push(` ${b.default.dim(`${i.length} passing (--show-passing to list)`)}`);continue}r.push("",` ${b.default.bold(Ui[o])} (${i.length})`);for(let s of i)r.push(...Qi(s,t))}}return e.length===0&&r.push(` ${b.default.dim("no checks reported")}`),r}function Qi(e,t){let[n,r]=lt[e.status],o=Zi(e.checkId),s=[` ${r(n)} ${o}${e.toolName?b.default.dim(` ${_(e.toolName)}`):""}`];return e.details&&s.push(...T(_(e.details),t-10).map(a=>` ${b.default.dim(a)}`)),e.evidence&&s.push(...T(_(e.evidence),t-10).map(a=>` ${b.default.dim(a)}`)),s}function Zi(e){return it[e]?.title??e}function es(e,t){if(!e)return[];let n=["",` ${b.default.bold("Tool selection")}`];if(e.skipped)return n.push(...T(_(e.skipReason??"The selection simulation did not run."),t-4).map(o=>` ${b.default.dim(o)}`)),n;let r=Math.round(e.accuracy*100);n.push(` ${r}% of ${e.steps.length} intent${e.steps.length===1?"":"s"} picked the right tool ${b.default.dim(_(e.model))}`);for(let o of e.steps){let[i,s]=o.ok?lt.pass:lt.fail,a=o.chosenTool?_(o.chosenTool):b.default.dim("nothing");n.push(` ${s(i)} ${Dn(_(o.intent),t-30)} ${b.default.dim("\u2192")} ${a}`)}return n}function ts(e,t){let n=e.source==="local"?"Captured by your own browser and scored without being stored \u2014 this result is not published or ranked anywhere. Run the audit at webmcp.ora.ai for a public one.":"";return n?T(n,t-4).map(r=>` ${b.default.dim(r)}`):[]}function Dn(e,t){return e.length>t?`${e.slice(0,t-1)}\u2026`:e}var N={OK:0,BELOW_MIN_SCORE:1,USAGE:2,API:3};function ns(e){let t=e.trim();if(!(!t||/\s/.test(t)))try{let n=new URL(t.includes("://")?t:`http://${t}`);return n.protocol!=="http:"&&n.protocol!=="https:"?void 0:n.toString()}catch{return}}function rs(e){if(e===void 0)return{};let t=Number(e);return e.trim()===""||!Number.isInteger(t)||t<0||t>100?{error:`--min-score must be an integer between 0 and 100, got ${JSON.stringify(e)}`}:{value:t}}async function Bn(e){let t=ns(e.url);if(!t)return console.error(`Not an auditable URL: ${JSON.stringify(e.url)}`),console.error("Pass the page you want audited, e.g. http://localhost:3000"),N.USAGE;let n=rs(e.minScore);if(n.error)return console.error(n.error),N.USAGE;let r=await _n(e.chromeEndpoint);if(!r.ok)return console.error(r.message),N.USAGE;e.json||k.start(r.launched?`Starting Chrome and capturing ${t}`:`Capturing ${t}`);let o;try{o=await Sn({url:t,endpoint:r.endpoint,onTools:d=>{e.json||k.update(`Capturing ${t} \u2014 ${d.length} tools`)}})}catch(d){return k.stop(),console.error(`Capture failed: ${d instanceof Error?d.message:String(d)}`),N.API}finally{await r.close()}let i=o.pages[0];if(i?.error)return k.stop(),console.error(`Could not capture ${t}: ${i.error}`),console.error("Is the dev server running?"),N.USAGE;let s=Nn(o);if(s)return k.stop(),console.error(`ora would refuse this capture: ${s}`),N.USAGE;let{capture:a,droppedScreenshot:c}=jn(o);e.json||k.update("Scoring with ora");let l;try{l=await Ln(t,a,{apiKey:e.apiKey??process.env.ORA_API_KEY,onEvent:d=>{e.json||k.update(os(d))}})}catch(d){return k.stop(),d instanceof I?(console.error(d.message),N.API):(console.error(`Scoring failed: ${d instanceof Error?d.message:String(d)}`),N.API)}if(k.stop(),e.json)console.log(JSON.stringify(l,null,2));else for(let d of Wn(l,{showPassing:e.showPassing}))console.log(d);c&&console.error("Note: the screenshot exceeded ora's 2 MB limit and was not sent, so page-experience could not be graded.");let u=Rn(o);if(u&&console.error(`
593
+ `)}var b=G(J(),1);var _t=12,Hi=["fail","warning","unmeasured","na","pass"],Ct={fail:["\u2716",b.default.red],warning:["\u25B2",b.default.yellow],unmeasured:["?",b.default.magenta],na:["\u2013",b.default.dim],pass:["\u2714",b.default.green]},Gi={fail:"Failing",warning:"Warnings",unmeasured:"Not measured",na:"Not applicable",pass:"Passing"},qi=["shared-experience","task-completion","tool-quality","trust"],Ki={"shared-experience":"Shared experience","task-completion":"Task completion","tool-quality":"Tool quality",trust:"Trust"};function Tr(e,t={}){let n=X(80,120),r=e.availability.status==="ready";return["",...Yi(e,n),"",...Xi(e.availability,n),...r?["",...zi(e,n),"",...Qi(e)]:[],"",...ta(e.findings,n,t.showPassing===!0),...oa(e.simulation,n),"",...sa(e,n)]}function Yi(e,t){let n=[` ${b.default.bold(C(e.url))}`],r=`${e.toolCount} tool${e.toolCount===1?"":"s"}`,o=[Vi(e.verdict),r,`Chrome ${C(e.chromeVersion)}`];return e.error&&o.push(b.default.red(C(e.error))),n.push(` ${b.default.dim(o.join(" \xB7 "))}`),n.map(s=>_r(s,t))}function Vi(e){switch(e){case"active":return b.default.green("active");case"testing-only":case"declared-inactive":case"api-empty":return b.default.yellow(e);case"blocked":case"load-error":return b.default.red(e);default:return b.default.dim(e)}}function Xi(e,t){let[n,r]=e.status==="ready"?["agent-ready",b.default.green]:e.status==="not-ready"?["not agent-ready",b.default.red]:["availability unknown",b.default.yellow],o=[` ${r(b.default.bold(n))}`];for(let s of e.reasons)o.push(...M(C(s.detail),t-4).map(i=>` ${b.default.dim(i)}`));return e.status==="not-ready"&&o.push(...M("No score is reported for a page an agent cannot use yet: the reasons above are what to fix first.",t-4).map(s=>` ${b.default.dim(s)}`)),o}function zi(e,t){let n=e.score===null?"\u2014":String(e.score),r=[` ${b.default.bold(`${n}/100`)} ${Zi(e)}`];return e.grade===null&&e.score!==null&&r.push(...M(`The grade is withheld because only ${e.evidenceCoverage}% of the applicable check weight was actually measured. The score above still stands; the "Not measured" checks below are what is missing.`,t-4).map(o=>` ${b.default.dim(o)}`)),r}function Zi(e){return e.grade!==null?b.default.bold(b.default.green(`grade ${e.grade}`)):b.default.dim("grade withheld")}function Qi(e){let t=[` ${b.default.bold("Pillars")}`];for(let n of qi){let r=e.categoryScores[n]??0,o=Vn[n],s=e.findings.some(c=>Rt[c.checkId]?.category===n&&c.status!=="na"&&c.status!=="unmeasured"),i=s?ea(r):b.default.dim("\u2591".repeat(_t)),a=s?`weight ${o}`:`weight ${o} \xB7 nothing measured`;t.push(` ${Ki[n].padEnd(18)} ${i} ${String(r).padStart(3)}% ${b.default.dim(a)}`)}return t}function ea(e){let t=Math.round(Math.min(100,Math.max(0,e))/100*_t);return`${(e>=75?b.default.green:e>=40?b.default.yellow:b.default.red)("\u2588".repeat(t))}${b.default.dim("\u2591".repeat(_t-t))}`}function ta(e,t,n){let r=[` ${b.default.bold("Checks")}`];for(let o of Hi){let s=e.filter(i=>i.status===o);if(s.length!==0){if(o==="pass"&&!n){r.push(` ${b.default.dim(`${s.length} passing (--show-passing to list)`)}`);continue}r.push("",` ${b.default.bold(Gi[o])} (${s.length})`);for(let i of s)r.push(...na(i,t))}}return e.length===0&&r.push(` ${b.default.dim("no checks reported")}`),r}function na(e,t){let[n,r]=Ct[e.status],o=ra(e.checkId),i=[` ${r(n)} ${o}${e.toolName?b.default.dim(` ${C(e.toolName)}`):""}`];return e.details&&i.push(...M(C(e.details),t-10).map(a=>` ${b.default.dim(a)}`)),e.evidence&&i.push(...M(C(e.evidence),t-10).map(a=>` ${b.default.dim(a)}`)),i}function ra(e){return Rt[e]?.title??e}function oa(e,t){if(!e)return[];let n=["",` ${b.default.bold("Tool selection")}`];if(e.skipped)return n.push(...M(C(e.skipReason??"The selection simulation did not run."),t-4).map(o=>` ${b.default.dim(o)}`)),n;let r=Math.round(e.accuracy*100);n.push(` ${r}% of ${e.steps.length} intent${e.steps.length===1?"":"s"} picked the right tool ${b.default.dim(C(e.model))}`);for(let o of e.steps){let[s,i]=o.ok?Ct.pass:Ct.fail,a=o.chosenTool?C(o.chosenTool):b.default.dim("nothing");n.push(` ${i(s)} ${_r(C(o.intent),t-30)} ${b.default.dim("\u2192")} ${a}`)}return n}function sa(e,t){let n=e.source==="local"?"Captured by your own browser and scored without being stored \u2014 this result is not published or ranked anywhere. Run the audit at webmcp.ora.ai for a public one.":"";return n?M(n,t-4).map(r=>` ${b.default.dim(r)}`):[]}function _r(e,t){return e.length>t?`${e.slice(0,t-1)}\u2026`:e}var D={OK:0,BELOW_MIN_SCORE:1,USAGE:2,API:3};function ia(e){let t=e.trim();if(!(!t||/\s/.test(t)))try{let n=new URL(t.includes("://")?t:`http://${t}`);return n.protocol!=="http:"&&n.protocol!=="https:"?void 0:n.toString()}catch{return}}function aa(e){if(e===void 0)return{};let t=Number(e);return e.trim()===""||!Number.isInteger(t)||t<0||t>100?{error:`--min-score must be an integer between 0 and 100, got ${JSON.stringify(e)}`}:{value:t}}async function Cr(e){let t=ia(e.url);if(!t)return console.error(`Not an auditable URL: ${JSON.stringify(e.url)}`),console.error("Pass the page you want audited, e.g. http://localhost:3000"),D.USAGE;let n=aa(e.minScore);if(n.error)return console.error(n.error),D.USAGE;let r=await fr(e.chromeEndpoint);if(!r.ok)return console.error(r.message),D.USAGE;e.json||$.start(r.launched?`Starting Chrome and capturing ${t}`:`Capturing ${t}`);let o;try{o=await dr({url:t,endpoint:r.endpoint,onTools:d=>{e.json||$.update(`Capturing ${t} \u2014 ${d.length} tools`)}})}catch(d){return $.stop(),console.error(`Capture failed: ${d instanceof Error?d.message:String(d)}`),D.API}finally{await r.close()}let s=o.pages[0];if(s?.error)return $.stop(),console.error(`Could not capture ${t}: ${s.error}`),console.error("Is the dev server running?"),D.USAGE;let i=$r(o);if(i)return $.stop(),console.error(`ora would refuse this capture: ${i}`),D.USAGE;let{capture:a,droppedScreenshot:c}=Rr(o);e.json||$.update("Scoring with ora");let l;try{l=await Er(t,a,{apiKey:e.apiKey??process.env.ORA_API_KEY,onEvent:d=>{e.json||$.update(ca(d))}})}catch(d){return $.stop(),d instanceof L?(console.error(d.message),D.API):(console.error(`Scoring failed: ${d instanceof Error?d.message:String(d)}`),D.API)}if($.stop(),e.json)console.log(JSON.stringify(l,null,2));else for(let d of Tr(l,{showPassing:e.showPassing}))console.log(d);c&&console.error("Note: the screenshot exceeded ora's 2 MB limit and was not sent, so page-experience could not be graded.");let u=yr(o);if(u&&console.error(`
591
594
  ${u}`),n.value!==void 0){if(l.availability.status!=="ready")return e.json||console.log(`
592
595
  Not agent-ready, so there is no score to compare against --min-score ${n.value}
593
- `),N.BELOW_MIN_SCORE;if(l.score===null)return e.json||console.error(`
594
- ora returned no score, so --min-score cannot be evaluated.`),N.API;if(l.score<n.value)return e.json||console.log(`
596
+ `),D.BELOW_MIN_SCORE;if(l.score===null)return e.json||console.error(`
597
+ ora returned no score, so --min-score cannot be evaluated.`),D.API;if(l.score<n.value)return e.json||console.log(`
595
598
  Score ${l.score} is below the required minimum ${n.value}
596
- `),N.BELOW_MIN_SCORE}return N.OK}function os(e){switch(e.type){case"phase":return`Scoring with ora \u2014 ${e.phase}`;case"tool-discovered":return`Scoring with ora \u2014 found ${_(e.tool.name)}`;case"finding":return`Scoring with ora \u2014 ${e.finding.checkId}`;case"simulation-step":return`Scoring with ora \u2014 simulating "${_(e.step.intent)}"`;default:return"Scoring with ora"}}function Un(){if(typeof process.loadEnvFile!="function")return!1;try{return process.loadEnvFile(),!0}catch{return!1}}var q="ax",is={meta:{name:"audit",description:"Score a site's agent readiness (exit codes: 0 ok, 1 below --min-score, 2 usage, 3 API error)"},args:{url:{type:"positional",description:"URL or domain to audit (e.g. https://docs.example.com)",required:!0},json:{type:"boolean",description:"Print the raw ora audit payload as JSON",default:!1},"min-score":{type:"string",description:"Exit 1 when the score is below this threshold (0-100); the CI gate"},"max-age":{type:"string",description:"Accept a cached result up to this many seconds old (server default 6h)"},force:{type:"boolean",description:"Bypass the cache and rescan (spends the stricter 6/day force budget)",default:!1},"tunnel-cmd":{type:"string",description:"Command that exposes a local target and prints its public https URL (e.g. 'ngrok http 3000 --log stdout'); also read from ORA_TUNNEL_CMD. The result is stored as ephemeral"},"api-key":{type:"string",description:"ora-issued scan API key that lifts the scan rate limits; also read from ORA_SCAN_API_KEY"},"show-passing":{type:"boolean",description:"List each passing check individually",default:!1},"show-skipped":{type:"boolean",description:"List not-applicable / pending checks too",default:!1}},async run({args:e}){process.exitCode=await Ot({url:e.url,json:!!e.json,showSkipped:!!e["show-skipped"],showPassing:!!e["show-passing"],minScore:e["min-score"],maxAge:e["max-age"],force:!!e.force,tunnelCmd:e["tunnel-cmd"],apiKey:e["api-key"]})}},ss={meta:{name:"journey",description:"Send a real AI agent at a site and watch it navigate live"},args:{intent:{type:"positional",description:'Goal for the agent (e.g. "Find the API docs and how to auth")',required:!0},domain:{type:"string",description:"Site the agent targets (e.g. stripe.com)"},harness:{type:"string",description:"Agent harness: claude-code, codex, openclaw, hermess, claude-agent, eve, \u2026",default:"claude-code"},model:{type:"string",description:"Model override (harness default when omitted)"},json:{type:"boolean",description:"Output as JSON",default:!1}},async run({args:e}){process.exitCode=await qt({intent:e.intent,domain:e.domain,harness:e.harness,model:e.model,json:!!e.json})}},as={meta:{name:"deep-journey",description:"Run a real AI agent at a site on a curated task \u2014 or, with a partner API key, a free-text one \u2014 via ora's public API (exit codes: 0 ok, 1 run failed, 2 usage, 3 API error)"},args:{url:{type:"positional",description:"URL or domain the agent targets (e.g. stripe.com)",required:!0},intent:{type:"string",description:"Curated intent id (see GET /api/journey/intents; server default when omitted)"},agent:{type:"string",description:"Agent id (see GET /api/journey/agents); defaults to cas-haiku (Claude Code \xB7 Haiku 4.5)"},json:{type:"boolean",description:"Print the terminal run detail as JSON",default:!1},task:{type:"string",description:"Free-text task for the agent (needs a partner API key; mutually exclusive with --intent)"},"api-key":{type:"string",description:"ora-issued partner API key: unlocks --task and the 1000/24h keyed allowance; also read from ORA_PARTNER_API_KEY"},"no-stream":{type:"boolean",description:"Skip the live trajectory stream and poll for the result instead",default:!1}},async run({args:e}){process.exitCode=await Gt({url:e.url,intent:e.intent,task:e.task,apiKey:e["api-key"],agent:e.agent,json:!!e.json,noStream:!!e["no-stream"]})}},cs={meta:{name:"skill",description:"List, print, or install ora's agent skills (digest-verified from the registry, never bundled)"},args:{name:{type:"positional",description:"Skill name (omit to list the registry)",required:!1},install:{type:"boolean",description:"Write <dir>/<name>/SKILL.md instead of printing",default:!1},dir:{type:"string",description:"Install directory (default .claude/skills)"},json:{type:"boolean",description:"Print the raw registry index as JSON",default:!1}},async run({args:e}){process.exitCode=await zt({name:e.name,install:!!e.install,dir:e.dir,json:!!e.json})}},ls={meta:{name:"webmcp-audit",description:"Audit a page's WebMCP tools in a real browser - localhost included, so you can check before you publish (exit codes: 0 ok, 1 below --min-score, 2 usage, 3 API error)"},args:{url:{type:"positional",description:"Page to audit, scheme included (e.g. http://localhost:3000)",required:!0},"chrome-endpoint":{type:"string",description:"Drive a Chrome you started instead of launching one: ws:// URL, http origin, or host:port"},"min-score":{type:"string",description:"Exit 1 when the score is below this threshold (0-100); the CI gate"},"api-key":{type:"string",description:"ora API key that lifts the ingest rate limits; also read from ORA_API_KEY"},json:{type:"boolean",description:"Print the raw ora audit payload as JSON",default:!1},"show-passing":{type:"boolean",description:"List each passing check individually",default:!1}},async run({args:e}){process.exitCode=await Bn({url:e.url,json:!!e.json,showPassing:!!e["show-passing"],minScore:e["min-score"],chromeEndpoint:e["chrome-endpoint"],apiKey:e["api-key"]})}};function us(){let e=Re.default.green("$"),t=Re.default.dim;return["",` ${Re.default.bold(q)} ${t(`v${Oe.version}`)}`,` ${t("Score any site's agent readiness \u2014 and watch real AI agents navigate it")}`,"",` ${t("Commands:")}`,` audit ${t("<url>")} ${t("Score a site's agent readiness")}`,` webmcp-audit ${t("<url>")} ${t("Audit a WebMCP surface in a real browser, localhost included")}`,` deep-journey ${t("<url>")} ${t("Run a real agent at a site on a curated or free-text task")}`,` journey ${t("<intent>")} ${t("Send a real agent at a site and watch it live (workspace)")}`,` skill ${t("[name]")} ${t("List, print, or install ora's agent skills")}`,"",` ${t("Examples:")}`,` ${e} ${q} audit https://docs.example.com`,` ${e} ${q} audit https://docs.example.com --min-score 70 ${t("# CI gate")}`,` ${e} ${q} audit https://docs.example.com --json`,` ${e} ${q} webmcp-audit http://localhost:3000`,` ${e} ${q} deep-journey stripe.com --intent pricing`,` ${e} ${q} journey "Find the API docs and how to authenticate" --domain stripe.com`,"",` ${t("audit options:")}`,` --min-score <n> ${t("Exit 1 when the score is below n (0-100); the CI gate")}`,` --max-age <s> ${t("Accept a cached result up to s seconds old (default 6h)")}`,` --force ${t("Bypass the cache and rescan (6/day budget)")}`,` --tunnel-cmd <c> ${t("Expose a local target via your own tunnel command (e.g. 'ngrok http 3000 --log stdout')")}`,` --api-key <k> ${t("ora-issued scan API key that lifts the rate limits; also read from ORA_SCAN_API_KEY")}`,` --json ${t("Print the raw ora audit payload as JSON")}`,` --show-passing ${t("List each passing check (hidden by default)")}`,` --show-skipped ${t("List skipped checks (hidden by default)")}`,"",` ${t("audit exit codes:")}`,` ${t("0 success \xB7 1 below --min-score \xB7 2 usage error \xB7 3 API unreachable/rate-limited")}`,"",` ${t("webmcp-audit options:")}`,` --chrome-endpoint ${t("<e> Drive a Chrome you started: ws:// URL, http origin, or host:port")}`,` --min-score <n> ${t("Exit 1 when the score is below n (0-100); the CI gate")}`,` --api-key <k> ${t("ora API key that lifts the ingest rate limits; also read from ORA_API_KEY")}`,` --json ${t("Print the raw ora audit payload as JSON")}`,` --show-passing ${t("List each passing check (hidden by default)")}`,` ${t("starts a headless Chrome you already have installed; never downloads one")}`,` ${t("scored by ora, stored nowhere: the result is never published or ranked")}`,"",` ${t("deep-journey options:")}`,` --intent <id> ${t("Curated task id, e.g. pricing, signup, api-docs (server default when omitted)")}`,` --task <text> ${t("Free-text task (needs a partner API key; replaces --intent)")}`,` --api-key <k> ${t("ora partner API key: unlocks --task + 1000 runs/24h; also read from ORA_PARTNER_API_KEY")}`,` --agent <id> ${t("Agent to run (default: cas-haiku \u2014 Claude Code \xB7 Haiku 4.5)")}`,` --no-stream ${t("Poll for the result instead of streaming the trajectory")}`,` --json ${t("Print the terminal run detail as JSON")}`,` ${t("no key needed \xB7 public caps: 100 runs/24h per target, 200 runs/24h per IP")}`,"",` ${t("journey options:")}`,` --domain <d> ${t("Site the agent targets (e.g. stripe.com)")}`,` --harness <h> ${t("Agent harness: claude-code (default), codex, openclaw, hermess, claude-agent, eve, \u2026")}`,` --model <m> ${t("Model override (harness default when omitted)")}`,` --json ${t("Output as JSON")}`,` ${t("requires ORA_API_KEY (see .env.example)")}`,""].join(`
597
- `)}var ds={meta:{name:q,version:Oe.version,description:"Score any site's agent readiness \u2014 and watch real AI agents navigate it"},subCommands:{audit:is,"webmcp-audit":ls,"deep-journey":as,journey:ss,skill:cs},setup(){let e=process.argv[2];(!e||e==="--help"||e==="-h")&&(console.log(us()),process.exit(0))}};Un();wt(ds);
599
+ `),D.BELOW_MIN_SCORE}return D.OK}function ca(e){switch(e.type){case"phase":return`Scoring with ora \u2014 ${e.phase}`;case"tool-discovered":return`Scoring with ora \u2014 found ${C(e.tool.name)}`;case"finding":return`Scoring with ora \u2014 ${e.finding.checkId}`;case"simulation-step":return`Scoring with ora \u2014 simulating "${C(e.step.intent)}"`;default:return"Scoring with ora"}}function Pr(){if(typeof process.loadEnvFile!="function")return!1;try{return process.loadEnvFile(),!0}catch{return!1}}var K="ax",la={meta:{name:"audit",description:"Score a site's agent readiness (exit codes: 0 ok, 1 below --min-score, 2 usage, 3 API error)"},args:{url:{type:"positional",description:"URL or domain to audit (e.g. https://docs.example.com)",required:!0},json:{type:"boolean",description:"Print the raw ora audit payload as JSON",default:!1},"min-score":{type:"string",description:"Exit 1 when the score is below this threshold (0-100); the CI gate"},"max-age":{type:"string",description:"Accept a cached result up to this many seconds old (server default 6h)"},force:{type:"boolean",description:"Bypass the cache and rescan (spends the stricter 6/day force budget)",default:!1},tunnel:{type:"string",description:"Open ora's own tunnel to a local target (value: ora); needs ORA_API_KEY with the tunnels:write + tunnels:connect scopes. Also read from ORA_TUNNEL. The result is stored as ephemeral"},"tunnel-cmd":{type:"string",description:"Bring your own tunnel: a command that exposes a local target and prints its public https URL (e.g. 'ngrok http 3000 --log stdout'); also read from ORA_TUNNEL_CMD. The result is stored as ephemeral"},"api-key":{type:"string",description:"ora-issued scan API key that lifts the scan rate limits; also read from ORA_SCAN_API_KEY"},"show-passing":{type:"boolean",description:"List each passing check individually",default:!1},"show-skipped":{type:"boolean",description:"List not-applicable / pending checks too",default:!1}},async run({args:e}){process.exitCode=await $n({url:e.url,json:!!e.json,showSkipped:!!e["show-skipped"],showPassing:!!e["show-passing"],minScore:e["min-score"],maxAge:e["max-age"],force:!!e.force,tunnelCmd:e["tunnel-cmd"],tunnel:e.tunnel,apiKey:e["api-key"]})}},ua={meta:{name:"journey",description:"Send a real AI agent at a site and watch it navigate live"},args:{intent:{type:"positional",description:'Goal for the agent (e.g. "Find the API docs and how to auth")',required:!0},domain:{type:"string",description:"Site the agent targets (e.g. stripe.com)"},harness:{type:"string",description:"Agent harness: claude-code, codex, openclaw, hermess, claude-agent, eve, \u2026",default:"claude-code"},model:{type:"string",description:"Model override (harness default when omitted)"},json:{type:"boolean",description:"Output as JSON",default:!1}},async run({args:e}){process.exitCode=await jn({intent:e.intent,domain:e.domain,harness:e.harness,model:e.model,json:!!e.json})}},da={meta:{name:"deep-journey",description:"Run a real AI agent at a site on a curated task \u2014 or, with a partner API key, a free-text one \u2014 via ora's public API (exit codes: 0 ok, 1 run failed, 2 usage, 3 API error)"},args:{url:{type:"positional",description:"URL or domain the agent targets (e.g. stripe.com)",required:!0},intent:{type:"string",description:"Curated intent id (see GET /api/journey/intents; server default when omitted)"},agent:{type:"string",description:"Agent id (see GET /api/journey/agents); defaults to cas-haiku (Claude Code \xB7 Haiku 4.5)"},json:{type:"boolean",description:"Print the terminal run detail as JSON",default:!1},task:{type:"string",description:"Free-text task for the agent (needs a partner API key; mutually exclusive with --intent)"},"api-key":{type:"string",description:"ora-issued partner API key: unlocks --task and the 1000/24h keyed allowance; also read from ORA_PARTNER_API_KEY"},"no-stream":{type:"boolean",description:"Skip the live trajectory stream and poll for the result instead",default:!1}},async run({args:e}){process.exitCode=await Nn({url:e.url,intent:e.intent,task:e.task,apiKey:e["api-key"],agent:e.agent,json:!!e.json,noStream:!!e["no-stream"]})}},pa={meta:{name:"skill",description:"List, print, or install ora's agent skills (digest-verified from the registry, never bundled)"},args:{name:{type:"positional",description:"Skill name (omit to list the registry)",required:!1},install:{type:"boolean",description:"Write <dir>/<name>/SKILL.md instead of printing",default:!1},dir:{type:"string",description:"Install directory (default .claude/skills)"},json:{type:"boolean",description:"Print the raw registry index as JSON",default:!1}},async run({args:e}){process.exitCode=await Bn({name:e.name,install:!!e.install,dir:e.dir,json:!!e.json})}},ma={meta:{name:"webmcp-audit",description:"Audit a page's WebMCP tools in a real browser - localhost included, so you can check before you publish (exit codes: 0 ok, 1 below --min-score, 2 usage, 3 API error)"},args:{url:{type:"positional",description:"Page to audit, scheme included (e.g. http://localhost:3000)",required:!0},"chrome-endpoint":{type:"string",description:"Drive a Chrome you started instead of launching one: ws:// URL, http origin, or host:port"},"min-score":{type:"string",description:"Exit 1 when the score is below this threshold (0-100); the CI gate"},"api-key":{type:"string",description:"ora API key that lifts the ingest rate limits; also read from ORA_API_KEY"},json:{type:"boolean",description:"Print the raw ora audit payload as JSON",default:!1},"show-passing":{type:"boolean",description:"List each passing check individually",default:!1}},async run({args:e}){process.exitCode=await Cr({url:e.url,json:!!e.json,showPassing:!!e["show-passing"],minScore:e["min-score"],chromeEndpoint:e["chrome-endpoint"],apiKey:e["api-key"]})}};function ha(){let e=Ge.default.green("$"),t=Ge.default.dim;return["",` ${Ge.default.bold(K)} ${t(`v${he.version}`)}`,` ${t("Score any site's agent readiness \u2014 and watch real AI agents navigate it")}`,"",` ${t("Commands:")}`,` audit ${t("<url>")} ${t("Score a site's agent readiness")}`,` webmcp-audit ${t("<url>")} ${t("Audit a WebMCP surface in a real browser, localhost included")}`,` deep-journey ${t("<url>")} ${t("Run a real agent at a site on a curated or free-text task")}`,` journey ${t("<intent>")} ${t("Send a real agent at a site and watch it live (workspace)")}`,` skill ${t("[name]")} ${t("List, print, or install ora's agent skills")}`,"",` ${t("Examples:")}`,` ${e} ${K} audit https://docs.example.com`,` ${e} ${K} audit https://docs.example.com --min-score 70 ${t("# CI gate")}`,` ${e} ${K} audit https://docs.example.com --json`,` ${e} ${K} audit localhost:3000 --tunnel ora ${t("# audit a local dev server")}`,` ${e} ${K} webmcp-audit http://localhost:3000`,` ${e} ${K} deep-journey stripe.com --intent pricing`,` ${e} ${K} journey "Find the API docs and how to authenticate" --domain stripe.com`,"",` ${t("audit options:")}`,` --min-score <n> ${t("Exit 1 when the score is below n (0-100); the CI gate")}`,` --max-age <s> ${t("Accept a cached result up to s seconds old (default 6h)")}`,` --force ${t("Bypass the cache and rescan (6/day budget)")}`,` --tunnel ora ${t("Expose a local target through ora's own tunnel (needs ORA_API_KEY: tunnels:write + tunnels:connect)")}`,` --tunnel-cmd <c> ${t("...or through your own tunnel command (e.g. 'ngrok http 3000 --log stdout')")}`,` --api-key <k> ${t("ora-issued scan API key that lifts the rate limits; also read from ORA_SCAN_API_KEY")}`,` --json ${t("Print the raw ora audit payload as JSON")}`,` --show-passing ${t("List each passing check (hidden by default)")}`,` --show-skipped ${t("List skipped checks (hidden by default)")}`,"",` ${t("audit exit codes:")}`,` ${t("0 success \xB7 1 below --min-score \xB7 2 usage error \xB7 3 API unreachable/rate-limited")}`,"",` ${t("webmcp-audit options:")}`,` --chrome-endpoint ${t("<e> Drive a Chrome you started: ws:// URL, http origin, or host:port")}`,` --min-score <n> ${t("Exit 1 when the score is below n (0-100); the CI gate")}`,` --api-key <k> ${t("ora API key that lifts the ingest rate limits; also read from ORA_API_KEY")}`,` --json ${t("Print the raw ora audit payload as JSON")}`,` --show-passing ${t("List each passing check (hidden by default)")}`,` ${t("starts a headless Chrome you already have installed; never downloads one")}`,` ${t("scored by ora, stored nowhere: the result is never published or ranked")}`,"",` ${t("deep-journey options:")}`,` --intent <id> ${t("Curated task id, e.g. pricing, signup, api-docs (server default when omitted)")}`,` --task <text> ${t("Free-text task (needs a partner API key; replaces --intent)")}`,` --api-key <k> ${t("ora partner API key: unlocks --task + 1000 runs/24h; also read from ORA_PARTNER_API_KEY")}`,` --agent <id> ${t("Agent to run (default: cas-haiku \u2014 Claude Code \xB7 Haiku 4.5)")}`,` --no-stream ${t("Poll for the result instead of streaming the trajectory")}`,` --json ${t("Print the terminal run detail as JSON")}`,` ${t("no key needed \xB7 public caps: 100 runs/24h per target, 200 runs/24h per IP")}`,"",` ${t("journey options:")}`,` --domain <d> ${t("Site the agent targets (e.g. stripe.com)")}`,` --harness <h> ${t("Agent harness: claude-code (default), codex, openclaw, hermess, claude-agent, eve, \u2026")}`,` --model <m> ${t("Model override (harness default when omitted)")}`,` --json ${t("Output as JSON")}`,` ${t("requires ORA_API_KEY (see .env.example)")}`,""].join(`
600
+ `)}var ga={meta:{name:K,version:he.version,description:"Score any site's agent readiness \u2014 and watch real AI agents navigate it"},subCommands:{audit:la,"webmcp-audit":ma,"deep-journey":da,journey:ua,skill:pa},setup(){let e=process.argv[2];(!e||e==="--help"||e==="-h")&&(console.log(ha()),process.exit(0))}};Pr();Wt(ga);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ax",
3
- "version": "0.7.5",
3
+ "version": "0.8.0",
4
4
  "description": "Score any site's agent readiness and watch real AI agents navigate it — powered by ora",
5
5
  "type": "module",
6
6
  "packageManager": "pnpm@10.34.5",
@@ -41,6 +41,7 @@
41
41
  "@biomejs/biome": "^2.5.7",
42
42
  "@commitlint/cli": "^21.2.2",
43
43
  "@commitlint/config-conventional": "^21.2.2",
44
+ "@ora-ai/tunnel-protocol": "^0.2.0",
44
45
  "@types/node": "^26.2.0",
45
46
  "@vitest/coverage-v8": "^3",
46
47
  "citty": "^0.2.2",