ax 0.9.1 → 0.10.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/README.md +16 -5
- package/dist/api/agent-files.d.ts +10 -2
- package/dist/contract/types.gen.d.ts +20 -8
- package/dist/contract/version.d.ts +1 -1
- package/dist/index.cjs +6 -4
- package/dist/index.js +6 -4
- package/dist/main.cjs +55 -55
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -31,7 +31,7 @@ Five commands:
|
|
|
31
31
|
- **`deep-journey <url>`** — run a real AI agent at a site on one of ora's curated tasks through the public journey API: no key, no workspace. A partner API key unlocks free-text tasks (`--task`) and a larger allowance.
|
|
32
32
|
- **`journey "<intent>"`** — send a real AI agent (claude-code, codex, …) at a site and watch its navigation live as a boxed node-graph, then get the scored insight, tokens, and cost. Partner-only: needs an `ORA_API_KEY` (see [For ora partners](#for-ora-partners)).
|
|
33
33
|
- **`skill [name]`** — list, print, or install ora's agent skills, digest-verified from the public registry.
|
|
34
|
-
- **`generate-files <domain>`** — draft the
|
|
34
|
+
- **`generate-files <domain>`** — draft the files agents look for on a site (`ard.json`, `ai-catalog.json`, `poppy.json`, `llms.txt`, a `robots.txt` edit, an API catalog, MCP server cards), filled in from ora's last scan of the domain.
|
|
35
35
|
|
|
36
36
|
## audit
|
|
37
37
|
|
|
@@ -263,14 +263,25 @@ Skills come from ora's public registry (`https://ora.ai/.well-known/agent-skills
|
|
|
263
263
|
## generate-files
|
|
264
264
|
|
|
265
265
|
```
|
|
266
|
-
ax generate-files example.com # writes
|
|
267
|
-
ax generate-files example.com --out public # writes public
|
|
266
|
+
ax generate-files example.com # writes into the current directory
|
|
267
|
+
ax generate-files example.com --out public # writes into public/ (your site's web root)
|
|
268
268
|
ax generate-files example.com --json # ora's payload, files + notes, nothing written
|
|
269
269
|
```
|
|
270
270
|
|
|
271
|
-
Drafts the files agents look for
|
|
271
|
+
Drafts the files agents look for on a site, filled in from ora's last scan of the domain (no new crawl), so run `ax audit` first for a domain ora has never scanned:
|
|
272
272
|
|
|
273
|
-
|
|
273
|
+
| File | Written to | What it is |
|
|
274
|
+
|---|---|---|
|
|
275
|
+
| `ard.json`, `ai-catalog.json` | `.well-known/` | An [Agentic Resource Discovery](https://agenticresourcediscovery.org/) catalog (the same document at the [AI Catalog Standard](https://ai-catalog.io/)'s path). Every entry is anchored to your domain, not to ora |
|
|
276
|
+
| `poppy.json` | `.well-known/` | A [Personal Agent Protocol](https://personalagentprotocol.org/docs/spec) file for signed-out browsing; the OAuth issuer and APIs ora saw are printed as notes, because naming them is only correct once they implement the protocol |
|
|
277
|
+
| `llms.txt` | web root | An index of the docs, APIs and agent endpoints ora found; skipped when you already publish one |
|
|
278
|
+
| `robots.txt` | web root | An edit of your current robots.txt: every line kept, a group added for AI search crawlers and user-requested agents your `User-agent: *` rules block (copying your other rules), and a `Sitemap:` line. Training crawlers and crawlers you block by name are never touched |
|
|
279
|
+
| `api-catalog` | `.well-known/` | An [RFC 9727](https://www.rfc-editor.org/rfc/rfc9727) API catalog pointing at your OpenAPI description |
|
|
280
|
+
| `server-card` | `<mcp path>/` | A draft MCP server card for each MCP server that has none. A card for a server on another host (`mcp.example.com`) is printed, not written |
|
|
281
|
+
|
|
282
|
+
A file ora cannot draft honestly (you already publish it, or ora never read the original) is left out and explained under "Not drafted". These are drafts: read each file and its notes before you publish.
|
|
283
|
+
|
|
284
|
+
Nothing is overwritten: if any target file exists - your `robots.txt` included - nothing is written and the command exits `2`. Pass `--force` to overwrite, or `--out <dir>` to write elsewhere and compare. Exit codes: `0` written, `2` usage (bad domain, files exist), `3` API. Same files as the web generator at [directory.ora.ai/generate](https://directory.ora.ai/generate) and `GET https://ora.ai/api/agent-files/{domain}?include=all`.
|
|
274
285
|
|
|
275
286
|
## Library use
|
|
276
287
|
|
|
@@ -1,15 +1,21 @@
|
|
|
1
1
|
export interface AgentFile {
|
|
2
|
-
/** Where the
|
|
2
|
+
/** Where the file is served, as a path on its host, e.g. "/.well-known/ard.json". */
|
|
3
3
|
path: string;
|
|
4
4
|
spec: {
|
|
5
5
|
name: string;
|
|
6
6
|
version: string;
|
|
7
7
|
url: string;
|
|
8
8
|
};
|
|
9
|
-
/** The JSON document to publish at `path
|
|
9
|
+
/** The JSON document to publish at `path`; `{}` for a text file (see `body`). */
|
|
10
10
|
content: Record<string, unknown>;
|
|
11
11
|
/** What to review or add before publishing. */
|
|
12
12
|
notes: string[];
|
|
13
|
+
/** Content-Type to serve the file with. */
|
|
14
|
+
mediaType?: string;
|
|
15
|
+
/** The exact bytes to publish. */
|
|
16
|
+
body?: string;
|
|
17
|
+
/** The full address the file is served at; a server card can live on a subdomain. */
|
|
18
|
+
url?: string;
|
|
13
19
|
}
|
|
14
20
|
export interface AgentFilesBundle {
|
|
15
21
|
domain: string;
|
|
@@ -17,6 +23,8 @@ export interface AgentFilesBundle {
|
|
|
17
23
|
/** When ora last scanned the domain; null when it never has. */
|
|
18
24
|
scannedAt: string | null;
|
|
19
25
|
files: AgentFile[];
|
|
26
|
+
/** Why an included file is absent, in plain sentences. */
|
|
27
|
+
notes?: string[];
|
|
20
28
|
}
|
|
21
29
|
/**
|
|
22
30
|
* Any failure to get the files from ora. `status` is the HTTP status when ora
|
|
@@ -131,7 +131,7 @@ export interface paths {
|
|
|
131
131
|
"/api/agent-files/{domain}": {
|
|
132
132
|
/**
|
|
133
133
|
* Draft a domain's own agent discovery files (ard.json, ai-catalog.json, poppy.json)
|
|
134
|
-
* @description Drafts the agent discovery files a domain publishes about itself: /.well-known/ard.json (Agentic Resource Discovery), /.well-known/ai-catalog.json (the same catalog at the AI Catalog Standard's path) and /.well-known/poppy.json (Personal Agent Protocol, Draft 0.1). Built from what ora already holds for the domain - no live crawl - so a domain ora never scanned still gets a valid minimal set (a catalog listing its website, a poppy.json for signed-out browsing) with scannedAt null. Every catalog entry is anchored to the domain itself (urn:air:<domain>:..., identity https://<domain>), never to ora, and carries only https URLs on the domain or its subdomains: anything the scan saw on another host is named in the file's notes instead. MCP servers are listed by their server card (the card the scan found, else the reserved <server-url>/server-card location, which the notes ask the owner to serve). The poppy.json is the minimal valid document; what ora saw that a fuller one could name (an OAuth issuer, MCP servers, an OpenAPI description) is listed in that file's notes. Review every file before publishing it. A leading www. is dropped, and any spelling other than the canonical domain answers 308 to /api/agent-files/<domain>. Sends Access-Control-Allow-Origin: * and is CDN-cached. Rate limited to 60 requests per minute per IP - returns 429 if exceeded. Also used by the generator page at directory.ora.ai/generate and by `npx ax generate-files <domain>`.
|
|
134
|
+
* @description Drafts the agent discovery files a domain publishes about itself: /.well-known/ard.json (Agentic Resource Discovery), /.well-known/ai-catalog.json (the same catalog at the AI Catalog Standard's path) and /.well-known/poppy.json (Personal Agent Protocol, Draft 0.1). Built from what ora already holds for the domain - no live crawl - so a domain ora never scanned still gets a valid minimal set (a catalog listing its website, a poppy.json for signed-out browsing) with scannedAt null. Every catalog entry is anchored to the domain itself (urn:air:<domain>:..., identity https://<domain>), never to ora, and carries only https URLs on the domain or its subdomains: anything the scan saw on another host is named in the file's notes instead. MCP servers are listed by their server card (the card the scan found, else the reserved <server-url>/server-card location, which the notes ask the owner to serve). The poppy.json is the minimal valid document; what ora saw that a fuller one could name (an OAuth issuer, MCP servers, an OpenAPI description) is listed in that file's notes. Pass ?include= for llms.txt, an edit of the site's robots.txt, an RFC 9727 api-catalog and draft MCP server cards. Review every file before publishing it. A leading www. is dropped, and any spelling other than the canonical domain answers 308 to /api/agent-files/<domain>. Sends Access-Control-Allow-Origin: * and is CDN-cached. Rate limited to 60 requests per minute per IP - returns 429 if exceeded. Also used by the generator page at directory.ora.ai/generate and by `npx ax generate-files <domain>`.
|
|
135
135
|
*/
|
|
136
136
|
get: operations["generateAgentFiles"];
|
|
137
137
|
};
|
|
@@ -431,7 +431,7 @@ export interface components {
|
|
|
431
431
|
* @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.
|
|
432
432
|
* @enum {string}
|
|
433
433
|
*/
|
|
434
|
-
contractVersion: "1.
|
|
434
|
+
contractVersion: "1.31.0";
|
|
435
435
|
/**
|
|
436
436
|
* @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.
|
|
437
437
|
* @enum {boolean}
|
|
@@ -634,7 +634,7 @@ export interface components {
|
|
|
634
634
|
* @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.
|
|
635
635
|
* @enum {string}
|
|
636
636
|
*/
|
|
637
|
-
contractVersion: "1.
|
|
637
|
+
contractVersion: "1.31.0";
|
|
638
638
|
/** @description Wall-clock duration of the scan that produced this stored result */
|
|
639
639
|
durationMs: number | null;
|
|
640
640
|
/**
|
|
@@ -682,7 +682,7 @@ export interface components {
|
|
|
682
682
|
* @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.
|
|
683
683
|
* @enum {string}
|
|
684
684
|
*/
|
|
685
|
-
contractVersion: "1.
|
|
685
|
+
contractVersion: "1.31.0";
|
|
686
686
|
/** @description The four scored layers in scoring order, with display name and current weight. */
|
|
687
687
|
layers: {
|
|
688
688
|
/** @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'. */
|
|
@@ -781,7 +781,7 @@ export interface components {
|
|
|
781
781
|
* @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.
|
|
782
782
|
* @enum {string}
|
|
783
783
|
*/
|
|
784
|
-
contractVersion: "1.
|
|
784
|
+
contractVersion: "1.31.0";
|
|
785
785
|
/** @description The apex domain derived from the requested URL. */
|
|
786
786
|
domain: string;
|
|
787
787
|
/** @description The normalized URL the run targeted. */
|
|
@@ -2188,9 +2188,11 @@ export interface components {
|
|
|
2188
2188
|
*/
|
|
2189
2189
|
scannedAt: string | null;
|
|
2190
2190
|
files: components["schemas"]["AgentFile"][];
|
|
2191
|
+
/** @description Why an included file is absent (the site already publishes it, Ora never read the original, nothing to list), in plain sentences. Empty without ?include=. */
|
|
2192
|
+
notes: string[];
|
|
2191
2193
|
};
|
|
2192
2194
|
AgentFile: {
|
|
2193
|
-
/** @description Where the
|
|
2195
|
+
/** @description Where the file is served, as a path on its host, e.g. /.well-known/ard.json. */
|
|
2194
2196
|
path: string;
|
|
2195
2197
|
/** @description The standard the file follows. */
|
|
2196
2198
|
spec: {
|
|
@@ -2198,12 +2200,18 @@ export interface components {
|
|
|
2198
2200
|
version: string;
|
|
2199
2201
|
url: string;
|
|
2200
2202
|
};
|
|
2201
|
-
/** @description The JSON document to publish at path. */
|
|
2203
|
+
/** @description The JSON document to publish at path; an empty object for a text file (llms.txt, robots.txt), whose bytes are in body. */
|
|
2202
2204
|
content: {
|
|
2203
2205
|
[key: string]: unknown;
|
|
2204
2206
|
};
|
|
2205
2207
|
/** @description What to review or add before publishing, in plain sentences. */
|
|
2206
2208
|
notes: string[];
|
|
2209
|
+
/** @description Content-Type to serve the file with, e.g. application/json, application/linkset+json, text/markdown, text/plain. */
|
|
2210
|
+
mediaType: string;
|
|
2211
|
+
/** @description The exact bytes to publish (JSON files pretty-printed with a trailing newline). */
|
|
2212
|
+
body: string;
|
|
2213
|
+
/** @description The full address the file is served at: https://<domain><path>, except an MCP server card, which lives on its server's host (possibly a subdomain). */
|
|
2214
|
+
url: string;
|
|
2207
2215
|
};
|
|
2208
2216
|
McpAuthRequiredResponse: {
|
|
2209
2217
|
/** @description Why the MCP server could not be inspected. */
|
|
@@ -3097,10 +3105,14 @@ export interface operations {
|
|
|
3097
3105
|
};
|
|
3098
3106
|
/**
|
|
3099
3107
|
* Draft a domain's own agent discovery files (ard.json, ai-catalog.json, poppy.json)
|
|
3100
|
-
* @description Drafts the agent discovery files a domain publishes about itself: /.well-known/ard.json (Agentic Resource Discovery), /.well-known/ai-catalog.json (the same catalog at the AI Catalog Standard's path) and /.well-known/poppy.json (Personal Agent Protocol, Draft 0.1). Built from what ora already holds for the domain - no live crawl - so a domain ora never scanned still gets a valid minimal set (a catalog listing its website, a poppy.json for signed-out browsing) with scannedAt null. Every catalog entry is anchored to the domain itself (urn:air:<domain>:..., identity https://<domain>), never to ora, and carries only https URLs on the domain or its subdomains: anything the scan saw on another host is named in the file's notes instead. MCP servers are listed by their server card (the card the scan found, else the reserved <server-url>/server-card location, which the notes ask the owner to serve). The poppy.json is the minimal valid document; what ora saw that a fuller one could name (an OAuth issuer, MCP servers, an OpenAPI description) is listed in that file's notes. Review every file before publishing it. A leading www. is dropped, and any spelling other than the canonical domain answers 308 to /api/agent-files/<domain>. Sends Access-Control-Allow-Origin: * and is CDN-cached. Rate limited to 60 requests per minute per IP - returns 429 if exceeded. Also used by the generator page at directory.ora.ai/generate and by `npx ax generate-files <domain>`.
|
|
3108
|
+
* @description Drafts the agent discovery files a domain publishes about itself: /.well-known/ard.json (Agentic Resource Discovery), /.well-known/ai-catalog.json (the same catalog at the AI Catalog Standard's path) and /.well-known/poppy.json (Personal Agent Protocol, Draft 0.1). Built from what ora already holds for the domain - no live crawl - so a domain ora never scanned still gets a valid minimal set (a catalog listing its website, a poppy.json for signed-out browsing) with scannedAt null. Every catalog entry is anchored to the domain itself (urn:air:<domain>:..., identity https://<domain>), never to ora, and carries only https URLs on the domain or its subdomains: anything the scan saw on another host is named in the file's notes instead. MCP servers are listed by their server card (the card the scan found, else the reserved <server-url>/server-card location, which the notes ask the owner to serve). The poppy.json is the minimal valid document; what ora saw that a fuller one could name (an OAuth issuer, MCP servers, an OpenAPI description) is listed in that file's notes. Pass ?include= for llms.txt, an edit of the site's robots.txt, an RFC 9727 api-catalog and draft MCP server cards. Review every file before publishing it. A leading www. is dropped, and any spelling other than the canonical domain answers 308 to /api/agent-files/<domain>. Sends Access-Control-Allow-Origin: * and is CDN-cached. Rate limited to 60 requests per minute per IP - returns 429 if exceeded. Also used by the generator page at directory.ora.ai/generate and by `npx ax generate-files <domain>`.
|
|
3101
3109
|
*/
|
|
3102
3110
|
generateAgentFiles: {
|
|
3103
3111
|
parameters: {
|
|
3112
|
+
query?: {
|
|
3113
|
+
/** @description Extra files to draft beyond the default three, comma-separated: llms.txt, robots.txt (an edit of the site's current robots.txt that keeps every line and only adds what lets AI search crawlers and user-requested agents in, plus a Sitemap line; training crawlers and crawlers the owner blocked by name are never touched), api-catalog (RFC 9727), mcp-server-card (a draft card for each of the domain's MCP servers that has none, served on the server's own host). `all` asks for every one. Unknown names are ignored. Opt-in, so a client built for the three files never receives a path it cannot place. A file Ora cannot draft honestly (the site already publishes it, or Ora never read it) is left out and explained in the bundle `notes`. */
|
|
3114
|
+
include?: string;
|
|
3115
|
+
};
|
|
3104
3116
|
path: {
|
|
3105
3117
|
/** @description A public host such as example.com (a full https:// URL without a path is also accepted). IPs, ports, paths and localhost are refused. */
|
|
3106
3118
|
domain: string;
|
|
@@ -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.
|
|
2
|
+
export declare const BUILT_AGAINST = "1.31.0";
|
package/dist/index.cjs
CHANGED
|
@@ -88,9 +88,11 @@ var AgentFilesApiError = class extends Error {
|
|
|
88
88
|
this.payload = options.payload;
|
|
89
89
|
}
|
|
90
90
|
};
|
|
91
|
-
var
|
|
91
|
+
var SAFE_SEGMENT = /^[a-z0-9._-]+$/;
|
|
92
92
|
function isSafeAgentFilePath(path) {
|
|
93
|
-
|
|
93
|
+
if (!path.startsWith("/")) return false;
|
|
94
|
+
const segments = path.slice(1).split("/");
|
|
95
|
+
return segments.length >= 1 && segments.length <= 6 && segments.every((seg) => SAFE_SEGMENT.test(seg) && seg !== "." && seg !== "..");
|
|
94
96
|
}
|
|
95
97
|
function trimTrailingSlashes(value) {
|
|
96
98
|
let end = value.length;
|
|
@@ -102,7 +104,7 @@ function normalizeDomainInput(input) {
|
|
|
102
104
|
}
|
|
103
105
|
async function fetchAgentFiles(domain, options = {}) {
|
|
104
106
|
const base = trimTrailingSlashes(options.baseUrl ?? process.env.ORA_API_URL ?? PUBLIC_BASE);
|
|
105
|
-
const url = `${base}/api/agent-files/${encodeURIComponent(normalizeDomainInput(domain))}`;
|
|
107
|
+
const url = `${base}/api/agent-files/${encodeURIComponent(normalizeDomainInput(domain))}?include=all`;
|
|
106
108
|
let res;
|
|
107
109
|
try {
|
|
108
110
|
res = await fetch(url, {
|
|
@@ -140,7 +142,7 @@ async function fetchAgentFiles(domain, options = {}) {
|
|
|
140
142
|
}
|
|
141
143
|
|
|
142
144
|
// src/contract/version.ts
|
|
143
|
-
var BUILT_AGAINST = "1.
|
|
145
|
+
var BUILT_AGAINST = "1.31.0";
|
|
144
146
|
|
|
145
147
|
// src/contract/index.ts
|
|
146
148
|
function minor(version) {
|
package/dist/index.js
CHANGED
|
@@ -50,9 +50,11 @@ var AgentFilesApiError = class extends Error {
|
|
|
50
50
|
this.payload = options.payload;
|
|
51
51
|
}
|
|
52
52
|
};
|
|
53
|
-
var
|
|
53
|
+
var SAFE_SEGMENT = /^[a-z0-9._-]+$/;
|
|
54
54
|
function isSafeAgentFilePath(path) {
|
|
55
|
-
|
|
55
|
+
if (!path.startsWith("/")) return false;
|
|
56
|
+
const segments = path.slice(1).split("/");
|
|
57
|
+
return segments.length >= 1 && segments.length <= 6 && segments.every((seg) => SAFE_SEGMENT.test(seg) && seg !== "." && seg !== "..");
|
|
56
58
|
}
|
|
57
59
|
function trimTrailingSlashes(value) {
|
|
58
60
|
let end = value.length;
|
|
@@ -64,7 +66,7 @@ function normalizeDomainInput(input) {
|
|
|
64
66
|
}
|
|
65
67
|
async function fetchAgentFiles(domain, options = {}) {
|
|
66
68
|
const base = trimTrailingSlashes(options.baseUrl ?? process.env.ORA_API_URL ?? PUBLIC_BASE);
|
|
67
|
-
const url = `${base}/api/agent-files/${encodeURIComponent(normalizeDomainInput(domain))}`;
|
|
69
|
+
const url = `${base}/api/agent-files/${encodeURIComponent(normalizeDomainInput(domain))}?include=all`;
|
|
68
70
|
let res;
|
|
69
71
|
try {
|
|
70
72
|
res = await fetch(url, {
|
|
@@ -102,7 +104,7 @@ async function fetchAgentFiles(domain, options = {}) {
|
|
|
102
104
|
}
|
|
103
105
|
|
|
104
106
|
// src/contract/version.ts
|
|
105
|
-
var BUILT_AGAINST = "1.
|
|
107
|
+
var BUILT_AGAINST = "1.31.0";
|
|
106
108
|
|
|
107
109
|
// src/contract/index.ts
|
|
108
110
|
function minor(version) {
|
package/dist/main.cjs
CHANGED
|
@@ -1,60 +1,60 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var Kr=Object.create;var Ft=Object.defineProperty;var qr=Object.getOwnPropertyDescriptor;var Yr=Object.getOwnPropertyNames;var Vr=Object.getPrototypeOf,Xr=Object.prototype.hasOwnProperty;var zr=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Qr=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Yr(t))!Xr.call(e,o)&&o!==n&&Ft(e,o,{get:()=>t[o],enumerable:!(r=qr(t,o))||r.enumerable});return e};var
|
|
3
|
-
`)}function I(e){return typeof e=="function"?e():e}var
|
|
4
|
-
`)}catch(n){console.error(n)}}var po=/^no[-A-Z]/;async function mo(e,t){let n=await I(e.meta||{}),r=Kt(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 g of r)if(g.type==="positional"){let f=g.name.toUpperCase(),
|
|
5
|
-
`)}function Ze(e){let t=e.valueHint?`=<${e.valueHint}>`:"",n=t||`=<${Bt(e.name)}>`;return!e.type||e.type==="positional"||e.type==="boolean"?t:e.type==="enum"&&e.options?.length?`=<${e.options.join("|")}>`:n}function Jt(e,t){let n=t?Pe("(Required)"):"",r=e.default===void 0?"":Pe(`(Default: ${e.default})`);return[e.description,n,r].filter(Boolean).join(" ")}async function Yt(e,t={}){let n=t.rawArgs||process.argv.slice(2),r=t.showUsage||uo;try{let o=await ho(e);if(o.help.length>0&&n.some(s=>o.help.includes(s)))await r(...await tt(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
|
|
6
|
-
`),process.exit(1)}}async function ho(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 ye(s.alias))r.add(i)}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 ze=
|
|
7
|
-
`))}function z(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 ve(e){let t=null;try{t=await e.clone().json()}catch{}return e.body?.cancel().catch(()=>{}),{message:t?.message||t?.error||`HTTP ${e.status}`,code:t?.code??null,payload:t}}async function ce(e){return(await ve(e)).message}var Q=e=>new Promise(t=>setTimeout(t,e));var vo="https://ora.ai",So=6e4,xo=2e3,Ao=45,st=14,j=class extends Error{code;payload;constructor(t,n={}){super(t),this.name="AuditApiError",this.code=n.code??null,this.payload=n.payload}},ko="MCP_AUTH_REQUIRED";function Zt(e){return e instanceof j&&e.code===ko}function en(e){return e?{authorization:`Bearer ${e}`}:{}}async function tn(e,t={}){let n=(t.baseUrl??process.env.ORA_API_URL??vo).replace(/\/+$/,"");t={...t,apiKey:t.apiKey||process.env.ORA_SCAN_API_KEY||void 0},t.progress?.(`Auditing ${e} with ora`);let r=await Eo(n,e,t);be(r.result.contractVersion);let o=r.result;return nn(o)&&(o=await To(n,o,t)),{result:o,verdict:r.verdict}}function $o(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 Eo(e,t,n){let r=n.idleMs??So,o=z(r),s=()=>new j(`ora audit timed out \u2014 no progress for ${Math.round(r/1e3)}s`),i;try{i=await fetch($o(e,t,n),{headers:{accept:"text/event-stream",...en(n.apiKey)},signal:o.signal})}catch(
|
|
2
|
+
"use strict";var Kr=Object.create;var Ft=Object.defineProperty;var qr=Object.getOwnPropertyDescriptor;var Yr=Object.getOwnPropertyNames;var Vr=Object.getPrototypeOf,Xr=Object.prototype.hasOwnProperty;var zr=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Qr=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Yr(t))!Xr.call(e,o)&&o!==n&&Ft(e,o,{get:()=>t[o],enumerable:!(r=qr(t,o))||r.enumerable});return e};var J=(e,t,n)=>(n=e!=null?Kr(Vr(e)):{},Qr(t||!e||!e.__esModule?Ft(n,"default",{value:e,enumerable:!0}):n,e));var F=zr((nc,rt)=>{"use strict";var Me=process||{},Vt=Me.argv||[],Ie=Me.env||{},go=!(Ie.NO_COLOR||Vt.includes("--no-color"))&&(!!Ie.FORCE_COLOR||Vt.includes("--color")||Me.platform==="win32"||(Me.stdout||{}).isTTY&&Ie.TERM!=="dumb"||!!Ie.CI),fo=(e,t,n=e)=>r=>{let o=""+r,s=o.indexOf(t,e.length);return~s?e+yo(o,t,n,s)+t:e+o+t},yo=(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)},Xt=(e=go)=>{let t=e?fo:()=>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")}};rt.exports=Xt();rt.exports.createColors=Xt});var Zr=/\d/,eo=["-","_","/","."];function to(e=""){if(!Zr.test(e))return e!==e.toLowerCase()}function Wt(e,t){let n=t??eo,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=to(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 no(e){return e?e[0].toUpperCase()+e.slice(1):""}function ro(e){return e?e[0].toLowerCase()+e.slice(1):""}function oo(e,t){return e?(Array.isArray(e)?e:Wt(e)).map(n=>no(t?.normalize?n.toLowerCase():n)).join(""):""}function fe(e,t){return ro(oo(e||"",t))}function _e(e,t){return e?(Array.isArray(e)?e:Wt(e)).map(n=>n.toLowerCase()).join(t??"-"):""}function Bt(e){return _e(e||"","_")}var Gt=require("util");function ye(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 X=class extends Error{code;constructor(e,t){super(e),this.name="CLIError",this.code=t}};function so(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 C of A)i.set(p,C),a.has(C)||a.set(C,[]),a.get(C).push(p),i.set(C,p),a.has(p)||a.set(p,[]),a.get(p).push(C)}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 m=[],g={};for(let p=0;p<e.length;p++){let y=e[p];if(y==="--"){m.push(...e.slice(p));break}if(y.startsWith("--no-")){let A=y.slice(5);g[A]=!0;continue}m.push(y)}let f;try{f=(0,Gt.parseArgs)({args:m,options:Object.keys(c).length>0?c:void 0,allowPositionals:!0,strict:!1})}catch{f={values:{},positionals:m}}let h={_:[]};h._=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=""),h[p]=A}for(let[p]of Object.entries(g)){h[p]=!1;let y=i.get(p);y&&(h[y]=!1);let A=a.get(p);if(A)for(let C of A)h[C]=!1}for(let[p,y]of i.entries())h[p]!==void 0&&h[y]===void 0&&(h[y]=h[p]),h[y]!==void 0&&h[p]===void 0&&(h[p]=h[y]),h[p]!==h[y]&&s[y]===h[y]&&(h[y]=h[p]);return h}var io=(()=>{let e=globalThis.process?.env??{};return e.NO_COLOR==="1"||e.TERM==="dumb"||e.TEST||e.CI})(),Oe=(e,t=39)=>n=>io?n:`\x1B[${e}m${n}\x1B[${t}m`,Te=Oe(1,22),H=Oe(36),Pe=Oe(90),Ce=Oe(4,24);function ao(e,t){let n={boolean:[],string:[],alias:{},default:{}},r=Kt(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=fe(a.name),l=_e(a.name);if(c!==a.name||l!==a.name){let u=ye(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=so(e,n),[...s]=o._,i=new Proxy(o,{get(a,c){return a[c]??a[fe(c)]??a[_e(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 X(`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 X(`Invalid value for argument: ${H(`--${a.name}`)} (${H(c)}). Expected one of: ${l.map(u=>H(u)).join(", ")}.`,"EARG")}else if(a.required&&i[a.name]===void 0)throw new X(`Missing required argument: --${a.name}`,"EARG");return i}function Kt(e){let t=[];for(let[n,r]of Object.entries(e||{}))t.push({...r,name:n,alias:ye(r.alias)});return t}async function co(e){return Promise.all(e.map(t=>I(t)))}async function et(e,t){let n=await I(e.args||{}),r=ao(t.rawArgs,n),o={rawArgs:t.rawArgs,args:r,data:t.data,cmd:e},s=await co(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=qt(t.rawArgs,n),d=t.rawArgs[u];if(d){let m=await nt(l,d);if(!m)throw new X(`Unknown command ${H(d)}`,"E_UNKNOWN_COMMAND");await et(m,{rawArgs:t.rawArgs.slice(u+1)})}else{let m=await I(e.default);if(m){if(e.run)throw new X("Cannot specify both 'run' and 'default' on the same command.","E_DEFAULT_CONFLICT");let g=await nt(l,m);if(!g)throw new X(`Default sub command ${H(m)} not found in subCommands.`,"E_UNKNOWN_COMMAND");await et(g,{rawArgs:t.rawArgs})}else if(!e.run)throw new X("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 tt(e,t,n){let r=await I(e.subCommands);if(r&&Object.keys(r).length>0){let o=qt(t,await I(e.args||{})),s=t[o],i=await nt(r,s);if(i)return tt(i,t.slice(o+1),e)}return[e,n]}async function nt(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&&ye(o.alias).includes(t))return r}}function qt(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(r==="--")return-1;if(r.startsWith("-")){!r.includes("=")&&lo(r,t)&&n++;continue}return n}return-1}function lo(e,t){let n=e.replace(/^-{1,2}/,""),r=fe(n);for(let[o,s]of Object.entries(t))if(!(s.type!=="string"&&s.type!=="enum")&&(r===fe(o)||(Array.isArray(s.alias)?s.alias:s.alias?[s.alias]:[]).includes(n)))return!0;return!1}async function uo(e,t){try{console.log(await mo(e,t)+`
|
|
4
|
+
`)}catch(n){console.error(n)}}var po=/^no[-A-Z]/;async function mo(e,t){let n=await I(e.meta||{}),r=Kt(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 g of r)if(g.type==="positional"){let f=g.name.toUpperCase(),h=g.required!==!1&&g.default===void 0;a.push([H(f+Ze(g)),Jt(g,h)]),l.push(h?`<${f}>`:`[${f}]`)}else{let f=g.required===!0&&g.default===void 0,h=[...(g.alias||[]).map(p=>`-${p}`),`--${g.name}`].join(", ")+Ze(g);if(i.push([H(h),Jt(g,f)]),g.type==="boolean"&&(g.default===!0||g.negativeDescription)&&!po.test(g.name)){let p=[...(g.alias||[]).map(y=>`--no-${y}`),`--no-${g.name}`].join(", ");i.push([H(p),[g.negativeDescription,f?Pe("(Required)"):""].filter(Boolean).join(" ")])}f&&l.push(`--${g.name}`+Ze(g))}if(e.subCommands){let g=[],f=await I(e.subCommands);for(let[h,p]of Object.entries(f)){let y=await I((await I(p))?.meta);if(y?.hidden)continue;let A=ye(y?.alias),C=[h,...A].join(", ");c.push([H(C),y?.description||""]),g.push(h,...A)}l.push(g.join("|"))}let u=[],d=n.version||o.version;u.push(Pe(`${n.description} (${s+(d?` v${d}`:"")})`),"");let m=i.length>0||a.length>0;return u.push(`${Ce(Te("USAGE"))} ${H(`${s}${m?" [OPTIONS]":""} ${l.join(" ")}`)}`,""),a.length>0&&(u.push(Ce(Te("ARGUMENTS")),""),u.push(Qe(a," ")),u.push("")),i.length>0&&(u.push(Ce(Te("OPTIONS")),""),u.push(Qe(i," ")),u.push("")),c.length>0&&(u.push(Ce(Te("COMMANDS")),""),u.push(Qe(c," ")),u.push("",`Use ${H(`${s} <command> --help`)} for more information about a command.`)),u.filter(g=>typeof g=="string").join(`
|
|
5
|
+
`)}function Ze(e){let t=e.valueHint?`=<${e.valueHint}>`:"",n=t||`=<${Bt(e.name)}>`;return!e.type||e.type==="positional"||e.type==="boolean"?t:e.type==="enum"&&e.options?.length?`=<${e.options.join("|")}>`:n}function Jt(e,t){let n=t?Pe("(Required)"):"",r=e.default===void 0?"":Pe(`(Default: ${e.default})`);return[e.description,n,r].filter(Boolean).join(" ")}async function Yt(e,t={}){let n=t.rawArgs||process.argv.slice(2),r=t.showUsage||uo;try{let o=await ho(e);if(o.help.length>0&&n.some(s=>o.help.includes(s)))await r(...await tt(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 X("No version specified","E_NO_VERSION");console.log(s.version)}else await et(e,{rawArgs:n})}catch(o){o instanceof X?(await r(...await tt(e,n)),console.error(o.message)):console.error(o,`
|
|
6
|
+
`),process.exit(1)}}async function ho(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 ye(s.alias))r.add(i)}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 ze=J(F(),1);var we={name:"ax",version:"0.10.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.4.1","@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 wt=J(F(),1);var ot="1.31.0";function zt(e){let[t=0,n=0]=e.split(".").map(r=>Number.parseInt(r,10));return[t,n]}function bo(e){if(!e||!/^\d+\.\d+\.\d+$/.test(e))return!1;let[t,n]=zt(e),[r,o]=zt(ot);return t>r||t===r&&n>o}var Qt=!1;function be(e){Qt||!bo(e)||(Qt=!0,process.stderr.write(`ora reports contract ${e}; this CLI was built against ${ot}. Newer fields may be missing from the output - upgrade with: npm i -g ax@latest
|
|
7
|
+
`))}function z(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 ve(e){let t=null;try{t=await e.clone().json()}catch{}return e.body?.cancel().catch(()=>{}),{message:t?.message||t?.error||`HTTP ${e.status}`,code:t?.code??null,payload:t}}async function ce(e){return(await ve(e)).message}var Q=e=>new Promise(t=>setTimeout(t,e));var vo="https://ora.ai",So=6e4,xo=2e3,Ao=45,st=14,j=class extends Error{code;payload;constructor(t,n={}){super(t),this.name="AuditApiError",this.code=n.code??null,this.payload=n.payload}},ko="MCP_AUTH_REQUIRED";function Zt(e){return e instanceof j&&e.code===ko}function en(e){return e?{authorization:`Bearer ${e}`}:{}}async function tn(e,t={}){let n=(t.baseUrl??process.env.ORA_API_URL??vo).replace(/\/+$/,"");t={...t,apiKey:t.apiKey||process.env.ORA_SCAN_API_KEY||void 0},t.progress?.(`Auditing ${e} with ora`);let r=await Eo(n,e,t);be(r.result.contractVersion);let o=r.result;return nn(o)&&(o=await To(n,o,t)),{result:o,verdict:r.verdict}}function $o(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 Eo(e,t,n){let r=n.idleMs??So,o=z(r),s=()=>new j(`ora audit timed out \u2014 no progress for ${Math.round(r/1e3)}s`),i;try{i=await fetch($o(e,t,n),{headers:{accept:"text/event-stream",...en(n.apiKey)},signal:o.signal})}catch(m){if(o.disarm(),o.tripped())throw s();let g=m instanceof Error?m.message:String(m);throw new j(`ora audit request failed: ${g}`)}if(i.status===429){o.disarm();let m=i.headers.get("retry-after");throw new j(`ora rate limit exceeded${m?` \u2014 retry after ${m}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){o.disarm();let m=await ve(i);throw new j(`ora audit failed: ${m.message}`,{code:m.code,payload:m.payload})}let a=_o(),c=new TextDecoder,l="",u,d;try{e:for await(let m of i.body){o.poke(),l=`${l}${c.decode(m,{stream:!0})}`.replace(/\r\n?/g,`
|
|
8
8
|
`);let g=l.indexOf(`
|
|
9
9
|
|
|
10
10
|
`);for(;g!==-1;){let f=Ro(l.slice(0,g));if(l=l.slice(g+2),g=l.indexOf(`
|
|
11
11
|
|
|
12
|
-
`),!f)continue;let
|
|
12
|
+
`),!f)continue;let h;try{h=JSON.parse(f)}catch{continue}let p=a(h);if(p&&n.progress?.(p),h.type==="error")throw new j(`ora audit failed: ${typeof h.message=="string"?h.message:"scan error"}`,{code:typeof h.code=="string"?h.code:null,payload:h});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(m){if(o.tripped())throw s();if(m instanceof j)throw m;let g=m instanceof Error?m.message:String(m);throw new j(`ora audit stream error: ${g}`)}finally{o.disarm(),i.body.cancel().catch(()=>{})}if(!u)throw new j("ora audit stream ended before completing");return{result:u,verdict:d}}function Ro(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 _o(){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(st,Math.max(0,Math.round(o/e*st)));return`${`${"\u2588".repeat(s)}${"\u2591".repeat(st-s)}`} ${o}/${e}${n?` \xB7 ${n}`:""}`}case"scan_complete":return"Finishing up\u2026";default:return}}}function nn(e){return e.analysisStatus==="complete"||e.analysisStatus==="stuck"?!1:e.analysisStatus==="partial"?!0:(e.pendingChecks?.length??0)>0}async function To(e,t,n){let r=`${e}/api/score/${encodeURIComponent(t.domain)}?format=audit`,o=n.pollEveryMs??xo,s=n.pollLimit??Ao,i=t;for(let a=0;a<s&&nn(i);a++){let c=i.pendingChecks?.length??0;n.progress?.(c?`Analyzing\u2026 ${c} check${c===1?"":"s"} pending`:"Analyzing\u2026"),await Q(o);try{let l=await fetch(r,{headers:{accept:"application/json",...en(n.apiKey)},signal:AbortSignal.timeout(15e3)});l.ok&&(i=await l.json())}catch{}}return i}function Co(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 Po(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 rn(e,t){let{result:n}=e,r=(n.layers??[]).map(i=>Co(i.name,(i.checks??[]).map(Po))),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=
|
|
15
|
-
`))}function Ho(e,t){return new Promise((n,r)=>{let o=process.platform!=="win32",s=(0,cn.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 _(`tunnel command did not print a public https URL within ${Math.round(t/1e3)}s: ${e}`)),t);s.on("error",d=>l(new _(d.message))),s.on("exit",d=>{let
|
|
16
|
-
output: ${a.trim().slice(-300)}`:"";l(new _(`tunnel command exited before printing a public https URL (code ${d??"unknown"}): ${e}${
|
|
14
|
+
`)}function _o(){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(st,Math.max(0,Math.round(o/e*st)));return`${`${"\u2588".repeat(s)}${"\u2591".repeat(st-s)}`} ${o}/${e}${n?` \xB7 ${n}`:""}`}case"scan_complete":return"Finishing up\u2026";default:return}}}function nn(e){return e.analysisStatus==="complete"||e.analysisStatus==="stuck"?!1:e.analysisStatus==="partial"?!0:(e.pendingChecks?.length??0)>0}async function To(e,t,n){let r=`${e}/api/score/${encodeURIComponent(t.domain)}?format=audit`,o=n.pollEveryMs??xo,s=n.pollLimit??Ao,i=t;for(let a=0;a<s&&nn(i);a++){let c=i.pendingChecks?.length??0;n.progress?.(c?`Analyzing\u2026 ${c} check${c===1?"":"s"} pending`:"Analyzing\u2026"),await Q(o);try{let l=await fetch(r,{headers:{accept:"application/json",...en(n.apiKey)},signal:AbortSignal.timeout(15e3)});l.ok&&(i=await l.json())}catch{}}return i}function Co(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 Po(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 rn(e,t){let{result:n}=e,r=(n.layers??[]).map(i=>Co(i.name,(i.checks??[]).map(Po))),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=J(F(),1),at="\u26A0 MCP handshake requires credentials \u2014 target is unscored",Oo=" (0/F means could not evaluate, not failed everything)",Io=80,Mo=120,Le=10;function Lo(){return Math.min(Mo,Math.max(Io,process.stdout.columns??100))}function ct(e,t){return e.length<t?e+" ".repeat(t-e.length):e}function sn(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 it(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,m)=>sn(typeof d=="string"?d:d[0],e[m].width)),l=Math.max(1,...c.map(d=>d.length)),u=[];for(let d=0;d<l;d++){let m=c.map((g,f)=>{let h=ct(g[d]??"",e[f].width),p=a??(typeof i[f]=="string"?e[f].paint:i[f][1]);return` ${p?p(h):h} `});u.push(r+m.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 No(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 on(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 jo(e,t){if(t<=0)return v.default.dim("\u2500".repeat(Le));let n=Math.min(Le,Math.max(0,Math.round(e/t*Le)));return v.default.green("\u2588".repeat(n))+v.default.dim("\u2591".repeat(Le-n))}function Uo(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(ct(e.name,n))} ${jo(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=it(No(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=it(on(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=it(on(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 Do(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(ct(r.id,n))} ${s}${i}`)}),t}function Fo(e){return e<90?`${e}s`:e<5400?`${Math.round(e/60)} min`:`${Math.round(e/3600)}h`}function an(e,t={}){let n=Lo(),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(` ${at}${Oo}`)),e.summary)for(let l of sn(e.summary,n-4))o.push(` ${v.default.dim(l)}`);for(let l of e.sections)o.push(...Uo(l,n,r,t));o.push(...Do(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 (${Fo(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 cn=require("child_process"),_=class extends Error{},Wo=3e4,ln=9e4,Bo=1e4;function lt(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 Jo(e){for(let t of e.matchAll(/https:\/\/[^\s"'|]+/g))try{let n=new URL(t[0]);if(n.pathname==="/"&&!n.search&&!lt(n.hostname))return n.origin}catch{}}async function un(e,t=Wo){let n=await Ho(e,t);try{await ut(n.url,ln)}catch(r){throw n.close(),r}return n}async function ut(e,t=ln,n=5e3,r){let o=Date.now()+t;for(;Date.now()<o;){if(r?.aborted)throw new _("interrupted while waiting for the tunnel");try{if((await fetch(e,{redirect:"manual",signal:AbortSignal.timeout(Bo)})).status<500)return}catch{}await new Promise(s=>setTimeout(s,n))}throw new _([`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 Ho(e,t){return new Promise((n,r)=>{let o=process.platform!=="win32",s=(0,cn.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 _(`tunnel command did not print a public https URL within ${Math.round(t/1e3)}s: ${e}`)),t);s.on("error",d=>l(new _(d.message))),s.on("exit",d=>{let m=a.trim()?`
|
|
16
|
+
output: ${a.trim().slice(-300)}`:"";l(new _(`tunnel command exited before printing a public https URL (code ${d??"unknown"}): ${e}${m}`))});for(let d of[s.stdout,s.stderr])d?.setEncoding("utf8"),d?.on("data",m=>{a=(a+m).slice(-2e3);let g=Jo(a);g&&!i&&(i=!0,clearTimeout(u),s.removeAllListeners("exit"),n({url:g,close:c}))})})}var Cn=require("crypto"),Pn=require("events"),On=require("http");var dn="https://api.agentfront.sh";function pn(e){return(e??process.env.ORA_PLATFORM_URL??dn).replace(/\/+$/,"")}var Go=12e4;async function Ne(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 Ko(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 dt(e){let t="message",n=[];for(let r of e.split(`
|
|
17
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(`
|
|
18
18
|
`)}:null}async function qo(e,t,n,r,o){let s=n.startsWith("http")?n:`${e}${n}`,i=z(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
|
|
19
|
+
`);let m=u.indexOf(`
|
|
20
20
|
|
|
21
|
-
`);for(;
|
|
21
|
+
`);for(;m!==-1;){let g=dt(u.slice(0,m));if(u=u.slice(m+2),m=u.indexOf(`
|
|
22
22
|
|
|
23
|
-
`),!g)continue;let f;try{f=JSON.parse(g.data)}catch{continue}if(Yo(l,g.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 Yo(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 Vo(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 Q(1200)}}async function pt(e,t={}){let n=(e.baseUrl??process.env.ORA_PLATFORM_URL??dn).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 Ne(n,r),s=await Ko(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 qo(n,o,s.streamUrl??`/experiment/v1/runs/${s.runId}/stream`,t,e.idleMs??Go),c=a.summary?await Vo(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"};function mn(e,t){return e.safeParse(t)}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 le(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 hn(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 ue(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 gn(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:le(n.port,`${t}.port`,1,65535)}}var gc=ue(e=>gn(e,"target")),fc=ue(e=>{let t=te(e,"hello");return{agentVersion:ee(t.agentVersion,"hello.agentVersion",1,64),target:gn(t.target,"hello.target"),maxStreams:t.maxStreams===void 0?32:le(t.maxStreams,"hello.maxStreams",1,256)}}),fn=ue(e=>{let t=te(e,"helloAck");return{tunnelId:ee(t.tunnelId,"helloAck.tunnelId",1),heartbeatMs:le(t.heartbeatMs,"helloAck.heartbeatMs",1),maxStreams:le(t.maxStreams,"helloAck.maxStreams",1),maxFrame:le(t.maxFrame,"helloAck.maxFrame",1)}}),yn=ue(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 "/"');let r={method:ee(t.method,"open.method",1,16),path:n,headers:hn(t.headers,"open.headers")};if(t.hasBody!==void 0){if(typeof t.hasBody!="boolean")throw new U("open.hasBody: expected boolean");r.hasBody=t.hasBody}return r}),wn=ue(e=>{let t=te(e,"responseHeaders");return{status:le(t.status,"responseHeaders.status",100,599),headers:hn(t.headers,"responseHeaders.headers")}});function bn(e){return ue(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 vn=bn("reset"),Sn=bn("goaway");var ne=9,Se=64*1024,re=0,de=(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))(de||{}),Xo=new Set(Object.values(de).filter(e=>typeof e=="number"));function xn(e,t=Se){if(e.payload.byteLength>t)throw new k(S.frameTooLarge,`frame payload ${e.payload.byteLength} exceeds max ${t}`);let n=new Uint8Array(ne+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,ne),n}function An(e,t=Se){if(e.byteLength<ne)throw new k(S.frameTooShort,`frame is ${e.byteLength} bytes, header alone is ${ne}`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=n.getUint8(0);if(!Xo.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!==ne+s)throw new k(S.frameLengthMismatch,`declared payload ${s} but message carries ${e.byteLength-ne}`);return{type:r,streamId:o,payload:e.subarray(ne)}}var $n="ora-tunnel.v1",kn=Se,zo=new TextEncoder,Qo=new TextDecoder,xe=class{constructor(t=Se){this.maxFrame=t}maxFrame;subprotocol=$n;encode(t){return xn(t,this.capFor(t.type))}decode(t){let n=An(t,Math.max(this.maxFrame,kn)),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:zo.encode(JSON.stringify(r))})}decodeJson(t,n){let r;try{r=JSON.parse(Qo.decode(t.payload))}catch{throw new k(S.badJson,"frame payload is not valid JSON")}let o=mn(n,r);if(!o.success)throw new k(S.badPayload,o.error.message);return o.data}capFor(t){return t===18?this.maxFrame:kn}};var En=1e4;function Rn(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!==re||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 je=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={};cancellation=new AbortController;get signal(){return this.cancellation.signal}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;try{this.writer.writeFrame(this.codec.encodeJson(20,this.id,r))}finally{this.notifyReset(r)}}receive(t){if(!this.resetPayload)switch(t.type){case 17:this.handlers.onHeaders?.(this.codec.decodeJson(t,wn));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,vn);this.resetPayload=n,this.notifyReset(n);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.notifyReset(t))}notifyReset(t){this.cancellation.abort(new k(S.streamReset,`${t.code}: ${t.message}`)),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 Ue=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,re,{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===re){t.type===32&&(this.goingAway=!0,this.opts.onGoaway?.(this.opts.codec.decodeJson(t,Sn)));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,yn);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 je(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 De=class{constructor(t){this.onCancel=t}onCancel;buffered=[];pending=null;ended=!1;error=null;cancelled=!1;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.buffered.length=0,this.pending)){let n=this.pending;this.pending=null,n.reject(t)}}[Symbol.asyncIterator](){let t=!1,n=()=>{t||this.cancelled||(this.cancelled=!0,this.ended=!0,this.error=null,this.buffered.length=0,this.pending?.resolve({value:void 0,done:!0}),this.pending=null,this.onCancel?.())};return{next:()=>this.buffered.length>0?Promise.resolve({value:this.buffered.shift(),done:!1}):this.error?Promise.reject(this.error):this.ended?(t=!0,Promise.resolve({value:void 0,done:!0})):new Promise((r,o)=>{this.pending={resolve:s=>{s.done&&(t=!0),r(s)},reject:o}}),return:async()=>(n(),{value:void 0,done:!0}),throw:async r=>{throw n(),r}}}};function _n(e){let t=new De;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 Tn(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 Ae=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=Rn(t,n,2,fn,this.opts.handshakeTimeoutMs??En);t.send(n.encodeJson(1,re,r));let s=await o;return this.mux=new Ue(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:_n(t),hasBody:n.hasBody,signal:t.signal});t.sendHeaders({status:r.status,headers:r.headers}),await Tn(t,r.body)}catch(r){try{t.sendReset(S.forwardError,r instanceof Error?r.message:String(r))}catch{}}}};var ht="tunnels:write + tunnels:connect",gt=[`--tunnel ora needs ORA_API_KEY: an ora platform key (ora_sk_...) with the ${ht} 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(`
|
|
23
|
+
`),!g)continue;let f;try{f=JSON.parse(g.data)}catch{continue}if(Yo(l,g.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 Yo(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 Vo(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 Q(1200)}}async function pt(e,t={}){let n=(e.baseUrl??process.env.ORA_PLATFORM_URL??dn).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 Ne(n,r),s=await Ko(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 qo(n,o,s.streamUrl??`/experiment/v1/runs/${s.runId}/stream`,t,e.idleMs??Go),c=a.summary?await Vo(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"};function mn(e,t){return e.safeParse(t)}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 le(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 hn(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 ue(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 gn(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:le(n.port,`${t}.port`,1,65535)}}var yc=ue(e=>gn(e,"target")),wc=ue(e=>{let t=te(e,"hello");return{agentVersion:ee(t.agentVersion,"hello.agentVersion",1,64),target:gn(t.target,"hello.target"),maxStreams:t.maxStreams===void 0?32:le(t.maxStreams,"hello.maxStreams",1,256)}}),fn=ue(e=>{let t=te(e,"helloAck");return{tunnelId:ee(t.tunnelId,"helloAck.tunnelId",1),heartbeatMs:le(t.heartbeatMs,"helloAck.heartbeatMs",1),maxStreams:le(t.maxStreams,"helloAck.maxStreams",1),maxFrame:le(t.maxFrame,"helloAck.maxFrame",1)}}),yn=ue(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 "/"');let r={method:ee(t.method,"open.method",1,16),path:n,headers:hn(t.headers,"open.headers")};if(t.hasBody!==void 0){if(typeof t.hasBody!="boolean")throw new U("open.hasBody: expected boolean");r.hasBody=t.hasBody}return r}),wn=ue(e=>{let t=te(e,"responseHeaders");return{status:le(t.status,"responseHeaders.status",100,599),headers:hn(t.headers,"responseHeaders.headers")}});function bn(e){return ue(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 vn=bn("reset"),Sn=bn("goaway");var ne=9,Se=64*1024,re=0,de=(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))(de||{}),Xo=new Set(Object.values(de).filter(e=>typeof e=="number"));function xn(e,t=Se){if(e.payload.byteLength>t)throw new k(S.frameTooLarge,`frame payload ${e.payload.byteLength} exceeds max ${t}`);let n=new Uint8Array(ne+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,ne),n}function An(e,t=Se){if(e.byteLength<ne)throw new k(S.frameTooShort,`frame is ${e.byteLength} bytes, header alone is ${ne}`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=n.getUint8(0);if(!Xo.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!==ne+s)throw new k(S.frameLengthMismatch,`declared payload ${s} but message carries ${e.byteLength-ne}`);return{type:r,streamId:o,payload:e.subarray(ne)}}var $n="ora-tunnel.v1",kn=Se,zo=new TextEncoder,Qo=new TextDecoder,xe=class{constructor(t=Se){this.maxFrame=t}maxFrame;subprotocol=$n;encode(t){return xn(t,this.capFor(t.type))}decode(t){let n=An(t,Math.max(this.maxFrame,kn)),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:zo.encode(JSON.stringify(r))})}decodeJson(t,n){let r;try{r=JSON.parse(Qo.decode(t.payload))}catch{throw new k(S.badJson,"frame payload is not valid JSON")}let o=mn(n,r);if(!o.success)throw new k(S.badPayload,o.error.message);return o.data}capFor(t){return t===18?this.maxFrame:kn}};var En=1e4;function Rn(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!==re||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 je=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={};cancellation=new AbortController;get signal(){return this.cancellation.signal}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;try{this.writer.writeFrame(this.codec.encodeJson(20,this.id,r))}finally{this.notifyReset(r)}}receive(t){if(!this.resetPayload)switch(t.type){case 17:this.handlers.onHeaders?.(this.codec.decodeJson(t,wn));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,vn);this.resetPayload=n,this.notifyReset(n);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.notifyReset(t))}notifyReset(t){this.cancellation.abort(new k(S.streamReset,`${t.code}: ${t.message}`)),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 Ue=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,re,{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===re){t.type===32&&(this.goingAway=!0,this.opts.onGoaway?.(this.opts.codec.decodeJson(t,Sn)));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,yn);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 je(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 De=class{constructor(t){this.onCancel=t}onCancel;buffered=[];pending=null;ended=!1;error=null;cancelled=!1;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.buffered.length=0,this.pending)){let n=this.pending;this.pending=null,n.reject(t)}}[Symbol.asyncIterator](){let t=!1,n=()=>{t||this.cancelled||(this.cancelled=!0,this.ended=!0,this.error=null,this.buffered.length=0,this.pending?.resolve({value:void 0,done:!0}),this.pending=null,this.onCancel?.())};return{next:()=>this.buffered.length>0?Promise.resolve({value:this.buffered.shift(),done:!1}):this.error?Promise.reject(this.error):this.ended?(t=!0,Promise.resolve({value:void 0,done:!0})):new Promise((r,o)=>{this.pending={resolve:s=>{s.done&&(t=!0),r(s)},reject:o}}),return:async()=>(n(),{value:void 0,done:!0}),throw:async r=>{throw n(),r}}}};function _n(e){let t=new De;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 Tn(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 Ae=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=Rn(t,n,2,fn,this.opts.handshakeTimeoutMs??En);t.send(n.encodeJson(1,re,r));let s=await o;return this.mux=new Ue(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:_n(t),hasBody:n.hasBody,signal:t.signal});t.sendHeaders({status:r.status,headers:r.headers}),await Tn(t,r.body)}catch(r){try{t.sendReset(S.forwardError,r instanceof Error?r.message:String(r))}catch{}}}};var ht="tunnels:write + tunnels:connect",gt=[`--tunnel ora needs ORA_API_KEY: an ora platform key (ora_sk_...) with the ${ht} 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
24
|
`),Zo=1,es=32,mt=()=>new _("interrupted before the tunnel was ready");function ts(e){let t;try{t=new URL(e.includes("://")?e:`http://${e}`)}catch{throw new _(`not a local target: ${JSON.stringify(e)}`)}if(t.protocol!=="http:")throw new _(`--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 In(e,t={}){let n=ts(e),r=t.apiKey??process.env.ORA_API_KEY;if(!r)throw new _(gt);let o=pn(t.platformUrl),s;try{s=await Ne(o,r)}catch(A){throw new _(`${A instanceof Error?A.message:String(A)}
|
|
25
|
-
(--tunnel ora needs a platform key with the ${ht} scopes)`)}if(t.signal?.aborted)throw mt();let i=await rs(o,s),a=()=>ss(o,s,i.id,()=>Ne(o,r)),c,l,u=!1,d=()=>{},
|
|
26
|
-
`)))),l=u=>{let{code:d,reason:
|
|
27
|
-
`;function Ln(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 gs(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 fs(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"}}function ys(e){let t=e?.mcpUrl;return typeof t=="string"&&t?t:void 0}async function Nn(e){let t=gs(e.url);if(!t)return console.error(`Not a scannable URL or domain: ${JSON.stringify(e.url)}`),$.USAGE;let n=Ln(e.minScore,"--min-score",0,100),r=Ln(e.maxAge,"--max-age",0,86400);for(let
|
|
28
|
-
`)),$.USAGE;if(o.kind==="ora"&&!process.env.ORA_API_KEY)return console.error(gt),$.USAGE;let i=!e.json;i&&E.start(`Auditing ${t} with ora`);let a,c,l=new AbortController,u=async()=>{await a?.close()},d=
|
|
29
|
-
`)}else{console.log(""),console.log(wt.default.yellow(` ${at}`));let p=ys(
|
|
30
|
-
`);else for(let
|
|
31
|
-
`),$.BELOW_MIN_SCORE}return $.OK}var b=
|
|
32
|
-
`);let
|
|
33
|
-
|
|
34
|
-
`);for(;
|
|
35
|
-
|
|
36
|
-
`),!g)continue;let f;try{f=JSON.parse(g.data)}catch{continue}if(g.event==="trajectory"){let
|
|
37
|
-
`;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
|
|
25
|
+
(--tunnel ora needs a platform key with the ${ht} scopes)`)}if(t.signal?.aborted)throw mt();let i=await rs(o,s),a=()=>ss(o,s,i.id,()=>Ne(o,r)),c,l,u=!1,d=()=>{},m=new Promise(A=>{d=A}),g=new Promise((A,C)=>{t.signal?.aborted&&C(mt()),t.signal?.addEventListener("abort",()=>C(mt()),{once:!0})}),f;try{f=ns(i),c=await Promise.race([is(f,s),g]),l=new Ae({socket:as(c),codec:new xe,hello:{agentVersion:`ax/${we.version}`,target:{protocol:"http",host:n.host,port:n.port},maxStreams:es},forwarder:ls(n.host,n.port),onConnectionClosed:A=>{u||d(new _(`ora tunnel connection dropped: ${A.message}`))}}),await Promise.race([l.start(),g]),await ut(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 h=l,p,y=()=>(p||(u=!0,p=(async()=>{try{h.close(1e3,"ax exit")}catch{}await a()})()),p);return{url:f.publicUrl,close:y,dropped:m}}function ns(e){if(!e.publicUrl||!e.connection?.url||!e.connection.subprotocol)throw new _("ora created a tunnel but returned no public URL to connect to");if(e.connection.kind!=="ora-ws")throw new _(`ora returned a "${e.connection.kind}" tunnel, which this version of ax cannot connect; upgrade ax`);return e}async function rs(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,Cn.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 _(`${os(n.status)}${s?`: ${s}`:""}`)}if(!o.id)throw new _("ora created a tunnel but returned no id");return o}function os(e){switch(e){case 401:return"ora rejected the platform key (401). Check ORA_API_KEY";case 403:return`the platform key lacks the ${ht} 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 ss(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 is(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 _(["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:m}=u;i(()=>o(new _(`ora closed the tunnel connection (${d??"?"} ${m??""})`)))};s.addEventListener("open",a),s.addEventListener("error",c),s.addEventListener("close",l)})}function as(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===Zo&&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 cs=new Set(["host","connection","keep-alive","transfer-encoding","upgrade","te"]);function ls(e,t){return{forward:n=>new Promise((r,o)=>{let s=(0,On.request)({host:e,port:t,path:n.path,method:n.method,headers:ds(n.headers)},i=>r({status:i.statusCode??502,headers:ps(i),body:i}));s.on("error",o),us(n.body,s).catch(i=>{s.destroy(i instanceof Error?i:new Error(String(i))),o(i)})})}}async function us(e,t){try{for await(let n of e)t.write(n)||await(0,Pn.once)(t,"drain")}finally{t.end()}}function ds(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!cs.has(t.toLowerCase())))}function ps(e){let t={};for(let[n,r]of Object.entries(e.headers))r!==void 0&&(t[n]=r);return t}var ft=J(F(),1);function Z(e,t){let n=process.stdout.columns??100;return Math.min(t,Math.max(e,n))}function oe(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 pe=["\u25C7","\u25C7","\u25C8","\u25C8","\u25C6","\u25C6","\u25C8","\u25C8"];function O(e){return e.replace(/[\u0000-\u001f\u007f-\u009f]/g," ")}var ms=80,Fe,yt=0,ke="";function hs(){let e=ft.default.cyan(pe[yt%pe.length]),t=Math.max(10,(process.stderr.columns??80)-2),n=ke.length>t?`${ke.slice(0,t-1)}\u2026`:ke;process.stderr.write(`\r\x1B[K${e} ${ft.default.dim(n)}`),yt++}var E={start(e){E.stop(),yt=0,ke=e,process.stderr.isTTY&&(Fe=setInterval(hs,ms))},update(e){ke=e},stop(){Fe&&(clearInterval(Fe),Fe=void 0,process.stderr.write("\r\x1B[K"))}};var $={OK:0,BELOW_MIN_SCORE:1,USAGE:2,API:3},Mn=`--min-score skipped: the MCP handshake requires credentials, so the target is unscored
|
|
27
|
+
`;function Ln(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 gs(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 fs(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"}}function ys(e){let t=e?.mcpUrl;return typeof t=="string"&&t?t:void 0}async function Nn(e){let t=gs(e.url);if(!t)return console.error(`Not a scannable URL or domain: ${JSON.stringify(e.url)}`),$.USAGE;let n=Ln(e.minScore,"--min-score",0,100),r=Ln(e.maxAge,"--max-age",0,86400);for(let h of[n,r])if(h.error)return console.error(h.error),$.USAGE;let o=fs(e);if("error"in o)return console.error(o.error),$.USAGE;let s=o.kind!=="none";if(!s&<(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(`
|
|
28
|
+
`)),$.USAGE;if(o.kind==="ora"&&!process.env.ORA_API_KEY)return console.error(gt),$.USAGE;let i=!e.json;i&&E.start(`Auditing ${t} with ora`);let a,c,l=new AbortController,u=async()=>{await a?.close()},d=h=>{process.removeListener("SIGINT",d),process.removeListener("SIGTERM",d),l.abort(),(async()=>{await c?.catch(()=>{}),await u()})().finally(()=>process.exit(h==="SIGINT"?130:143))},m=t;if(o.kind!=="none"){i&&E.update(`Opening a tunnel to ${t}`),process.on("SIGINT",d),process.on("SIGTERM",d);try{c=o.kind==="ora"?In(t,{signal:l.signal}):un(o.command),a=await c}catch(h){return E.stop(),process.removeListener("SIGINT",d),process.removeListener("SIGTERM",d),console.error(h instanceof Error?h.message:String(h)),$.USAGE}m=a.url}let g;try{let h=tn(m,{progress:i?p=>E.update(p):void 0,maxAgeSeconds:r.value,force:e.force,ephemeral:s||void 0,apiKey:e.apiKey?.trim()||void 0});g=a?.dropped?await Promise.race([h,a.dropped.then(p=>Promise.reject(p))]):await h}catch(h){if(E.stop(),Zt(h)){if(e.json){let p=h.payload===void 0?{code:h.code,message:h.message}:h.payload;process.stdout.write(`${JSON.stringify(p,null,2)}
|
|
29
|
+
`)}else{console.log(""),console.log(wt.default.yellow(` ${at}`));let p=ys(h.payload);p&&console.log(wt.default.dim(` MCP endpoint: ${p}`)),console.log("")}return n.value!==void 0&&process.stderr.write(Mn),$.OK}return console.error(`Audit failed: ${h instanceof Error?h.message:String(h)}`),h instanceof j?$.API:$.USAGE}finally{await u(),process.removeListener("SIGINT",d),process.removeListener("SIGTERM",d)}E.stop();let{result:f}=g;if(e.json)process.stdout.write(`${JSON.stringify(f,null,2)}
|
|
30
|
+
`);else for(let h of an(rn(g,t),{showSkipped:e.showSkipped,showPassing:e.showPassing,tunnel:s}))console.log(h);if(n.value!==void 0){if(f.mcpAuthRequired)return process.stderr.write(Mn),$.OK;if(f.score<n.value)return e.json||console.log(` Score ${f.score} is below the required minimum ${n.value}
|
|
31
|
+
`),$.BELOW_MIN_SCORE}return $.OK}var b=J(F(),1);var ws="https://ora.ai",bs=12e4,vs=5e3,Ss=180,xs=15*6e4,As=6e4,ks=5,$s=2e3,T=class extends Error{},$e=class extends T{constructor(n,r,o){super(n);this.status=r;this.retryAfterMs=o}status;retryAfterMs};function bt(e){return(e??process.env.ORA_API_URL??ws).replace(/\/+$/,"")}async function vt(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 T(`ora request failed: ${r}`)}if(!t.ok)throw new T(`ora request failed: ${await ce(t)}`);return await t.json()}function Un(e){return vt(`${bt(e)}/api/journey/intents`)}function Dn(e){return vt(`${bt(e)}/api/journey/agents`)}function Es(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 Rs(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 T(`ora journey request failed: ${a}`)}if(o.status===401)throw new T("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: 20 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 T(`ora journey caller limit exceeded${i?` \u2014 retry after ${St(Number(i)*1e3)}`:""} (${a})`)}if(o.status===503)throw new T("ora's run engine is unavailable right now \u2014 try again shortly");if(!o.ok)throw new T(`ora journey request failed: ${await ce(o)}`);let s=await o.json();return be(s.contractVersion),{record:s,cached:s.rate_limited===!0,allowance:Es(o)}}function St(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 _s(e){if(!e)return"starting\u2026";if(e.type==="text")return"thinking\u2026";if(e.action==="search")return e.search_query?`searching \u201C${jn(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} ${jn(t,48)}`:`${n}\u2026`}function jn(e,t){return e.length>t?`${e.slice(0,t-1)}\u2026`:e}async function Ts(e,t,n){let r=t.startsWith("http")?t:`${e}${t}`,o=n.idleMs??bs,s=z(o),i=()=>new T(`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",...n.apiKey?{authorization:`Bearer ${n.apiKey}`}:{}},signal:s.signal})}catch(d){if(s.disarm(),s.tripped())throw i();let m=d instanceof Error?d.message:String(d);throw new T(`ora journey stream failed: ${m}`)}if(!a.ok||!a.body){s.disarm();let d=Number(a.headers.get("retry-after"));throw new $e(`ora journey stream failed (${a.status}): ${await ce(a)}`,a.status,Number.isFinite(d)&&d>0?d*1e3:void 0)}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,`
|
|
32
|
+
`);let m=u.indexOf(`
|
|
33
|
+
|
|
34
|
+
`);for(;m!==-1;){let g=dt(u.slice(0,m));if(u=u.slice(m+2),m=u.indexOf(`
|
|
35
|
+
|
|
36
|
+
`),!g)continue;let f;try{f=JSON.parse(g.data)}catch{continue}if(g.event==="trajectory"){let h=f.steps??[],p=h.filter(y=>y.type==="tool_call").at(-1);n.progress?.(`step ${h.length} \xB7 ${_s(p??h.at(-1))}`),n.onTrajectory?.(h)}else if(g.event==="processing")n.progress?.(typeof f.message=="string"?f.message:"generating insights\u2026");else if(g.event==="result"){l.result=f;break e}else if(g.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 T)throw d;let m=d instanceof Error?d.message:String(d);throw new T(`ora journey stream error: ${m}`)}finally{s.disarm(),a.body.cancel().catch(()=>{})}return l}async function Cs(e,t,n,r){let o=n.reopenPauseMs??$s,s,i=0;for(let a=0;a<=ks&&Date.now()<r;a++){a>0&&(n.progress?.("stream dropped \u2014 reopening"),await Q(i)),i=o;try{let c=await Ts(e,t,n);if(c.result||c.errorMessage)return c.errorMessage;s=new T("ora journey stream closed before the run ended")}catch(c){if(s=c,c instanceof $e){if(c.status!==429)throw c;i=Math.min(c.retryAfterMs??o,As)}}}throw s??new T("ora journey stream was never opened")}function We(e,t){return vt(`${e}/api/journey/runs/${encodeURIComponent(t)}`)}async function Ps(e,t,n,r){let o=n.pollEveryMs??vs,s=n.pollLimit??Ss,i=await We(e,t);for(let a=0;a<s&&i.status==="running"&&Date.now()<r;a++){n.progress?.("agent working\u2026 (polling)"),await Q(o);try{i=await We(e,t)}catch{}}return i}async function Fn(e,t){let n=bt(t.baseUrl);t={...t,apiKey:t.apiKey||process.env.ORA_PARTNER_API_KEY||process.env.ORA_SCAN_API_KEY||void 0};let r=await Rs(n,e,t),{record:o}=r;r.cached&&t.progress?.("target at its 24h cap \u2014 fetching the most recent stored run");let s,i;if(o.status==="running"){let c=Date.now()+(t.followBudgetMs??xs),l=t.noStream?{...t,onTrajectory:void 0}:t;try{s=await Cs(n,o.stream_url,l,c)}catch(u){if(u instanceof $e&&u.status!==429)throw u;i=u instanceof Error?u.message:String(u),t.progress?.(`stream unavailable (${i}) \u2014 polling`),await Ps(n,o.id,t,c)}}let a=await Os(n,o.id,t);if(a.status==="running")throw s?new T(`ora journey run failed: ${s}`):new T(`run ${o.id} is still executing \u2014 ${i?`the stream could not be followed (${i}) and polling ran out of time`:"the stream ended"} before a terminal result. Check ${n}/api/journey/runs/${o.id} shortly`);return be(a.contractVersion),{record:o,cached:r.cached,retryAfterMs:r.record.retry_after_ms,allowance:r.allowance,detail:a,engineError:s}}async function Os(e,t,n){let r=await We(e,t);for(let o=0;o<3&&r.status==="running";o++)n.progress?.("finalizing\u2026"),await Q(1500),r=await We(e,t);return r}var P=J(F(),1);function xt(e){if(!e)return{};let t=e.match(/https?:\/\/([^/\s]+)(\/\S*)?/i);return t?{host:t[1],path:t[2]??"/"}:{}}function se(e){return/search/i.test(`${e.tool??""} ${e.action??""}`)}function Is(e){if(se(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 Ms(e,t){if(se(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:oe(`"${c}"`,t),meta:l?`${l} results`:void 0,tone:"ok",notes:[],children:[]}}let{host:n,path:r}=xt(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:Is(e),label:oe(`${n??"?"}${r??""}`,t),meta:a,tone:s?"redirect":i?"error":"ok",notes:[],children:[]}}function Be(e,t,n){let r=Z(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:oe(t,s),tone:"root",notes:[],children:[]},a=new Map,c=[],l,u,d;for(let m of e){if(m.type==="text"&&m.kind==="reasoning"){let h=(m.thinking??m.text??"").trim();h&&c.push(oe(h,s));continue}if(m.type!=="tool_call")continue;let g=Ms(m,o);g.notes=c,c=[],a.set(m.id,g);let f=i;if(!se(m)){let h=m.attribution?.referrer?.step_id,p=m.attribution?.kind,y=h!=null?a.get(h):void 0;y&&y!==g?f=y:p==="web_search"&&l?f=l:p==="previous_artifact"&&u&&(f=u)}f.children.push(g),se(m)?l=g:u=g,d=g}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"&&se(o)).length,r=[`${P.default.bold(String(e.length))} steps`];return t&&r.push(`${P.default.bold(String(t))} reasoning`),n&&r.push(`${P.default.bold(String(n))} search${n===1?"":"es"}`),r.join(P.default.dim(" \xB7 "))}function Ls(e){switch(e){case"root":return{frame:P.default.dim,ink:t=>P.default.bold(t)};case"active":return{frame:P.default.cyan,ink:t=>P.default.cyan(P.default.bold(t))};case"redirect":return{frame:P.default.yellow,ink:P.default.yellow};case"error":return{frame:P.default.red,ink:P.default.red};default:return{frame:P.default.green,ink:P.default.green}}}var Wn=e=>P.default.dim(`(\u2026) ${e}`);function Bn(e,t){let{frame:n,ink:r}=Ls(e.tone),s=`${e.icon} ${e.label}${e.meta?` ${e.meta}`:""}`.length+2,i=`${e.icon} ${r(e.label)}${e.meta?` ${P.default.dim(e.meta)}`:""}`,a=e.children.length>0,c=e.notes.map(Wn);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,m=Bn(l,!0),g=l.notes.length+1;m.forEach((f,h)=>{let p;h===g?p=d?" \u2570\u2500\u2500":" \u251C\u2500\u2500":h<g?p=" \u2502 ":p=d?" ":" \u2502 ",c.push(P.default.dim(p)+f)})}),c}function He(e){let t=Bn(e.root,!1);return e.looseNotes.length&&(t.push(""),t.push(...e.looseNotes.map(Wn))),t}var Ge=J(F(),1);var me=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=Ge.default.cyan(pe[this.beat%pe.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} ${Ge.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[Ge.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}
|
|
37
|
+
`;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 q={OK:0,RUN_FAILED:1,USAGE:2,API:3},Ns="public caps: 100 runs/24h per target \xB7 20 runs/24h per IP",js="keyed caps: 1000 runs/24h per key \xB7 no per-target cap",Us={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 At(e){return console.error(b.default.red(`ax deep-journey: ${e}`)),q.API}function Ds(e,t){if(t==="failed")return b.default.red("\u2717 run failed");switch(e){case"satisfied":return b.default.green("\u2713 task satisfied");case"partial":return b.default.yellow("\u25D0 partially satisfied");case"unsatisfied":return b.default.red("\u2717 task not satisfied");default:return b.default.dim("\xB7 not gradable")}}function kt(e){return`${e.label} \xB7 ${e.variant}`}function Jn(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 Hn(e,t,n){return[` ${Je(e)}`,"",...He(Be(e,t,n)).map(r=>` ${r}`)]}var Fs=e=>e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e);function Ws(e){return e<.01?`$${e.toFixed(4)}`:e<1?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function Bs(e){if(!e)return;let{input_tokens:t,output_tokens:n}=e;if(!(t==null&&n==null))return(t??0)+(n??0)}function Js(e){return(e?.trajectory?.steps??[]).filter(t=>t.action==="search").length}function $t(e,t,n){return e>=t?b.default.green:e>=n?b.default.yellow:b.default.red}function Hs(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:$t(s,70,40)})}if(t?.answer_efficiency!=null){let s=Math.round(t.answer_efficiency*100);o.push({label:"answer efficiency",pct:s,paint:$t(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:$t(i,70,35)})}return o}function Gs(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))}${b.default.dim("\u25B1".repeat(t-r))}`,s=`${e.pct}%`.padStart(4);return` ${b.default.dim(e.label.padEnd(n))} ${o} ${e.paint(b.default.bold(s))}`}function Et(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 Ks(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 m of e){i.push(Et(`${m.pct}%`,s,p=>m.paint(b.default.bold(p))));let g=s-2,f=Math.max(1,Math.min(g,Math.round(m.pct/100*g)));a.push(` ${m.paint("\u2594".repeat(f))}${b.default.dim("\u2594".repeat(g-f))} `);let h=M(m.label.toUpperCase(),s).map(p=>Et(p,s,b.default.dim));c.push(h),l=Math.max(l,h.length)}let u=m=>` ${m.join(" ".repeat(r))}`,d=["",u(i),u(a)];for(let m=0;m<l;m++)d.push(u(c.map(g=>g[m]??Et("",s,b.default.dim))));return d}function Gn(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=["",` ${b.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=`${b.default.dim("\u25B0".repeat(c))}${b.default.dim("\u25B1".repeat(20-c))}`;s.push(` ${b.default.dim(i.label.padEnd(o))} ${l} ${b.default.dim(`${a}%`.padStart(4))}`)}return s}function qs(e){return b.default.dim(` ${"\u2500".repeat(Math.min(e-4,52))}`)}function Ys(e,t){let n=e.run_signals,r=[];if(n?.reached_anchor!=null){let c=n.reached_anchor?b.default.green("\u2713 reached the site"):b.default.red("\u2717 never reached the site");r.push("",` ${c}`)}let o=Hs(e);if(o.length){let c=Ks(o,t);if(c)r.push(...c);else{r.push("");for(let l of o)r.push(Gs(l))}}let s=n?.answer_basis;s&&s.sections_total>0&&r.push(...Gn("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(...Gn("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 Vs(e,t){let n=Z(60,120),{detail:r}=e,o=r.result,s=["",qs(n),""];s.push(` ${Ds(r.verdict,r.status)} ${b.default.dim("\xB7")} ${b.default.dim(r.domain??t)}`);let i=[];r.step_count!=null&&i.push(`${r.step_count} steps`);let a=o?.run_signals?.search_count??Js(o);a&&i.push(`${a} search${a===1?"":"es"}`),o?.duration_ms!=null&&i.push(`${(o.duration_ms/1e3).toFixed(1)}s`);let c=Bs(o);if(c!=null&&i.push(`${Fs(c)} tokens`),o?.cost_usd!=null&&i.push(Ws(o.cost_usd)),i.length&&s.push(` ${b.default.dim(i.join(" \xB7 "))}`),o&&s.push(...Ys(o,n)),o?.insight?.summary){s.push("");for(let u of M(O(o.insight.summary),n-4))s.push(` ${u}`)}let l=o?.insight?.key_observations??[];if(l.length){s.push("",` ${b.default.bold("Observations")}`);for(let u of l){let[d,...m]=M(O(u),n-6);s.push(` ${b.default.cyan("\xB7")} ${d}`);for(let g of m)s.push(` ${g}`)}}return r.status==="failed"&&s.push("",b.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("",b.default.dim(` For the 4-layer readiness audit, run: ax audit ${t}`)),s}async function Kn(e){let t=e.url.trim();if(!t)return console.error("ax deep-journey: a target URL or domain is required"),q.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"),q.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)"),q.USAGE;let s=e.intent,i,a=r??"journey";try{let[p,y]=await Promise.all([r?void 0:Un(),Dn()]);if(p){if(s===void 0)s=p.defaultId;else if(!p.intents.some(ae=>ae.id===s))return console.error(`ax deep-journey: unknown intent "${s}". Available intents:
|
|
38
38
|
${p.intents.map(ae=>` ${ae.id.padEnd(12)} ${ae.hint}`).join(`
|
|
39
|
-
`)}`),
|
|
39
|
+
`)}`),q.USAGE;let N=p.intents.find(ae=>ae.id===s);a=(N?.template||N?.hint||N?.label||s||"journey").replace(/\{domain\}/g,t)}let C=y.agents.some(N=>N.harness==="claude-agent-sdk"&&/haiku/i.test(N.model))?y.agents:[Us,...y.agents],Ee=C.find(N=>N.harness==="claude-agent-sdk"&&/haiku/i.test(N.model))?.id??y.defaultId,Re=e.agent??Ee,Dt=C.find(N=>N.id===Re);if(!Dt)return console.error(`ax deep-journey: unknown agent "${Re}". Available agents:
|
|
40
40
|
${C.map(N=>` ${N.id.padEnd(12)} ${kt(N)}`).join(`
|
|
41
|
-
`)}`),
|
|
42
|
-
`}var ni=new Map([["/.well-known/ard.json","ard.json"],["/.well-known/ai-catalog.json","ai-catalog.json"],["/.well-known/poppy.json","poppy.json"]]);function
|
|
43
|
-
`):console.error(`generate-files failed: ${
|
|
44
|
-
`),$.OK;let n=e.out??".",{writes:r,
|
|
45
|
-
`),i.result?.outcome==="success"?0:1}catch(i){return console.error(`Journey failed: ${i instanceof Error?i.message:String(i)}`),2}let n=new me,r=[],o=!1,s=()=>[` ${Je(r)}`,"",...He(Be(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 pt(t,{snapshot:a=>{r=a;let c=a[a.length-1];n.draw(s(),c?
|
|
46
|
-
`),$.OK;console.log("");for(let o of r){let s=o.digest?ge.default.dim(` ${o.digest.slice(0,19)}\u2026`):"";if(console.log(` ${ge.default.bold(o.name)}${s}`),o.description)for(let i of
|
|
47
|
-
`).map(i=>i.trim()).filter(i=>i.length>0).join(", ");t[o]=t[o]===void 0?s:`${t[o]}, ${s}`}return t}function Tt(e){try{return new URL(e).host}catch{return""}}var
|
|
41
|
+
`)}`),q.USAGE;i=Dt}catch(p){return At(p instanceof Error?p.message:String(p))}e.json||console.error(b.default.dim(o?js:Ns));let c=n&&!e.noStream,l=new me,u=[],d=`waking ${i.label}`,m=()=>l.draw(Hn(u,a,!1),d);c?(console.log(),console.log(` ${b.default.cyan("\u25B6")} ${b.default.bold(t)} ${b.default.dim("\xB7")} ${b.default.dim(kt(i))} ${b.default.dim("\xB7")} ${b.default.dim(r?"custom task":s??"default")}`),console.log(),l.open(),m()):n&&E.start(`Sending ${kt(i)} to ${t} (${r?`"${r}"`:s})`);let g=p=>{c?(d=p,m()):n&&E.update(p)},f;try{f=await Fn(t,{intentId:r?void 0:s,task:r,apiKey:o,harness:i.harness,model:i.model,noStream:e.noStream,progress:n?g:void 0,onTrajectory:c?p=>{u=p.map(Jn),m()}:void 0})}catch(p){return c?l.close():n&&E.stop(),p instanceof T?At(p.message):At(p instanceof Error?p.message:String(p))}if(c?l.close():n&&E.stop(),e.json)return console.log(JSON.stringify(f.detail,null,2)),f.detail.status==="failed"?q.RUN_FAILED:q.OK;f.cached?console.error(b.default.yellow(`This target hit its 24h cap \u2014 showing the most recent stored run${f.retryAfterMs?` (fresh run in ${St(f.retryAfterMs)})`:""}.`)):f.allowance.remaining!==void 0&&f.allowance.limit!==void 0&&console.error(b.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(Jn);if(h.length){console.log();for(let p of Hn(h,a,!0))console.log(p)}for(let p of Vs(f,t))console.log(p);return f.detail.status==="failed"?q.RUN_FAILED:q.OK}var he=require("fs"),W=require("path"),D=J(F(),1);var Xs="https://ora.ai",zs=3e4,Y=class extends Error{status;payload;constructor(t,n={}){super(t),this.name="AgentFilesApiError",this.status=n.status??null,this.payload=n.payload}},Qs=/^[a-z0-9._-]+$/;function Zs(e){if(!e.startsWith("/"))return!1;let t=e.slice(1).split("/");return t.length>=1&&t.length<=6&&t.every(n=>Qs.test(n)&&n!=="."&&n!=="..")}function qn(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t--;return e.slice(0,t)}function ei(e){return qn(e.trim().replace(/^https?:\/\//i,""))}async function Yn(e,t={}){let n=qn(t.baseUrl??process.env.ORA_API_URL??Xs),r=`${n}/api/agent-files/${encodeURIComponent(ei(e))}?include=all`,o;try{o=await fetch(r,{headers:{accept:"application/json"},signal:AbortSignal.timeout(zs)})}catch(i){throw new Y(`could not reach ora at ${n}: ${i instanceof Error?i.message:String(i)}`)}if(!o.ok){let{message:i,payload:a}=await ve(o);throw new Y(i,{status:o.status,payload:a})}let s=await o.json();if(!Array.isArray(s?.files))throw new Y("ora answered without a files list",{status:o.status,payload:s});for(let i of s.files)if(!Zs(i.path))throw new Y(`ora named a file path ax will not write: ${JSON.stringify(i.path)}`,{status:o.status,payload:s});return s}function ti(e){return typeof e.body=="string"?e.body:`${JSON.stringify(e.content,null,2)}
|
|
42
|
+
`}var ni=new Map([["/.well-known/ard.json",[".well-known","ard.json"]],["/.well-known/ai-catalog.json",[".well-known","ai-catalog.json"]],["/.well-known/poppy.json",[".well-known","poppy.json"]],["/.well-known/api-catalog",[".well-known","api-catalog"]],["/llms.txt",["llms.txt"]],["/robots.txt",["robots.txt"]]]),ri="/server-card";function oi(e,t){if(!e.url)return!0;try{return new URL(e.url).hostname===t}catch(n){if(n instanceof TypeError)return!1;throw n}}function si(e,t){let n=(0,W.resolve)(t),r={writes:[],elsewhere:[],unknown:[]};for(let o of e.files){if(!oi(o,e.domain)){r.elsewhere.push(o);continue}let s=ni.get(o.path);if(s)r.writes.push({target:(0,W.join)(n,...s),file:o});else if(o.path.endsWith(ri)){let i=(0,W.join)(n,...o.path.slice(1).split("/"));if((0,W.relative)(n,i).startsWith(".."))throw new Y(`refusing to write outside ${n}: ${o.path}`);r.writes.push({target:i,file:o})}else r.unknown.push(o)}return r}function Vn(e,t=process.cwd()){let n=(0,W.relative)(t,e);return n&&!n.startsWith("..")&&!(0,W.isAbsolute)(n)?n:e}function ii(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 Xn(e){if(!e.domain?.trim())return console.error("Usage: ax generate-files <domain>"),$.USAGE;let t;try{t=await Yn(e.domain,{baseUrl:e.baseUrl})}catch(c){return e.json&&c instanceof Y&&c.payload!==void 0?process.stdout.write(`${JSON.stringify(c.payload,null,2)}
|
|
43
|
+
`):console.error(`generate-files failed: ${c instanceof Error?c.message:String(c)}`),c instanceof Y&&c.status===400?$.USAGE:$.API}if(e.json)return process.stdout.write(`${JSON.stringify(t,null,2)}
|
|
44
|
+
`),$.OK;let n=e.out??".",{writes:r,elsewhere:o,unknown:s}=si(t,n);for(let c of s)console.error(D.default.yellow(`skipped ${c.path}: this version of ax does not write it - upgrade with npm i -g ax@latest`));let i=r.filter(c=>(0,he.existsSync)(c.target));if(i.length>0&&!e.force){console.error("These files already exist, so nothing was written:");for(let c of i)console.error(` ${Vn(c.target)}`);return console.error(D.default.dim("Pass --force to overwrite them, or --out <dir> to write somewhere else.")),$.USAGE}for(let{target:c,file:l}of r)(0,he.mkdirSync)((0,W.dirname)(c),{recursive:!0}),(0,he.writeFileSync)(c,ti(l));let a=c=>{for(let l of c){let[u,...d]=ii(l,74,"");console.log(D.default.dim(` - ${u}`));for(let m of d)console.log(D.default.dim(` ${m}`))}};console.log(""),console.log(` ${D.default.bold(t.domain)} ${D.default.dim(t.scannedAt?`from ora's scan of ${t.scannedAt.slice(0,10)}`:"not scanned by ora yet")}`),console.log("");for(let{target:c,file:l}of r)console.log(` ${D.default.green("wrote")} ${Vn(c)} ${D.default.dim(`${l.spec.name} ${l.spec.version}`)}`),a(l.notes),console.log("");for(let c of o)console.log(` ${D.default.yellow("not written")} ${c.url} ${D.default.dim(`${c.spec.name} ${c.spec.version}`)}`),a(["This file is served from another host, so it is not written here. Run with --json to get its body.",...c.notes]),console.log("");return t.notes&&t.notes.length>0&&(console.log(` ${D.default.bold("Not drafted")}`),a(t.notes),console.log("")),console.log(D.default.dim(` Publish them at https://${t.domain}/ from your web root - these are drafts, review each before you ship it.`)),console.log(""),$.OK}var x=J(F(),1);var Ke=()=>Z(60,120);function ai(e){if(e.type==="tool_call"){let t=e.input_display??e.summary??"";if(se(e))return t?`searching ${oe(t,40)}`:"searching\u2026";let{host:n}=xt(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 ci=e=>e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e);function li(e){return e<.01?`$${e.toFixed(4)}`:e<1?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function ui(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(`${ci(t.totalTokens)} tokens`),t?.costUsd!=null&&r.push(li(t.costUsd)),["",` ${x.default.dim("\u2500".repeat(Math.min(Ke()-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 di(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 pi(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 mi(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")} ${di(n)} ${r(x.default.bold(`${n}/100`))} ${o}`)}if(e.summary){t.push("");for(let n of M(e.summary,Ke()-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,Ke()-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(` ${pi(n.priority)} ${x.default.bold(n.title)}`);for(let r of M(n.detail,Ke()-8))t.push(` ${x.default.dim(r)}`)}}return t.push(""),t}function hi(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 zn(e){let t={intent:e.intent,domain:e.domain,harness:e.harness,model:e.model};if(e.json)try{let i=await pt(t);return process.stdout.write(`${hi(i)}
|
|
45
|
+
`),i.result?.outcome==="success"?0:1}catch(i){return console.error(`Journey failed: ${i instanceof Error?i.message:String(i)}`),2}let n=new me,r=[],o=!1,s=()=>[` ${Je(r)}`,"",...He(Be(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 pt(t,{snapshot:a=>{r=a;let c=a[a.length-1];n.draw(s(),c?ai(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 ui(i.result,i.usage))console.log(a);if(i.insight)for(let a of mi(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 qe=require("fs"),_t=require("path"),ge=J(F(),1);var Zn=require("crypto"),gi="https://ora.ai",G=class extends Error{};function er(e){return(e??process.env.ORA_API_URL??gi).replace(/\/+$/,"")}async function Rt(e){let t=er(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 G(`could not reach the skill registry at ${t}: ${o instanceof Error?o.message:String(o)}`)}if(!n.ok)throw new G(`skill registry answered HTTP ${n.status}`);let r=await n.json();if(!Array.isArray(r.skills))throw new G("skill registry index has no skills[]");return r.skills}function Qn(e){return`sha256:${(0,Zn.createHash)("sha256").update(e).digest("hex")}`}async function tr(e,t){let n=er(t),r=await Rt(n),o=r.find(c=>c.name===e);if(!o){let c=r.map(l=>l.name).join(", ");throw new G(`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 G(`could not fetch ${s}: ${c instanceof Error?c.message:String(c)}`)}if(!i.ok)throw new G(`skill fetch answered HTTP ${i.status} for ${s}`);let a=new Uint8Array(await i.arrayBuffer());if(o.digest&&Qn(a)!==o.digest)throw new G(`digest mismatch for ${e}: index says ${o.digest}, served bytes hash to ${Qn(a)} - refusing to use them`);return{entry:o,bytes:a}}var fi=".claude/skills";function yi(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 nr(e){try{if(!e.name){let r=await Rt();if(e.json)return process.stdout.write(`${JSON.stringify(r,null,2)}
|
|
46
|
+
`),$.OK;console.log("");for(let o of r){let s=o.digest?ge.default.dim(` ${o.digest.slice(0,19)}\u2026`):"";if(console.log(` ${ge.default.bold(o.name)}${s}`),o.description)for(let i of yi(o.description,76," "))console.log(ge.default.dim(i));console.log("")}return console.log(ge.default.dim(" Install one with: ax skill <name> --install")),console.log(""),$.OK}let{entry:t,bytes:n}=await tr(e.name);if(e.install){let r=(0,_t.join)(e.dir??fi,t.name);(0,qe.mkdirSync)(r,{recursive:!0});let o=(0,_t.join)(r,"SKILL.md");return(0,qe.writeFileSync)(o,n),console.log(`Installed ${t.name} to ${o}`),t.digest&&console.log(ge.default.dim(`verified ${t.digest}`)),$.OK}return process.stdout.write(n),$.OK}catch(t){let n=t instanceof Error?t.message:String(t);return console.error(`Skill command failed: ${n}`),t instanceof G&&n.includes("unknown skill")?$.USAGE:$.API}}var R=class extends Error{constructor(t,n){super(t,n),this.name="CdpError"}},rr=1e4,or=5e3,Ct=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}`))},or);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??rr;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 Ot(e,t=or){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 Ye=class e{connection;product;constructor(t,n){this.connection=t,this.product=n}static async connect(t){let n=await Ct.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 Pt(this.connection,o,n,t.entryUrl);return await s.prepare(t.initScripts??[],t.viewport),s}close(){this.connection.close()}},wi=8,bi=1024*1024,vi=new Set(["Image","Media","Font"]),Pt=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=Tt(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;(vi.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:Si(o.headers??{})});return}if(n!=="Script"||this.scriptsStarted>=wi)return;let s=typeof o.url=="string"?o.url:"",i=Tt(s);i&&(i!==this.entryHost&&i!==Tt(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,bi)})}).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=rr){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 Si(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.toLowerCase(),s=r.split(`
|
|
47
|
+
`).map(i=>i.trim()).filter(i=>i.length>0).join(", ");t[o]=t[o]===void 0?s:`${t[o]}, ${s}`}return t}function Tt(e){try{return new URL(e).host}catch{return""}}var xi=new Set([2,3]),Ai=8192,ki=864e10;function $i(e){if(typeof e!="string")return null;let t=e.trim();if(t.length===0||t.length>Ai)return null;let n;try{n=Buffer.from(t,"base64")}catch{return null}if(n.length<=69||!xi.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>ki?null:{origin:i,feature:a,expiry:c,isSubdomain:s.isSubdomain===!0,isThirdParty:s.isThirdParty===!0}}function Ei(e){return e.toLowerCase().replace(/[^a-z]/g,"").includes("modelcontext")}function Ri(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 sr(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=$i(s);if(!i)continue;let a=Ei(i.feature),c=i.expiry*1e3>n.getTime(),l=Ri(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 ir(e){return e?e.split(",").map(t=>t.trim()).filter(t=>t.length>0):[]}var It="capture-incomplete:";function _i(e){return e.imperative!==null||e.polyfillPackages.length>0}function ar(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||_i(e.staticSignals)?"declared-inactive":"absent"}function cr(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 lr={"shared-experience":30,"task-completion":25,"tool-quality":25,trust:20},Mt={"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"}},ie="1";function Ti(e,t,n){return!!(t["cf-mitigated"]==="challenge"||e===403&&n.includes("cf-browser-verification")||e===503&&n.includes("challenge-platform"))}function ur(e,t,n){return!!(Ti(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 Ci=100,pr=4096,Pi=32768,Oi=50,Ii=200,dr="__oraWebmcpCapture",mr=`(function () {
|
|
48
48
|
"use strict";
|
|
49
49
|
try {
|
|
50
50
|
var W = typeof globalThis !== "undefined" ? globalThis : window;
|
|
51
51
|
if (W.${dr}) return;
|
|
52
52
|
|
|
53
53
|
var SHIM_VERSION = ${JSON.stringify(ie)};
|
|
54
|
-
var MAX_TOOLS = ${
|
|
54
|
+
var MAX_TOOLS = ${Ci};
|
|
55
55
|
var MAX_DESCRIPTION_CHARS = ${pr};
|
|
56
|
-
var MAX_SCHEMA_CHARS = ${
|
|
57
|
-
var MAX_ERRORS = ${
|
|
56
|
+
var MAX_SCHEMA_CHARS = ${Pi};
|
|
57
|
+
var MAX_ERRORS = ${Oi};
|
|
58
58
|
// Internal bound only: a page looping on addEventListener must not grow
|
|
59
59
|
// the shim's retained set without limit.
|
|
60
60
|
var MAX_LISTENERS = 50;
|
|
@@ -526,7 +526,7 @@ ${C.map(N=>` ${N.id.padEnd(12)} ${kt(N)}`).join(`
|
|
|
526
526
|
}
|
|
527
527
|
}
|
|
528
528
|
})();`,hr=`(function () {
|
|
529
|
-
var MAX_FORMS = ${
|
|
529
|
+
var MAX_FORMS = ${Ii};
|
|
530
530
|
var MAX_DESCRIPTION_CHARS = ${pr};
|
|
531
531
|
var forms = [];
|
|
532
532
|
var nodes = document.querySelectorAll("form[toolname], [toolname]");
|
|
@@ -543,8 +543,8 @@ ${C.map(N=>` ${N.id.padEnd(12)} ${kt(N)}`).join(`
|
|
|
543
543
|
});
|
|
544
544
|
}
|
|
545
545
|
return { forms: forms };
|
|
546
|
-
})()`;var fr=["@mcp-b/global","@mcp-b/react-webmcp","usewebmcp"];function
|
|
547
|
-
`)),s=new Set;for(let a of r){let c=a.toLowerCase();for(let l of fr)c.includes(l)&&s.add(l)}let i=gr(e)||r.some(gr);return{imperative:o,polyfillPackages:[...s],keywordMention:i}}var vr=15e3,
|
|
546
|
+
})()`;var fr=["@mcp-b/global","@mcp-b/react-webmcp","usewebmcp"];function Mi(e){let t=e.toLowerCase(),n=/document\.modelcontext/.test(t),r=/navigator\.modelcontext/.test(t),o=/modelcontext\??\.(registertool|providecontext)/.test(t),s=fr.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 Li=["webmcp","web model context protocol"];function gr(e){let t=e.toLowerCase();return Li.some(n=>t.includes(n))}function yr(e,t,n){let r=[t,...n.map(a=>a.body)],o=Mi(r.join(`
|
|
547
|
+
`)),s=new Set;for(let a of r){let c=a.toLowerCase();for(let l of fr)c.includes(l)&&s.add(l)}let i=gr(e)||r.some(gr);return{imperative:o,polyfillPackages:[...s],keywordMention:i}}var vr=15e3,Ni=3e4,ji=2e3,Ui=250,Di={fast:12e3,deep:2e4},Fi=2*1024*1024,Sr=512,Wi=512,Bi=60,Ji=15e5,xr={width:1280,height:720},wr={imperative:null,polyfillPackages:[],keywordMention:!1},Hi=`(function () {
|
|
548
548
|
var tokens = [];
|
|
549
549
|
try {
|
|
550
550
|
var metas = document.querySelectorAll('meta[http-equiv="origin-trial" i]');
|
|
@@ -569,7 +569,7 @@ ${C.map(N=>` ${N.id.padEnd(12)} ${kt(N)}`).join(`
|
|
|
569
569
|
} catch (e) {
|
|
570
570
|
return null;
|
|
571
571
|
}
|
|
572
|
-
})()`,
|
|
572
|
+
})()`,Gi=`(function () {
|
|
573
573
|
try {
|
|
574
574
|
var g = window.__oraWebmcpCapture;
|
|
575
575
|
if (!g) return "none";
|
|
@@ -579,26 +579,26 @@ ${C.map(N=>` ${N.id.padEnd(12)} ${kt(N)}`).join(`
|
|
|
579
579
|
} catch (e) {
|
|
580
580
|
return "error";
|
|
581
581
|
}
|
|
582
|
-
})()`;function kr(e,t){return e.filter(n=>!n.unregistered).map(n=>({name:n.name.slice(0,Sr),description:n.description,via:"imperative",entryPoint:n.source==="provideContext"?"provideContext":n.entryPoint,pageUrl:t,inputSchema:n.inputSchema,annotations:
|
|
583
|
-
`)[0].slice(0,300)}function Xe(e,t){return Math.max(250,Math.min(t,e-Date.now()))}function
|
|
584
|
-
`)}}try{let t=await
|
|
585
|
-
`):null}function
|
|
586
|
-
`)[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 ${Er/1e3}s.`)}async function
|
|
587
|
-
`)}var
|
|
582
|
+
})()`;function kr(e,t){return e.filter(n=>!n.unregistered).map(n=>({name:n.name.slice(0,Sr),description:n.description,via:"imperative",entryPoint:n.source==="provideContext"?"provideContext":n.entryPoint,pageUrl:t,inputSchema:n.inputSchema,annotations:qi(n.annotations),hasExecute:n.hasExecute,registrationMs:n.registrationMs}))}function Ki(e,t){return e.map(n=>({name:n.toolName.slice(0,Sr),description:n.toolDescription,via:"declarative",entryPoint:"form",pageUrl:t,inputSchema:null,annotations:{},hasExecute:!0,registrationMs:null}))}function qi(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,Wi)),n}function Yi(e){if(!e)return[];let t=[...e.registrationErrors];return e.takenOver.length>0&&t.push(`${It} the page replaced modelContext on ${e.takenOver.join(", ")}, so imperative tools may be under-reported`),e.extraToolCount>0&&t.push(`${It} the capture's tool cap was reached and ${e.extraToolCount} further registration attempts were not stored`),t}function Vi(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 Xi(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:xr});let a;try{a=await i.goto(t,Xe(n,vr))}catch(h){return{...s,navMs:Date.now()-o,loadError:Ve(h)}}let c=Date.now()-o;await i.waitForLoad(Xe(n,5e3));let l=a?.headers??{},u=a?.status??0,d=(await i.content()).slice(0,Fi),m=await i.inlineScripts(),g=await i.evaluate(Hi).catch(()=>null)??{},f=r?await ta(i,n):null;return{finalUrl:i.url(),navMs:c,blocked:ur(u,l,d),nativeApi:g.nativeApi===!0,originTrialTokens:[...ir(l["origin-trial"]),...Array.isArray(g.metaTokens)?g.metaTokens:[]],permissionsPolicy:l["permissions-policy"]??null,html:d,inlineJs:m,scripts:i.collectedScripts(),screenshot:f,loadError:null}}catch(a){return{...s,navMs:Date.now()-o,loadError:Ve(a)}}finally{await i?.close()}}async function zi(e,t,n,r,o){let s=null;try{s=await e.newContext({initScripts:[mr],entryUrl:t,viewport:xr});try{await s.goto(t,Xe(r,vr))}catch(l){return{snapshot:null,declarative:null,quietMs:0,loadError:Ve(l)}}let i=await Qi(s,n,r,o),a=await s.evaluate(Ar).catch(()=>null),c=await s.evaluate(hr).catch(()=>null);return{snapshot:a,declarative:c,quietMs:i,loadError:null}}catch(i){return{snapshot:null,declarative:null,quietMs:0,loadError:Ve(i)}}finally{await s?.close()}}async function Qi(e,t,n,r){let o=Date.now(),s=Math.min(Di[t],Math.max(0,n-o)),i=null,a=o;for(;Date.now()-o<s;){let c=await e.evaluate(Gi).catch(()=>null);if(c!==i)i=typeof c=="string"?c:null,a=Date.now(),r&&await Zi(e,r);else if(Date.now()-a>=ji)break;if(await ra(Math.min(Ui,Math.max(0,n-Date.now()))),Date.now()>=n)break}return Date.now()-o}async function Zi(e,t){let n=await e.evaluate(Ar).catch(()=>null);n&&t(kr(n.tools,e.url()))}async function ea(e,t,n,r,o){let s=Date.now(),i=s+Ni,a=await Xi(e,t,i,r),l=a.loadError!==null||a.blocked?{snapshot:null,declarative:null,quietMs:0,loadError:null}:await zi(e,t,n,i,o),u=a.loadError??l.loadError,d=l.snapshot,m=(l.declarative?.forms??[]).filter(Re=>Re.toolName.trim()!==""),g=a.finalUrl||t,f=d?kr(d.tools,g):[],h=Ki(m,g),p=[...f,...h],y=na(a.html,a.inlineJs,a.scripts),A=sr(a.originTrialTokens,br(g)??br(t)??"",new Date),C={loadError:u,blocked:a.blocked,nativeApi:a.nativeApi,originTrialValid:A?.valid===!0,declarativeToolCount:h.length,toolCount:p.length,shimTakenOver:(d?.takenOver.length??0)>0,staticSignals:y},Ee=ar(C);return{page:{url:t,finalUrl:g,verdict:Ee,status:cr(Ee,p),tools:p,declarativeFormCount:h.length,consumer:{nativeApi:a.nativeApi,originTrial:A,permissionsPolicy:a.permissionsPolicy,iframeAllow:Vi(a.permissionsPolicy)},staticSignals:y,apiSurface:{toolchangeEvents:d?.toolchangeEvents??0,provideContextCalls:d?.provideContextCalls??0,registrationErrors:Yi(d)},timing:{navMs:a.navMs,quietMs:l.quietMs,totalMs:Date.now()-s},error:u},screenshot:a.blocked?null:a.screenshot}}async function $r(e){let{url:t,endpoint:n,mode:r="fast",screenshot:o=!0,onTools:s}=e,i=Date.now(),a=new Date().toISOString(),c=await Ye.connect(n);try{let l=await ea(c,t,r,o,s);return{url:t,pages:[l.page],chromeVersion:c.product,shimVersion:ie,capturedAt:a,durationMs:Date.now()-i,screenshot:l.screenshot}}finally{c.close()}}async function ta(e,t){let n=await e.screenshot(Bi,Xe(t,5e3));if(!n||n.byteLength===0||n.byteLength>Ji)return null;let r=e.viewportSize();return{data:n.toString("base64"),mimeType:"image/jpeg",width:r?.width??0,height:r?.height??0}}function na(e,t,n){if(!e)return wr;try{return yr(e,t,n)}catch{return wr}}function br(e){try{return new URL(e).origin}catch{return null}}function Ve(e){return(e instanceof Error?e.message:String(e)).split(`
|
|
583
|
+
`)[0].slice(0,300)}function Xe(e,t){return Math.max(250,Math.min(t,e-Date.now()))}function ra(e){return new Promise(t=>setTimeout(t,e))}var Rr=require("child_process"),K=require("fs"),_r=require("os"),Nt=require("path");var Tr=9222;async function Cr(e){if(e)try{return{ok:!0,endpoint:await Ot(e),close:async()=>{},launched:!1}}catch(t){let n=Lt(t);return{ok:!1,message:[`No debuggable Chrome answered at ${e}.`,...n.startsWith("no debuggable Chrome answered")?[]:[n],"",...oa(Tr)].join(`
|
|
584
|
+
`)}}try{let t=await ma();return{ok:!0,endpoint:t.endpoint,close:t.close,launched:!0}}catch(t){return{ok:!1,message:Lt(t)}}}function Pr(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(`
|
|
585
|
+
`):null}function oa(e){return["The audit drives a Chrome you already have; it never downloads one.","Start one with a debugging port and a scratch profile:","",` ${Or(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 Or(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 Lt(e){return e instanceof R||e instanceof Error?e.message:String(e)}function sa(){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 ia(){for(let e of sa())try{if((0,K.statSync)(e).isFile())return e}catch{}return null}var aa=["--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 ca(){return process.env.AX_WEBMCP_NO_SANDBOX==="1"}var Er=2e4,la=3e3,ua=4,da=150;function pa(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 ma(){let e=ia();if(!e)throw new R(fa());let t=(0,K.mkdtempSync)((0,Nt.join)((0,_r.tmpdir)(),"ax-webmcp-")),n=(0,Rr.spawn)(e,[...aa,...ca()?["--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 pa(n,la),await ga(t)};process.once("SIGINT",r),process.once("SIGTERM",r);try{let s=await ha(t,n);return{endpoint:await Ot(`127.0.0.1:${s}`),close:o}}catch(s){throw await o(),s instanceof R?s:new R(Lt(s))}}async function ha(e,t){let n=(0,Nt.join)(e,"DevToolsActivePort"),r=Date.now()+Er;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,K.readFileSync)(n,"utf8").split(`
|
|
586
|
+
`)[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 ${Er/1e3}s.`)}async function ga(e){for(let t=0;t<ua;t++){try{if((0,K.rmSync)(e,{recursive:!0,force:!0}),!(0,K.existsSync)(e))return}catch{}await new Promise(n=>setTimeout(n,da))}try{(0,K.rmSync)(e,{recursive:!0,force:!0})}catch{}}function fa(){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:","",` ${Or(Tr)}`].join(`
|
|
587
|
+
`)}var ya="https://ora.ai",wa=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}},Ir=4*1024*1024,Mr=10,Lr=100,Nr=32768,jr=4096,Ur=512;function Dr(e){if(e.shimVersion!==ie)return`this build captures with shim version ${e.shimVersion}, which is not the version it was built against (${ie})`;if(e.pages.length>Mr)return`capture covers ${e.pages.length} pages; the limit is ${Mr}`;for(let t of e.pages){if(t.tools.length>Lr)return`${t.url} registered ${t.tools.length} tools; the limit is ${Lr} per page`;for(let n of t.tools){if(n.name.length>Ur)return`tool name on ${t.url} is ${n.name.length} characters; the limit is ${Ur}`;if(n.description.length>jr)return`description for "${n.name}" is ${n.description.length} characters; the limit is ${jr}`;for(let[r,o]of[["inputSchema",n.inputSchema],["annotations",n.annotations]]){let s=ba(o);if(s===null)return`${r} for "${n.name}" could not be serialized (a cycle, or a value JSON cannot carry)`;if(s.length>Nr)return`${r} for "${n.name}" serializes to ${s.length} characters; the limit is ${Nr}`}}}return null}function Fr(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 ba(e){try{return JSON.stringify(e)??"null"}catch{return null}}async function Wr(e,t,n={}){let r=(n.baseUrl??process.env.ORA_API_URL??ya).replace(/\/+$/,""),o=n.idleMs??wa,s=z(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")>Ir)throw s.disarm(),new L(`this capture serializes to ${Math.round(Buffer.byteLength(a,"utf8")/1024)} KB; the ingest limit is ${Ir/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 va(c);return Sa(c,s,n,i)}async function va(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.
|
|
588
588
|
Upgrade with \`npm i -g ax@latest\` (or \`npx ax@latest webmcp-audit \u2026\`) and run it again.
|
|
589
589
|
|
|
590
|
-
ora said: ${t?.error??"shim version mismatch"}`,{code:n}):e.status===503?new L(`ora cannot score right now: ${
|
|
590
|
+
ora said: ${t?.error??"shim version mismatch"}`,{code:n}):e.status===503?new L(`ora cannot score right now: ${xa(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 ce(e)}`,{code:n})}async function Sa(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,`
|
|
591
591
|
`);let c=s.indexOf(`
|
|
592
592
|
|
|
593
|
-
`);for(;c!==-1;){let l=
|
|
593
|
+
`);for(;c!==-1;){let l=Aa(s.slice(0,c));if(s=s.slice(c+2),c=s.indexOf(`
|
|
594
594
|
|
|
595
|
-
`),!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
|
|
595
|
+
`),!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 xa(e){let t=e.trim();return/[.!?]$/.test(t)?t:`${t}.`}function Aa(e){let t=[];for(let n of e.split(`
|
|
596
596
|
`))n.startsWith("data:")&&t.push(n.slice(5).replace(/^ /,""));return t.join(`
|
|
597
|
-
`)}var w=
|
|
597
|
+
`)}var w=J(F(),1);var jt=12,ka=["fail","warning","unmeasured","na","pass"],Ut={fail:["\u2716",w.default.red],warning:["\u25B2",w.default.yellow],unmeasured:["?",w.default.magenta],na:["\u2013",w.default.dim],pass:["\u2714",w.default.green]},$a={fail:"Failing",warning:"Warnings",unmeasured:"Not measured",na:"Not applicable",pass:"Passing"},Ea=["shared-experience","task-completion","tool-quality","trust"],Ra={"shared-experience":"Shared experience","task-completion":"Task completion","tool-quality":"Tool quality",trust:"Trust"};function Br(e,t={}){let n=Z(80,120),r=e.availability.status==="ready";return["",..._a(e,n),"",...Ca(e.availability,n),...r?["",...Pa(e,n),"",...Ia(e)]:[],"",...La(e.findings,n,t.showPassing===!0),...Ua(e.simulation,n),"",...Da(e,n)]}function _a(e,t){let n=[` ${w.default.bold(O(e.url))}`],r=`${e.toolCount} tool${e.toolCount===1?"":"s"}`,o=[Ta(e.verdict),r,`Chrome ${O(e.chromeVersion)}`];return e.error&&o.push(w.default.red(O(e.error))),n.push(` ${w.default.dim(o.join(" \xB7 "))}`),n.map(s=>Jr(s,t))}function Ta(e){switch(e){case"active":return w.default.green("active");case"testing-only":case"declared-inactive":case"api-empty":return w.default.yellow(e);case"blocked":case"load-error":return w.default.red(e);default:return w.default.dim(e)}}function Ca(e,t){let[n,r]=e.status==="ready"?["agent-ready",w.default.green]:e.status==="not-ready"?["not agent-ready",w.default.red]:["availability unknown",w.default.yellow],o=[` ${r(w.default.bold(n))}`];for(let s of e.reasons)o.push(...M(O(s.detail),t-4).map(i=>` ${w.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=>` ${w.default.dim(s)}`)),o}function Pa(e,t){let n=e.score===null?"\u2014":String(e.score),r=[` ${w.default.bold(`${n}/100`)} ${Oa(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=>` ${w.default.dim(o)}`)),r}function Oa(e){return e.grade!==null?w.default.bold(w.default.green(`grade ${e.grade}`)):w.default.dim("grade withheld")}function Ia(e){let t=[` ${w.default.bold("Pillars")}`];for(let n of Ea){let r=e.categoryScores[n]??0,o=lr[n],s=e.findings.some(c=>Mt[c.checkId]?.category===n&&c.status!=="na"&&c.status!=="unmeasured"),i=s?Ma(r):w.default.dim("\u2591".repeat(jt)),a=s?`weight ${o}`:`weight ${o} \xB7 nothing measured`;t.push(` ${Ra[n].padEnd(18)} ${i} ${String(r).padStart(3)}% ${w.default.dim(a)}`)}return t}function Ma(e){let t=Math.round(Math.min(100,Math.max(0,e))/100*jt);return`${(e>=75?w.default.green:e>=40?w.default.yellow:w.default.red)("\u2588".repeat(t))}${w.default.dim("\u2591".repeat(jt-t))}`}function La(e,t,n){let r=[` ${w.default.bold("Checks")}`];for(let o of ka){let s=e.filter(i=>i.status===o);if(s.length!==0){if(o==="pass"&&!n){r.push(` ${w.default.dim(`${s.length} passing (--show-passing to list)`)}`);continue}r.push("",` ${w.default.bold($a[o])} (${s.length})`);for(let i of s)r.push(...Na(i,t))}}return e.length===0&&r.push(` ${w.default.dim("no checks reported")}`),r}function Na(e,t){let[n,r]=Ut[e.status],o=ja(e.checkId),i=[` ${r(n)} ${o}${e.toolName?w.default.dim(` ${O(e.toolName)}`):""}`];return e.details&&i.push(...M(O(e.details),t-10).map(a=>` ${w.default.dim(a)}`)),e.evidence&&i.push(...M(O(e.evidence),t-10).map(a=>` ${w.default.dim(a)}`)),i}function ja(e){return Mt[e]?.title??e}function Ua(e,t){if(!e)return[];let n=["",` ${w.default.bold("Tool selection")}`];if(e.skipped)return n.push(...M(O(e.skipReason??"The selection simulation did not run."),t-4).map(o=>` ${w.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 ${w.default.dim(O(e.model))}`);for(let o of e.steps){let[s,i]=o.ok?Ut.pass:Ut.fail,a=o.chosenTool?O(o.chosenTool):w.default.dim("nothing");n.push(` ${i(s)} ${Jr(O(o.intent),t-30)} ${w.default.dim("\u2192")} ${a}`)}return n}function Da(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=>` ${w.default.dim(r)}`):[]}function Jr(e,t){return e.length>t?`${e.slice(0,t-1)}\u2026`:e}var B={OK:0,BELOW_MIN_SCORE:1,USAGE:2,API:3};function Fa(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 Wa(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 Hr(e){let t=Fa(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"),B.USAGE;let n=Wa(e.minScore);if(n.error)return console.error(n.error),B.USAGE;let r=await Cr(e.chromeEndpoint);if(!r.ok)return console.error(r.message),B.USAGE;e.json||E.start(r.launched?`Starting Chrome and capturing ${t}`:`Capturing ${t}`);let o;try{o=await $r({url:t,endpoint:r.endpoint,onTools:d=>{e.json||E.update(`Capturing ${t} \u2014 ${d.length} tools`)}})}catch(d){return E.stop(),console.error(`Capture failed: ${d instanceof Error?d.message:String(d)}`),B.API}finally{await r.close()}let s=o.pages[0];if(s?.error)return E.stop(),console.error(`Could not capture ${t}: ${s.error}`),console.error("Is the dev server running?"),B.USAGE;let i=Dr(o);if(i)return E.stop(),console.error(`ora would refuse this capture: ${i}`),B.USAGE;let{capture:a,droppedScreenshot:c}=Fr(o);e.json||E.update("Scoring with ora");let l;try{l=await Wr(t,a,{apiKey:e.apiKey??process.env.ORA_API_KEY,onEvent:d=>{e.json||E.update(Ba(d))}})}catch(d){return E.stop(),d instanceof L?(console.error(d.message),B.API):(console.error(`Scoring failed: ${d instanceof Error?d.message:String(d)}`),B.API)}if(E.stop(),e.json)console.log(JSON.stringify(l,null,2));else for(let d of Br(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=Pr(o);if(u&&console.error(`
|
|
598
598
|
${u}`),n.value!==void 0){if(l.availability.status!=="ready")return e.json||console.log(`
|
|
599
599
|
Not agent-ready, so there is no score to compare against --min-score ${n.value}
|
|
600
|
-
`),
|
|
601
|
-
ora returned no score, so --min-score cannot be evaluated.`),
|
|
600
|
+
`),B.BELOW_MIN_SCORE;if(l.score===null)return e.json||console.error(`
|
|
601
|
+
ora returned no score, so --min-score cannot be evaluated.`),B.API;if(l.score<n.value)return e.json||console.log(`
|
|
602
602
|
Score ${l.score} is below the required minimum ${n.value}
|
|
603
|
-
`),F.BELOW_MIN_SCORE}return F.OK}function Fa(e){switch(e.type){case"phase":return`Scoring with ora \u2014 ${e.phase}`;case"tool-discovered":return`Scoring with ora \u2014 found ${O(e.tool.name)}`;case"finding":return`Scoring with ora \u2014 ${e.finding.checkId}`;case"simulation-step":return`Scoring with ora \u2014 simulating "${O(e.step.intent)}"`;default:return"Scoring with ora"}}function Gr(){if(typeof process.loadEnvFile!="function")return!1;try{return process.loadEnvFile(),!0}catch{return!1}}var Y="ax",Wa={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 Nn({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"]})}},Ba={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 zn({intent:e.intent,domain:e.domain,harness:e.harness,model:e.model,json:!!e.json})}},Ja={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:"Hide the live trajectory view and print only the final result",default:!1}},async run({args:e}){process.exitCode=await Kn({url:e.url,intent:e.intent,task:e.task,apiKey:e["api-key"],agent:e.agent,json:!!e.json,noStream:!!e["no-stream"]})}},Ha={meta:{name:"generate-files",description:"Draft a domain's agent discovery files (ard.json, ai-catalog.json, poppy.json) into <out>/.well-known/ (exit codes: 0 ok, 2 usage or files already exist, 3 API error)"},args:{domain:{type:"positional",description:"Domain the files speak for (e.g. example.com)",required:!0},out:{type:"string",description:"Directory your site serves from; files land in <out>/.well-known/ (default: current directory)"},force:{type:"boolean",description:"Overwrite files that already exist",default:!1},json:{type:"boolean",description:"Print ora's payload as JSON and write nothing",default:!1}},async run({args:e}){process.exitCode=await Xn({domain:e.domain,out:e.out,force:!!e.force,json:!!e.json})}},Ga={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 nr({name:e.name,install:!!e.install,dir:e.dir,json:!!e.json})}},Ka={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 Hr({url:e.url,json:!!e.json,showPassing:!!e["show-passing"],minScore:e["min-score"],chromeEndpoint:e["chrome-endpoint"],apiKey:e["api-key"]})}};function qa(){let e=ze.default.green("$"),t=ze.default.dim;return["",` ${ze.default.bold(Y)} ${t(`v${we.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")}`,` generate-files ${t("<domain>")} ${t("Draft ard.json, ai-catalog.json and poppy.json for a domain")}`,"",` ${t("Examples:")}`,` ${e} ${Y} audit https://docs.example.com`,` ${e} ${Y} audit https://docs.example.com --min-score 70 ${t("# CI gate")}`,` ${e} ${Y} audit https://docs.example.com --json`,` ${e} ${Y} audit localhost:3000 --tunnel ora ${t("# audit a local dev server")}`,` ${e} ${Y} webmcp-audit http://localhost:3000`,` ${e} ${Y} deep-journey stripe.com --intent pricing`,` ${e} ${Y} journey "Find the API docs and how to authenticate" --domain stripe.com`,` ${e} ${Y} generate-files example.com --out public`,"",` ${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("Hide the live trajectory view and print only the final result")}`,` --json ${t("Print the terminal run detail as JSON")}`,` ${t("no key needed \xB7 public caps: 100 runs/24h per target, 20 runs/24h per IP")}`,"",` ${t("generate-files options:")}`,` --out <dir> ${t("Directory your site serves from; writes <dir>/.well-known/* (default: .)")}`,` --force ${t("Overwrite files that already exist (otherwise nothing is written)")}`,` --json ${t("Print ora's payload as JSON and write nothing")}`,` ${t("drafts from ora's last scan of the domain - review each file before you publish it")}`,"",` ${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(`
|
|
604
|
-
`)}var
|
|
603
|
+
`),B.BELOW_MIN_SCORE}return B.OK}function Ba(e){switch(e.type){case"phase":return`Scoring with ora \u2014 ${e.phase}`;case"tool-discovered":return`Scoring with ora \u2014 found ${O(e.tool.name)}`;case"finding":return`Scoring with ora \u2014 ${e.finding.checkId}`;case"simulation-step":return`Scoring with ora \u2014 simulating "${O(e.step.intent)}"`;default:return"Scoring with ora"}}function Gr(){if(typeof process.loadEnvFile!="function")return!1;try{return process.loadEnvFile(),!0}catch{return!1}}var V="ax",Ja={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 Nn({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"]})}},Ha={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 zn({intent:e.intent,domain:e.domain,harness:e.harness,model:e.model,json:!!e.json})}},Ga={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:"Hide the live trajectory view and print only the final result",default:!1}},async run({args:e}){process.exitCode=await Kn({url:e.url,intent:e.intent,task:e.task,apiKey:e["api-key"],agent:e.agent,json:!!e.json,noStream:!!e["no-stream"]})}},Ka={meta:{name:"generate-files",description:"Draft a domain's agent files (ard.json, ai-catalog.json, poppy.json, llms.txt, a robots.txt edit, api-catalog, MCP server cards) into <out> (exit codes: 0 ok, 2 usage or files already exist, 3 API error)"},args:{domain:{type:"positional",description:"Domain the files speak for (e.g. example.com)",required:!0},out:{type:"string",description:"Your site's web root; files land under it (.well-known/, robots.txt, llms.txt) (default: current directory)"},force:{type:"boolean",description:"Overwrite files that already exist",default:!1},json:{type:"boolean",description:"Print ora's payload as JSON and write nothing",default:!1}},async run({args:e}){process.exitCode=await Xn({domain:e.domain,out:e.out,force:!!e.force,json:!!e.json})}},qa={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 nr({name:e.name,install:!!e.install,dir:e.dir,json:!!e.json})}},Ya={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 Hr({url:e.url,json:!!e.json,showPassing:!!e["show-passing"],minScore:e["min-score"],chromeEndpoint:e["chrome-endpoint"],apiKey:e["api-key"]})}};function Va(){let e=ze.default.green("$"),t=ze.default.dim;return["",` ${ze.default.bold(V)} ${t(`v${we.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")}`,` generate-files ${t("<domain>")} ${t("Draft a domain's agent files: ARD catalog, poppy.json, llms.txt, robots.txt edit, \u2026")}`,"",` ${t("Examples:")}`,` ${e} ${V} audit https://docs.example.com`,` ${e} ${V} audit https://docs.example.com --min-score 70 ${t("# CI gate")}`,` ${e} ${V} audit https://docs.example.com --json`,` ${e} ${V} audit localhost:3000 --tunnel ora ${t("# audit a local dev server")}`,` ${e} ${V} webmcp-audit http://localhost:3000`,` ${e} ${V} deep-journey stripe.com --intent pricing`,` ${e} ${V} journey "Find the API docs and how to authenticate" --domain stripe.com`,` ${e} ${V} generate-files example.com --out public`,"",` ${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("Hide the live trajectory view and print only the final result")}`,` --json ${t("Print the terminal run detail as JSON")}`,` ${t("no key needed \xB7 public caps: 100 runs/24h per target, 20 runs/24h per IP")}`,"",` ${t("generate-files options:")}`,` --out <dir> ${t("Your site's web root: writes .well-known/*, robots.txt, llms.txt there (default: .)")}`,` --force ${t("Overwrite files that already exist (otherwise nothing is written)")}`,` --json ${t("Print ora's payload as JSON and write nothing")}`,` ${t("drafts from ora's last scan of the domain - review each file before you publish it")}`,"",` ${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(`
|
|
604
|
+
`)}var Xa={meta:{name:V,version:we.version,description:"Score any site's agent readiness \u2014 and watch real AI agents navigate it"},subCommands:{audit:Ja,"webmcp-audit":Ya,"deep-journey":Ga,journey:Ha,skill:qa,"generate-files":Ka},setup(){let e=process.argv[2];(!e||e==="--help"||e==="-h")&&(console.log(Va()),process.exit(0))}};Gr();Yt(Xa);
|