ax 0.10.2 → 0.11.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 +26 -19
- package/dist/api/agent-files.d.ts +1 -1
- package/dist/api/deep-journey.d.ts +30 -2
- package/dist/api/key-destination.d.ts +19 -0
- package/dist/api/platform.d.ts +14 -0
- package/dist/api/shared.d.ts +9 -0
- package/dist/api/skills.d.ts +19 -0
- package/dist/contract/index.d.ts +1 -0
- package/dist/contract/types.gen.d.ts +619 -46
- package/dist/contract/version.d.ts +1 -1
- package/dist/env.d.ts +24 -0
- package/dist/index.cjs +160 -22
- package/dist/index.js +160 -22
- package/dist/main.cjs +227 -79
- package/package.json +3 -3
package/dist/main.cjs
CHANGED
|
@@ -1,60 +1,67 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
3
|
-
`)}function
|
|
4
|
-
`)}catch(n){console.error(n)}}var
|
|
5
|
-
`)}function
|
|
6
|
-
`),process.exit(1)}}async function
|
|
7
|
-
`))
|
|
8
|
-
`);let
|
|
2
|
+
"use strict";var Os=Object.create;var Un=Object.defineProperty;var Ms=Object.getOwnPropertyDescriptor;var Ns=Object.getOwnPropertyNames;var Ls=Object.getPrototypeOf,js=Object.prototype.hasOwnProperty;var Us=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Ds=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ns(t))!js.call(e,o)&&o!==n&&Un(e,o,{get:()=>t[o],enumerable:!(r=Ms(t,o))||r.enumerable});return e};var V=(e,t,n)=>(n=e!=null?Os(Ls(e)):{},Ds(t||!e||!e.__esModule?Un(n,"default",{value:e,enumerable:!0}):n,e));var Y=Us((du,jt)=>{"use strict";var ot=process||{},qn=ot.argv||[],rt=ot.env||{},Qs=!(rt.NO_COLOR||qn.includes("--no-color"))&&(!!rt.FORCE_COLOR||qn.includes("--color")||ot.platform==="win32"||(ot.stdout||{}).isTTY&&rt.TERM!=="dumb"||!!rt.CI),ei=(e,t,n=e)=>r=>{let o=""+r,s=o.indexOf(t,e.length);return~s?e+ti(o,t,n,s)+t:e+o+t},ti=(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)},Yn=(e=Qs)=>{let t=e?ei:()=>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")}};jt.exports=Yn();jt.exports.createColors=Yn});var Fs=/\d/,Ws=["-","_","/","."];function Bs(e=""){if(!Fs.test(e))return e!==e.toLowerCase()}function Dn(e,t){let n=t??Ws,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 u=Bs(a);if(i===!1){if(s===!1&&u===!0){r.push(o),o=a,s=u;continue}if(s===!0&&u===!1&&o.length>1){let l=o.at(-1);r.push(o.slice(0,Math.max(0,o.length-1))),o=l+a,s=u;continue}}o+=a,s=u,i=c}return r.push(o),r}function Js(e){return e?e[0].toUpperCase()+e.slice(1):""}function Hs(e){return e?e[0].toLowerCase()+e.slice(1):""}function Gs(e,t){return e?(Array.isArray(e)?e:Dn(e)).map(n=>Js(t?.normalize?n.toLowerCase():n)).join(""):""}function Ue(e,t){return Hs(Gs(e||"",t))}function Ze(e,t){return e?(Array.isArray(e)?e:Dn(e)).map(n=>n.toLowerCase()).join(t??"-"):""}function Fn(e){return Ze(e||"","_")}var Jn=require("util");function De(e){return Array.isArray(e)?e:e===void 0?[]:[e]}function Ct(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 B(e){return typeof e=="function"?e():e}var ae=class extends Error{code;constructor(e,t){super(e),this.name="CLIError",this.code=t}};function Ks(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[f,y]of Object.entries(o)){let S=y;for(let b of S)i.set(f,b),a.has(b)||a.set(b,[]),a.get(b).push(f),i.set(b,f),a.has(f)||a.set(f,[]),a.get(f).push(b)}let c={};function u(f){if(n.has(f))return"boolean";let y=a.get(f)||[];for(let S of y)if(n.has(S))return"boolean";return"string"}function l(f){if(r.has(f))return!0;let y=a.get(f)||[];for(let S of y)if(r.has(S))return!0;return!1}let p=new Set([...n,...r,...Object.keys(o),...Object.values(o).flat(),...Object.keys(s)]);for(let f of p)c[f]||(c[f]={type:u(f),default:s[f]});for(let[f,y]of i.entries())f.length===1&&c[y]&&!c[y].short&&(c[y].short=f);let d=[],m={};for(let f=0;f<e.length;f++){let y=e[f];if(y==="--"){d.push(...e.slice(f));break}if(y.startsWith("--no-")){let S=y.slice(5);m[S]=!0;continue}d.push(y)}let h;try{h=(0,Jn.parseArgs)({args:d,options:Object.keys(c).length>0?c:void 0,allowPositionals:!0,strict:!1})}catch{h={values:{},positionals:d}}let g={_:[]};g._=h.positionals;for(let[f,y]of Object.entries(h.values)){let S=y;u(f)==="boolean"&&typeof y=="string"?S=y!=="false":l(f)&&typeof y=="boolean"&&(S=""),g[f]=S}for(let[f]of Object.entries(m)){g[f]=!1;let y=i.get(f);y&&(g[y]=!1);let S=a.get(f);if(S)for(let b of S)g[b]=!1}for(let[f,y]of i.entries())g[f]!==void 0&&g[y]===void 0&&(g[y]=g[f]),g[y]!==void 0&&g[f]===void 0&&(g[f]=g[y]),g[f]!==g[y]&&s[y]===g[y]&&(g[y]=g[f]);return g}var qs=(()=>{let e=globalThis.process?.env??{};return e.NO_COLOR==="1"||e.TERM==="dumb"||e.TEST||e.CI})(),nt=(e,t=39)=>n=>qs?n:`\x1B[${e}m${n}\x1B[${t}m`,Qe=nt(1,22),ne=nt(36),tt=nt(90),et=nt(4,24);function Ys(e,t){let n={boolean:[],string:[],alias:{},default:{}},r=Hn(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=Ue(a.name),u=Ze(a.name);if(c!==a.name||u!==a.name){let l=De(n.alias[a.name]||[]);c!==a.name&&!l.includes(c)&&l.push(c),u!==a.name&&!l.includes(u)&&l.push(u),l.length>0&&(n.alias[a.name]=l)}}let o=Ks(e,n),[...s]=o._,i=new Proxy(o,{get(a,c){return a[c]??a[Ue(c)]??a[Ze(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 ae(`Missing required positional argument: ${a.name.toUpperCase()}`,"EARG");i[a.name]=a.default}}else if(a.type==="enum"){let c=i[a.name],u=a.options||[];if(c!==void 0&&u.length>0&&!u.includes(c))throw new ae(`Invalid value for argument: ${ne(`--${a.name}`)} (${ne(c)}). Expected one of: ${u.map(l=>ne(l)).join(", ")}.`,"EARG")}else if(a.required&&i[a.name]===void 0)throw new ae(`Missing required argument: --${a.name}`,"EARG");return i}function Hn(e){let t=[];for(let[n,r]of Object.entries(e||{}))t.push({...r,name:n,alias:De(r.alias)});return t}async function Xs(e){return Promise.all(e.map(t=>B(t)))}async function It(e,t){let n=await B(e.args||{}),r=Ys(t.rawArgs,n),o={rawArgs:t.rawArgs,args:r,data:t.data,cmd:e},s=await Xs(e.plugins??[]),i,a;try{for(let l of s)await l.setup?.(o);typeof e.setup=="function"&&await e.setup(o);let u=await B(e.subCommands);if(u&&Object.keys(u).length>0){let l=Gn(t.rawArgs,n),p=t.rawArgs[l];if(p){let d=await Mt(u,p);if(!d)throw new ae(`Unknown command ${ne(p)}`,"E_UNKNOWN_COMMAND");await It(d,{rawArgs:t.rawArgs.slice(l+1)})}else{let d=await B(e.default);if(d){if(e.run)throw new ae("Cannot specify both 'run' and 'default' on the same command.","E_DEFAULT_CONFLICT");let m=await Mt(u,d);if(!m)throw new ae(`Default sub command ${ne(d)} not found in subCommands.`,"E_UNKNOWN_COMMAND");await It(m,{rawArgs:t.rawArgs})}else if(!e.run)throw new ae("No command specified.","E_NO_COMMAND")}}typeof e.run=="function"&&(i=await e.run(o))}catch(u){a=u}let c=[];if(typeof e.cleanup=="function")try{await e.cleanup(o)}catch(u){c.push(u)}for(let u of[...s].reverse())try{await u.cleanup?.(o)}catch(l){c.push(l)}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 Ot(e,t,n){let r=await B(e.subCommands);if(r&&Object.keys(r).length>0){let o=Gn(t,await B(e.args||{})),s=t[o],i=await Mt(r,s);if(i)return Ot(i,t.slice(o+1),e)}return[e,n]}async function Mt(e,t){if(t in e)return B(e[t]);for(let n of Object.values(e)){let r=await B(n),o=await B(r?.meta);if(o?.alias&&De(o.alias).includes(t))return r}}function Gn(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(r==="--")return-1;if(r.startsWith("-")){!r.includes("=")&&Vs(r,t)&&n++;continue}return n}return-1}function Vs(e,t){let n=e.replace(/^-{1,2}/,""),r=Ue(n);for(let[o,s]of Object.entries(t))if(!(s.type!=="string"&&s.type!=="enum")&&(r===Ue(o)||(Array.isArray(s.alias)?s.alias:s.alias?[s.alias]:[]).includes(n)))return!0;return!1}async function Nt(e,t){try{console.log(await Lt(e,t)+`
|
|
4
|
+
`)}catch(n){console.error(n)}}var zs=/^no[-A-Z]/;async function Lt(e,t){let n=await B(e.meta||{}),r=Hn(await B(e.args||{})),o=await B(t?.meta||{}),s=`${o.name?`${o.name} `:""}`+(n.name||process.argv[1]),i=[],a=[],c=[],u=[];for(let m of r)if(m.type==="positional"){let h=m.name.toUpperCase(),g=m.required!==!1&&m.default===void 0;a.push([ne(h+Pt(m)),Wn(m,g)]),u.push(g?`<${h}>`:`[${h}]`)}else{let h=m.required===!0&&m.default===void 0,g=[...(m.alias||[]).map(f=>`-${f}`),`--${m.name}`].join(", ")+Pt(m);if(i.push([ne(g),Wn(m,h)]),m.type==="boolean"&&(m.default===!0||m.negativeDescription)&&!zs.test(m.name)){let f=[...(m.alias||[]).map(y=>`--no-${y}`),`--no-${m.name}`].join(", ");i.push([ne(f),[m.negativeDescription,h?tt("(Required)"):""].filter(Boolean).join(" ")])}h&&u.push(`--${m.name}`+Pt(m))}if(e.subCommands){let m=[],h=await B(e.subCommands);for(let[g,f]of Object.entries(h)){let y=await B((await B(f))?.meta);if(y?.hidden)continue;let S=De(y?.alias),b=[g,...S].join(", ");c.push([ne(b),y?.description||""]),m.push(g,...S)}u.push(m.join("|"))}let l=[],p=n.version||o.version;l.push(tt(`${n.description} (${s+(p?` v${p}`:"")})`),"");let d=i.length>0||a.length>0;return l.push(`${et(Qe("USAGE"))} ${ne(`${s}${d?" [OPTIONS]":""} ${u.join(" ")}`)}`,""),a.length>0&&(l.push(et(Qe("ARGUMENTS")),""),l.push(Ct(a," ")),l.push("")),i.length>0&&(l.push(et(Qe("OPTIONS")),""),l.push(Ct(i," ")),l.push("")),c.length>0&&(l.push(et(Qe("COMMANDS")),""),l.push(Ct(c," ")),l.push("",`Use ${ne(`${s} <command> --help`)} for more information about a command.`)),l.filter(m=>typeof m=="string").join(`
|
|
5
|
+
`)}function Pt(e){let t=e.valueHint?`=<${e.valueHint}>`:"",n=t||`=<${Fn(e.name)}>`;return!e.type||e.type==="positional"||e.type==="boolean"?t:e.type==="enum"&&e.options?.length?`=<${e.options.join("|")}>`:n}function Wn(e,t){let n=t?tt("(Required)"):"",r=e.default===void 0?"":tt(`(Default: ${e.default})`);return[e.description,n,r].filter(Boolean).join(" ")}async function Kn(e,t={}){let n=t.rawArgs||process.argv.slice(2),r=t.showUsage||Nt;try{let o=await Zs(e);if(o.help.length>0&&n.some(s=>o.help.includes(s)))await r(...await Ot(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 ae("No version specified","E_NO_VERSION");console.log(s.version)}else await It(e,{rawArgs:n})}catch(o){o instanceof ae?(await r(...await Ot(e,n)),console.error(o.message)):console.error(o,`
|
|
6
|
+
`),process.exit(1)}}async function Zs(e){let t=await B(e.args||{}),n=new Set,r=new Set;for(let[o,s]of Object.entries(t)){n.add(o);for(let i of De(s.alias))r.add(i)}return{help:Bn("help","h",n,r),version:Bn("version","v",n,r)}}function Bn(e,t,n,r){return n.has(e)||r.has(e)?[]:n.has(t)||r.has(t)?[`--${e}`]:[`--${e}`,`-${t}`]}var _e=V(Y(),1);var Fe={name:"ax",version:"0.11.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":"^4",citty:"^0.2.2","openapi-typescript":"^6.7.6",picocolors:"^1",tsup:"^8",typescript:"^7.0.2",vitest:"^4"},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"]};function Xn(){if(Ut.clear(),typeof process.loadEnvFile!="function")return!1;let e=new Set(Object.keys(process.env).map(Dt));try{process.loadEnvFile();for(let t of Object.keys(process.env).map(Dt))e.has(t)||Ut.add(t);return!0}catch{return!1}}var Ut=new Set;function Dt(e){return process.platform==="win32"?e.toUpperCase():e}function Vn(e){return Ut.has(Dt(e))}var We=class extends Error{constructor(t){super(t),this.name="KeyDestinationError"}};function zn(e){return e==="localhost"||e==="[::1]"||/^127(\.\d{1,3}){3}$/.test(e)}function ri(e){return zn(e)||e.endsWith(".localhost")}function Zn(e,t,n){let r;try{r=new URL(e)}catch{return`${t} is not a URL, so ax did not send your key anywhere.`}if(r.origin===new URL(n).origin)return;let o=ri(r.hostname);if(r.protocol!=="https:"&&!o)return`${t} is ${r.origin}. ax sends your key only over https, or over plain http to this machine.`;if(!zn(r.hostname)&&Vn(t)&&oi(process.env[t],r))return`${t} in ./.env points at ${r.host}, so ax did not send your key there. To use that host, export ${t} in your shell.`}function oi(e,t){try{return e!==void 0&&new URL(e).origin===t.origin}catch{return!1}}function ue(e,t,n){let r=Zn(e,t,n);if(r)throw new We(r)}var Qn="once ORA_PLATFORM_URL is fixed as said above";function de(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 J(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 st(e){let t=null;try{t=await e.clone().json()}catch{return null}if(t?.error!=="usage_limit_reached")return null;let n=t.used!==void 0&&t.limit!==void 0?` (${t.used} of ${t.limit})`:"",r=t.resets_at?` It resets at ${t.resets_at}.`:"",o=t.kind?`${t.kind} limit`:"usage limit",s=t.period?` for the ${t.period}`:"";return`this API key has used its ${o}${s}${n}.${r} GET /api/usage shows the numbers; ask ora to raise the limit.`}async function er(e){return(await J(e)).message}var pe=e=>new Promise(t=>setTimeout(t,e));var Ft="https://api.agentfront.sh";function it(e){return(e??process.env.ORA_PLATFORM_URL??Ft).replace(/\/+$/,"")}var si=3e4,re=class extends Error{status;payload;constructor(t,n){super(t),this.name="PlatformApiError",this.status=n.status,this.payload=n.payload}};function Wt(e){try{return JSON.parse(e)}catch(t){if(t instanceof SyntaxError)return null;throw t}}var ii=12e4;async function at(e,t){ue(e,"ORA_PLATFORM_URL",Ft);let n=await fetch(`${e}/auth/token`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:"{}",signal:AbortSignal.timeout(si)}),r=Wt(await n.text());if(n.status===401)throw new re("ora rejected the API key (401). Check ORA_API_KEY.",{status:401,payload:r});let o=r??{},s=`ora auth failed (${n.status})${o.error?`: ${o.error}`:""}`;if(!n.ok)throw new re(s,{status:n.status,payload:r});if(!o.token)throw new Error(s);return o.token}async function ai(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)}),s=await o.text();if(o.status===429)throw new re("ora rate limit hit (429). Wait a moment and retry.",{status:429,payload:Wt(s)});let i;try{i=JSON.parse(s)}catch{throw new Error(`ora returned a non-JSON response (${o.status})`)}let a=`ora run failed (${o.status}): ${i.message??i.error??s}`;if(!o.ok)throw new re(a,{status:o.status,payload:i});if(!i.runId)throw new Error(a);return i}function Bt(e){let t="message",n=[];for(let r of e.split(`
|
|
7
|
+
`))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(`
|
|
8
|
+
`)}:null}async function ci(e,t,n,r,o){let s=n.startsWith("http")?n:`${e}${n}`,i=de(o),a=await fetch(s,{headers:{authorization:`Bearer ${t}`,accept:"text/event-stream"},signal:i.signal});if(!a.ok)throw i.disarm(),new re(`ora run stream failed (${a.status})`,{status:a.status,payload:Wt(await a.text())});if(!a.body)throw i.disarm(),new Error(`ora run stream failed (${a.status})`);let c=new TextDecoder,u={steps:[],trajectory:[]},l="";try{e:for await(let p of a.body){i.poke(),l=`${l}${c.decode(p,{stream:!0})}`.replace(/\r\n?/g,`
|
|
9
|
+
`);let d=l.indexOf(`
|
|
9
10
|
|
|
10
|
-
`);for(;
|
|
11
|
+
`);for(;d!==-1;){let m=Bt(l.slice(0,d));if(l=l.slice(d+2),d=l.indexOf(`
|
|
11
12
|
|
|
12
|
-
`),!
|
|
13
|
-
`)
|
|
14
|
-
`)
|
|
15
|
-
`))}
|
|
16
|
-
|
|
17
|
-
`))
|
|
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,`
|
|
13
|
+
`),!m)continue;let h;try{h=JSON.parse(m.data)}catch{continue}if(li(u,m.event,h,r),u.summary&&u.insight)break e}}}catch(p){throw i.tripped()?new Error(`ora run stream timed out after ${o}ms of silence`):p}finally{i.disarm(),a.body.cancel().catch(()=>{})}return u}function li(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 ui(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 pe(1200)}}async function Jt(e,t={}){let n=(e.baseUrl??process.env.ORA_PLATFORM_URL??Ft).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 at(n,r),s=await ai(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 ci(n,o,s.streamUrl??`/experiment/v1/runs/${s.runId}/stream`,t,e.idleMs??ii),c=a.summary?await ui(n,o,s.runId):void 0;return{...i,result:a.summary,insight:a.insight,usage:c,steps:a.steps,trajectory:a.trajectory}}var nr=require("crypto");var di="https://ora.ai",H=class extends Error{code;payload;constructor(t,n,r={}){super(t),this.name="SkillApiError",this.code=n,this.payload=r.payload}};function $e(e){return(e??process.env.ORA_API_URL??di).replace(/\/+$/,"")}async function Ht(e){let t=$e(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 H(`could not reach the skill registry at ${t}: ${o instanceof Error?o.message:String(o)}`,"REGISTRY_UNREACHABLE")}if(!n.ok){let{payload:o}=await J(n);throw new H(`skill registry answered HTTP ${n.status}`,"REGISTRY_ERROR",{payload:o})}let r=await n.json();if(!Array.isArray(r.skills))throw new H("skill registry index has no skills[]","REGISTRY_ERROR");return r.skills}function tr(e){return`sha256:${(0,nr.createHash)("sha256").update(e).digest("hex")}`}async function ct(e,t){let n=$e(t),r=await Ht(n),o=r.find(c=>c.name===e);if(!o){let c=r.map(u=>u.name).join(", ");throw new H(`unknown skill ${JSON.stringify(e)} - the registry has: ${c}`,"UNKNOWN_SKILL")}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 H(`could not fetch ${s}: ${c instanceof Error?c.message:String(c)}`,"REGISTRY_UNREACHABLE")}if(!i.ok){let{payload:c}=await J(i);throw new H(`skill fetch answered HTTP ${i.status} for ${s}`,"REGISTRY_ERROR",{payload:c})}let a=new Uint8Array(await i.arrayBuffer());if(o.digest&&tr(a)!==o.digest)throw new H(`digest mismatch for ${e}: index says ${o.digest}, served bytes hash to ${tr(a)} - refusing to use them`,"DIGEST_MISMATCH");return{entry:o,bytes:a}}var pi=/^ {0,3}(`{3,}|~{3,})(.*)$/,mi=/^ {0,3}(#{1,6})[ \t]+(.*?)(?:[ \t]+#+)?[ \t]*$/;function rr(e,t){let n=e.replace(/\r\n?/g,`
|
|
14
|
+
`).split(`
|
|
15
|
+
`),r=t.trim().toLowerCase(),o,s=-1,i=0;for(let a=0;a<n.length;a++){let c=pi.exec(n[a]);if(c){let p=c[1];o===void 0?o=p:p[0]===o[0]&&p.length>=o.length&&!c[2].trim()&&(o=void 0);continue}if(o!==void 0)continue;let u=mi.exec(n[a]);if(!u)continue;let l=u[1].length;if(s===-1)u[2].toLowerCase()===r&&(s=a,i=l);else if(l<=i)return n.slice(s,a).join(`
|
|
16
|
+
`).trimEnd()}return s===-1?null:n.slice(s).join(`
|
|
17
|
+
`).trimEnd()}var nn=V(Y(),1);var Gt="1.42.0";function or(e){let[t=0,n=0]=e.split(".").map(r=>Number.parseInt(r,10));return[t,n]}function hi(e){if(!e||!/^\d+\.\d+\.\d+$/.test(e))return!1;let[t,n]=or(e),[r,o]=or(Gt);return t>r||t===r&&n>o}var sr=!1;function Be(e){sr||!hi(e)||(sr=!0,process.stderr.write(`ora reports contract ${e}; this CLI was built against ${Gt}. Newer fields may be missing from the output - upgrade with: npm i -g ax@latest
|
|
18
|
+
`))}var ir="https://ora.ai",fi=6e4,gi=2e3,yi=45,Kt=14,q=class extends Error{code;payload;constructor(t,n={}){super(t),this.name="AuditApiError",this.code=n.code??null,this.payload=n.payload}},wi="MCP_AUTH_REQUIRED";function ar(e){return e instanceof q&&e.code===wi}function cr(e){return e?{authorization:`Bearer ${e}`}:{}}async function lr(e,t={}){let n=(t.baseUrl??process.env.ORA_API_URL??ir).replace(/\/+$/,"");t={...t,apiKey:t.apiKey||process.env.ORA_SCAN_API_KEY||void 0},t.apiKey&&ue(n,"ORA_API_URL",ir),t.progress?.(`Auditing ${e} with ora`);let r=await Si(n,e,t);Be(r.result.contractVersion);let o=r.result;return ur(o)&&(o=await xi(n,o,t)),{result:o,verdict:r.verdict}}function bi(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 Si(e,t,n){let r=n.idleMs??fi,o=de(r),s=()=>new q(`ora audit timed out \u2014 no progress for ${Math.round(r/1e3)}s`),i;try{i=await fetch(bi(e,t,n),{headers:{accept:"text/event-stream",...cr(n.apiKey)},signal:o.signal})}catch(d){if(o.disarm(),o.tripped())throw s();let m=d instanceof Error?d.message:String(d);throw new q(`ora audit request failed: ${m}`)}if(i.status===429){o.disarm();let d=await st(i),{payload:m}=await J(i);if(d)throw new q(`ora usage limit reached: ${d}`,{payload:m});let h=i.headers.get("retry-after");throw new q(`ora rate limit exceeded${h?` \u2014 retry after ${h}s`:""} (burst: 10 scans/min/IP; daily: 30 scans + 6 force per 24h). An ora-issued scan API key lifts these limits: set ORA_SCAN_API_KEY or pass --api-key.`,{payload:m})}if(!i.ok||!i.body){o.disarm();let d=await J(i);throw new q(`ora audit failed: ${d.message}`,{code:d.code,payload:d.payload})}let a=Ai(),c=new TextDecoder,u="",l,p;try{e:for await(let d of i.body){o.poke(),u=`${u}${c.decode(d,{stream:!0})}`.replace(/\r\n?/g,`
|
|
19
19
|
`);let m=u.indexOf(`
|
|
20
20
|
|
|
21
|
-
`);for(;m!==-1;){let
|
|
22
|
-
|
|
23
|
-
`),!g)continue;let f;try{f=JSON.parse(g.data)}catch{continue}if(Zo(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 Zo(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 es(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 mt(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 Le(n,r),s=await zo(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??Xo),c=a.summary?await es(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 Sc=ue(e=>gn(e,"target")),xc=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||{}),ts=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(!ts.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 En="ora-tunnel.v1",kn=Se,ns=new TextEncoder,rs=new TextDecoder,xe=class{constructor(t=Se){this.maxFrame=t}maxFrame;subprotocol=En;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:ns.encode(JSON.stringify(r))})}decodeJson(t,n){let r;try{r=JSON.parse(rs.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 Rn=1e4;function $n(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 We=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 Tn(e){let t=new We;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 _n(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=$n(t,n,2,fn,this.opts.handshakeTimeoutMs??Rn);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:Tn(t),hasBody:n.hasBody,signal:t.signal});t.sendHeaders({status:r.status,headers:r.headers}),await _n(t,r.body)}catch(r){try{t.sendReset(S.forwardError,r instanceof Error?r.message:String(r))}catch{}}}};var gt="tunnels:write + tunnels:connect",ft=[`--tunnel ora needs ORA_API_KEY: an ora platform key (ora_sk_...) with the ${gt} 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
|
-
`),os=1,ss=32,ht=()=>new T("interrupted before the tunnel was ready");function is(e){let t;try{t=new URL(e.includes("://")?e:`http://${e}`)}catch{throw new T(`not a local target: ${JSON.stringify(e)}`)}if(t.protocol!=="http:")throw new T(`--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=is(e),r=t.apiKey??process.env.ORA_API_KEY;if(!r)throw new T(ft);let o=pn(t.platformUrl),s;try{s=await Le(o,r)}catch(x){throw new T(`${x instanceof Error?x.message:String(x)}
|
|
25
|
-
(--tunnel ora needs a platform key with the ${gt} scopes)`)}if(t.signal?.aborted)throw ht();let i=await cs(o,s),a=()=>us(o,s,i.id,()=>Le(o,r)),c,l,u=!1,d=()=>{},m=new Promise(x=>{d=x}),g=new Promise((x,C)=>{t.signal?.aborted&&C(ht()),t.signal?.addEventListener("abort",()=>C(ht()),{once:!0})}),f;try{f=as(i),c=await Promise.race([ds(f,s),g]),l=new Ae({socket:ps(c),codec:new xe,hello:{agentVersion:`ax/${we.version}`,target:{protocol:"http",host:n.host,port:n.port},maxStreams:ss},forwarder:hs(n.host,n.port),onConnectionClosed:x=>{u||d(new T(`ora tunnel connection dropped: ${x.message}`))}}),await Promise.race([l.start(),g]),await dt(f.publicUrl,t.routableMs,t.probeEveryMs,t.signal)}catch(x){u=!0;try{l?l.close(1e3,"ax setup failed"):c?.close()}catch{}throw await a(),x}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 as(e){if(!e.publicUrl||!e.connection?.url||!e.connection.subprotocol)throw new T("ora created a tunnel but returned no public URL to connect to");if(e.connection.kind!=="ora-ws")throw new T(`ora returned a "${e.connection.kind}" tunnel, which this version of ax cannot connect; upgrade ax`);return e}async function cs(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 T(`${ls(n.status)}${s?`: ${s}`:""}`)}if(!o.id)throw new T("ora created a tunnel but returned no id");return o}function ls(e){switch(e){case 401:return"ora rejected the platform key (401). Check ORA_API_KEY";case 403:return`the platform key lacks the ${gt} 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 us(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 ds(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 T(["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 T(`ora closed the tunnel connection (${d??"?"} ${m??""})`)))};s.addEventListener("open",a),s.addEventListener("error",c),s.addEventListener("close",l)})}function ps(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===os&&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 ms=new Set(["host","connection","keep-alive","transfer-encoding","upgrade","te"]);function hs(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:fs(n.headers)},i=>r({status:i.statusCode??502,headers:ys(i),body:i}));s.on("error",o),gs(n.body,s).catch(i=>{s.destroy(i instanceof Error?i:new Error(String(i))),o(i)})})}}async function gs(e,t){try{for await(let n of e)t.write(n)||await(0,Pn.once)(t,"drain")}finally{t.end()}}function fs(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!ms.has(t.toLowerCase())))}function ys(e){let t={};for(let[n,r]of Object.entries(e.headers))r!==void 0&&(t[n]=r);return t}var yt=B(D(),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 ws=80,De,wt=0,ke="";function bs(){let e=yt.default.cyan(pe[wt%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} ${yt.default.dim(n)}`),wt++}var R={start(e){R.stop(),wt=0,ke=e,process.stderr.isTTY&&(De=setInterval(bs,ws))},update(e){ke=e},stop(){De&&(clearInterval(De),De=void 0,process.stderr.write("\r\x1B[K"))}};var E={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 Nn(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 vs(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 Ss(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 xs(e){let t=e?.mcpUrl;return typeof t=="string"&&t?t:void 0}async function Ln(e){let t=vs(e.url);if(!t)return console.error(`Not a scannable URL or domain: ${JSON.stringify(e.url)}`),E.USAGE;let n=Nn(e.minScore,"--min-score",0,100),r=Nn(e.maxAge,"--max-age",0,86400);for(let h of[n,r])if(h.error)return console.error(h.error),E.USAGE;let o=Ss(e);if("error"in o)return console.error(o.error),E.USAGE;let s=o.kind!=="none";if(!s&&ut(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 7 days)."].join(`
|
|
28
|
-
`)),E.USAGE;if(o.kind==="ora"&&!process.env.ORA_API_KEY)return console.error(ft),E.USAGE;let i=!e.json;i&&R.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&&R.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 R.stop(),process.removeListener("SIGINT",d),process.removeListener("SIGTERM",d),console.error(h instanceof Error?h.message:String(h)),E.USAGE}m=a.url}let g;try{let h=tn(m,{progress:i?p=>R.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(R.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(bt.default.yellow(` ${ct}`));let p=xs(h.payload);p&&console.log(bt.default.dim(` MCP endpoint: ${p}`)),console.log("")}return n.value!==void 0&&process.stderr.write(Mn),E.OK}return console.error(`Audit failed: ${h instanceof Error?h.message:String(h)}`),h instanceof j?E.API:E.USAGE}finally{await u(),process.removeListener("SIGINT",d),process.removeListener("SIGTERM",d)}R.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),E.OK;if(f.score<n.value)return e.json||console.log(` Score ${f.score} is below the required minimum ${n.value}
|
|
31
|
-
`),E.BELOW_MIN_SCORE}return E.OK}var b=B(D(),1);var As="https://ora.ai",ks=12e4,Es=5e3,Rs=180,$s=15*6e4,Ts=6e4,_s=5,Cs=2e3,_=class extends Error{},Ee=class extends _{constructor(n,r,o){super(n);this.status=r;this.retryAfterMs=o}status;retryAfterMs};function vt(e){return(e??process.env.ORA_API_URL??As).replace(/\/+$/,"")}async function St(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 _(`ora request failed: ${r}`)}if(!t.ok)throw new _(`ora request failed: ${await ce(t)}`);return await t.json()}function Un(e){return St(`${vt(e)}/api/journey/intents`)}function Wn(e){return St(`${vt(e)}/api/journey/agents`)}function Ps(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 Os(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 _(`ora journey request failed: ${a}`)}if(o.status===401)throw new _("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 _(`ora journey caller limit exceeded${i?` \u2014 retry after ${xt(Number(i)*1e3)}`:""} (${a})`)}if(o.status===503)throw new _("ora's run engine is unavailable right now \u2014 try again shortly");if(!o.ok)throw new _(`ora journey request failed: ${await ce(o)}`);let s=await o.json();return be(s.contractVersion),{record:s,cached:s.rate_limited===!0,allowance:Ps(o)}}function xt(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 Is(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 Ms(e,t,n){let r=t.startsWith("http")?t:`${e}${t}`,o=n.idleMs??ks,s=z(o),i=()=>new _(`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 _(`ora journey stream failed: ${m}`)}if(!a.ok||!a.body){s.disarm();let d=Number(a.headers.get("retry-after"));throw new Ee(`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(`
|
|
21
|
+
`);for(;m!==-1;){let h=vi(u.slice(0,m));if(u=u.slice(m+2),m=u.indexOf(`
|
|
33
22
|
|
|
34
|
-
`);
|
|
35
|
-
|
|
36
|
-
`)
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
`)}`),q.USAGE;let L=p.intents.find(ae=>ae.id===s);a=(L?.template||L?.hint||L?.label||s||"journey").replace(/\{domain\}/g,t)}let C=y.agents.some(L=>L.harness==="claude-agent-sdk"&&/haiku/i.test(L.model))?y.agents:[Js,...y.agents],Re=C.find(L=>L.harness==="claude-agent-sdk"&&/haiku/i.test(L.model))?.id??y.defaultId,$e=e.agent??Re,Wt=C.find(L=>L.id===$e);if(!Wt)return console.error(`ax deep-journey: unknown agent "${$e}". Available agents:
|
|
40
|
-
${
|
|
41
|
-
|
|
42
|
-
`}
|
|
43
|
-
`):
|
|
44
|
-
`),
|
|
45
|
-
`)
|
|
46
|
-
`)
|
|
47
|
-
`)
|
|
23
|
+
`),!h)continue;let g;try{g=JSON.parse(h)}catch{continue}let f=a(g);if(f&&n.progress?.(f),g.type==="error")throw new q(`ora audit failed: ${typeof g.message=="string"?g.message:"scan error"}`,{code:typeof g.code=="string"?g.code:null,payload:g});if(g.type==="scan_complete"&&g.result?l=g.result:g.type==="summary_ready"&&typeof g.agenticSummary=="string"&&(p=g.agenticSummary),l&&p)break e}}}catch(d){if(o.tripped())throw s();if(d instanceof q)throw d;let m=d instanceof Error?d.message:String(d);throw new q(`ora audit stream error: ${m}`)}finally{o.disarm(),i.body.cancel().catch(()=>{})}if(!l)throw new q("ora audit stream ended before completing");return{result:l,verdict:p}}function vi(e){let t=[];for(let n of e.split(`
|
|
24
|
+
`))n.startsWith("data:")&&t.push(n.slice(5).replace(/^ /,""));return t.join(`
|
|
25
|
+
`)}function Ai(){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(Kt,Math.max(0,Math.round(o/e*Kt)));return`${`${"\u2588".repeat(s)}${"\u2591".repeat(Kt-s)}`} ${o}/${e}${n?` \xB7 ${n}`:""}`}case"scan_complete":return"Finishing up\u2026";default:return}}}function ur(e){return e.analysisStatus==="complete"||e.analysisStatus==="stuck"?!1:e.analysisStatus==="partial"?!0:(e.pendingChecks?.length??0)>0}async function xi(e,t,n){let r=`${e}/api/score/${encodeURIComponent(t.domain)}?format=audit`,o=n.pollEveryMs??gi,s=n.pollLimit??yi,i=t;for(let a=0;a<s&&ur(i);a++){let c=i.pendingChecks?.length??0;n.progress?.(c?`Analyzing\u2026 ${c} check${c===1?"":"s"} pending`:"Analyzing\u2026"),await pe(o);try{let u=await fetch(r,{headers:{accept:"application/json",...cr(n.apiKey)},signal:AbortSignal.timeout(15e3)});u.ok&&(i=await u.json())}catch{}}return i}function me(e,t){let n=process.stdout.columns??100;return Math.min(t,Math.max(e,n))}function be(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function G(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 Ce=["\u25C7","\u25C7","\u25C8","\u25C8","\u25C6","\u25C6","\u25C8","\u25C8"];function N(e){return e.replace(/[\u0000-\u001f\u007f-\u009f]/g," ")}function dr(e){return e.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g," ")}function C(e){return{placeholder:e}}var Ei=/^[A-Za-z0-9_@%+=:,./-]+$/;function he(e){return Ei.test(e)?e:`'${e.replaceAll("'","'\\''")}'`}function w(e){return["ax",...e.map(n=>typeof n=="string"?he(n):`<${n.placeholder}>`)].join(" ")}function Ri(e){return e.method!=="GET"||!/^https?:\/\//.test(e.url)?!1:!new URL(e.url).pathname.startsWith("/api/")}function _i(e,t){let n=/^https?:\/\//.test(e.url)?e.url:`${t}${e.url}`;if(e.method==="GET")return`curl -s ${he(n)}`;let r=e.body?` -H ${he("content-type: application/json")} -d ${he(JSON.stringify(e.body))}`:"";return`curl -s -X ${he(e.method)} ${he(n)}${r}`}function mr(e,t){let n=t.axEquivalent;if(Ri(e))return t.pageCall?{call:t.pageCall,why:`${e.reason} ${e.url}`}:{call:e.url,why:e.reason};let r=n&&e.method===n.method&&e.url===n.url?n.call:_i(e,t.base),o=e.wait_seconds;return{call:`${Number.isInteger(o)&&(o??0)>0?`sleep ${o} && `:""}${r}`,why:e.reason}}function pr(e){let t=e.why?`Next: ${e.call} # ${e.why}`:`Next: ${e.call}`;return N(t)}function T(e,t){t.stderr?console.error(pr(e)):console.log(pr(e))}function ki(e){return{error:{code:e.code,message:e.message,next:e.next.call}}}function j(e,t){let n=dr(e.message);if(console.error(t.display?t.display(n):n),T(e.next,{stderr:!0}),!t.json)return;let r=t.served===void 0||t.served===null?ki(e):t.served;process.stdout.write(`${JSON.stringify(r,null,2)}
|
|
26
|
+
`)}function Ti(e,t){let n=t.filter(o=>!o.skipped),r=t.filter(o=>o.unverified).length;return{name:e,checks:t,passed:n.filter(o=>o.passed).length,total:n.length,skipped:t.length-n.length-r,unverified:r}}function $i(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),e.status==="na"&&e.naKind==="unverified"&&(r.unverified=!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 hr(e,t){let{result:n}=e,r=(n.layers??[]).map(i=>Ti(i.name,(i.checks??[]).map($i))),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 E=V(Y(),1),Yt="\u26A0 MCP handshake requires credentials \u2014 target is unscored",Ci=" (0/F means could not evaluate, not failed everything)",Pi=80,Ii=120,lt=10;function Oi(){return Math.min(Ii,Math.max(Pi,process.stdout.columns??100))}function Xt(e,t){return e.length<t?e+" ".repeat(t-e.length):e}function fr(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 ut(e,t){let n=(i,a,c)=>E.default.dim(i+e.map(u=>"\u2500".repeat(u.width+2)).join(a)+c),r=E.default.dim("\u2502"),o=(i,a)=>{let c=i.map((p,d)=>fr(typeof p=="string"?p:p[0],e[d].width)),u=Math.max(1,...c.map(p=>p.length)),l=[];for(let p=0;p<u;p++){let d=c.map((m,h)=>{let g=Xt(m[p]??"",e[h].width),f=a??(typeof i[h]=="string"?e[h].paint:i[h][1]);return` ${f?f(g):g} `});l.push(r+d.join(r)+r)}return l},s=[n("\u250C","\u252C","\u2510")];return s.push(...o(e.map(i=>i.title),E.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 Mi(e,t){let r=Math.max(46,e-4-13),o=14,s=Math.min(26,Math.max(5,...t.map(u=>u.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:E.default.bold},{title:"What's wrong",width:a},{title:"How to fix",width:c,paint:E.default.cyan}]}function qt(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 Ni(e,t){if(t<=0)return E.default.dim("\u2500".repeat(lt));let n=Math.min(lt,Math.max(0,Math.round(e/t*lt)));return E.default.green("\u2588".repeat(n))+E.default.dim("\u2591".repeat(lt-n))}function Li(e,t,n,r){let o=[""],s=e.total>0?`${e.passed}/${e.total} passed`:"no applicable checks",i=e.unverified>0?` \xB7 ${e.unverified} couldn't verify`:"",a=e.skipped>0?` \xB7 ${e.skipped} skipped`:"";o.push(` ${E.default.bold(Xt(e.name,n))} ${Ni(e.passed,e.total)} ${E.default.dim(s+i+a)}`);let c=e.checks.filter(l=>!l.passed&&!l.skipped);if(c.length){o.push(` ${E.default.red("\u2717")} ${E.default.bold(`Issues (${c.length})`)}`);let l=ut(Mi(t,c.map(d=>d.name)),c.map(d=>[d.status==="warning"?["\u26A0",E.default.yellow]:["\u2717",E.default.red],d.name,[d.detail??"",m=>m],d.hint??""]));o.push(...l.map(d=>` ${d}`));let p=c.filter(d=>d.specUrl);for(let d of p)o.push(E.default.dim(` \u21B3 ${d.id} spec: ${d.specUrl}`))}let u=e.checks.filter(l=>l.unverified);if(u.length){o.push(` ${E.default.yellow("?")} ${E.default.bold(`Couldn't verify (${u.length})`)}`);let l=ut(qt(t,u.map(p=>p.name),["Check","What happened"]),u.map(p=>[p.name,p.detail??""]));o.push(...l.map(p=>` ${p}`))}if(r.showPassing){let l=e.checks.filter(p=>p.passed&&!p.skipped);if(l.length){o.push(` ${E.default.green("\u2713")} ${E.default.bold(`Passed (${l.length})`)}`);let p=ut(qt(t,l.map(d=>d.name),["Check","Details"]),l.map(d=>[d.name,d.detail??""]));o.push(...p.map(d=>` ${d}`))}}if(r.showSkipped){let l=e.checks.filter(p=>p.skipped&&!p.unverified);if(l.length){o.push(` ${E.default.dim(`\u25CB Skipped (${l.length})`)}`);let p=ut(qt(t,l.map(d=>d.name),["Check","Reason"],E.default.dim),l.map(d=>[d.name,d.detail??""]));o.push(...p.map(d=>` ${d}`))}}return o}function ji(e){if(!e.topFixes.length)return[];let t=["",` ${E.default.bold("Top fixes")} ${E.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"?E.default.green(`\u2248 +${r.estScoreGain} pts`):E.default.dim("\u2014"),i=r.bonus?E.default.dim(" (bonus)"):"";t.push(` ${o+1}. ${E.default.bold(Xt(r.id,n))} ${s}${i}`)}),t}function Ui(e){return e<90?`${e}s`:e<5400?`${Math.round(e/60)} min`:`${Math.round(e/3600)}h`}function gr(e,t={}){let n=Oi(),r=e.sections.reduce((u,l)=>Math.max(u,l.name.length),0),o=[""],s=e.score>=70?E.default.green:e.score>=50?E.default.yellow:E.default.red;if(o.push(` ${E.default.bold(e.target)} ${s(E.default.bold(`${e.score}/100 ${e.grade}`))}`),t.tunnel&&o.push(E.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(E.default.yellow(` ${Yt}${Ci}`)),e.summary)for(let u of fr(e.summary,n-4))o.push(` ${E.default.dim(u)}`);for(let u of e.sections)o.push(...Li(u,n,r,t));o.push(...ji(e));let i=e.sections.reduce((u,l)=>u+l.passed,0),a=e.sections.reduce((u,l)=>u+l.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 (${Ui(e.cacheAgeSeconds)} old) \xB7 pass --force for a fresh scan`),e.reportUrl&&c.push(` Full report: ${e.reportUrl}`),c.length){o.push("");for(let u of c)o.push(E.default.dim(u))}return o.push(""),o}var yr=require("child_process"),O=class extends Error{payload;constructor(t,n={}){super(t),this.payload=n.payload}},Di=3e4,wr=9e4,Fi=1e4;function Je(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 Wi(e){for(let t of e.matchAll(/https:\/\/[^\s"'|]+/g))try{let n=new URL(t[0]);if(n.pathname==="/"&&!n.search&&!Je(n.hostname))return n.origin}catch{}}async function br(e,t=Di){let n=await Bi(e,t);try{await Vt(n.url,wr)}catch(r){throw n.close(),r}return n}async function Vt(e,t=wr,n=5e3,r){let o=Date.now()+t;for(;Date.now()<o;){if(r?.aborted)throw new O("interrupted while waiting for the tunnel");try{if((await fetch(e,{redirect:"manual",signal:AbortSignal.timeout(Fi)})).status<500)return}catch{}await new Promise(s=>setTimeout(s,n))}throw new O([`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(`
|
|
27
|
+
`))}function Bi(e,t){return new Promise((n,r)=>{let o=process.platform!=="win32",s=(0,yr.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{}},u=p=>{i||(i=!0,clearTimeout(l),c(),r(p))},l=setTimeout(()=>u(new O(`tunnel command did not print a public https URL within ${Math.round(t/1e3)}s: ${e}`)),t);s.on("error",p=>u(new O(p.message))),s.on("exit",p=>{let d=a.trim()?`
|
|
28
|
+
output: ${a.trim().slice(-300)}`:"";u(new O(`tunnel command exited before printing a public https URL (code ${p??"unknown"}): ${e}${d}`))});for(let p of[s.stdout,s.stderr])p?.setEncoding("utf8"),p?.on("data",d=>{a=(a+d).slice(-2e3);let m=Wi(a);m&&!i&&(i=!0,clearTimeout(l),s.removeAllListeners("exit"),n({url:m,close:c}))})})}var jr=require("crypto"),Ur=require("events"),Dr=require("http");var $=class extends Error{constructor(n,r){super(r);this.code=n;this.name="ProtocolError"}code},R={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 Sr(e,t){return e.safeParse(t)}var X=class extends Error{};function ve(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new X(`${t}: expected object`);return e}function Se(e,t,n=0,r=Number.POSITIVE_INFINITY){if(typeof e!="string")throw new X(`${t}: expected string`);if(e.length<n)throw new X(`${t}: expected at least ${n} characters`);if(e.length>r)throw new X(`${t}: expected at most ${r} characters`);return e}function Pe(e,t,n,r=Number.POSITIVE_INFINITY){if(typeof e!="number"||!Number.isInteger(e))throw new X(`${t}: expected integer`);if(e<n||e>r)throw new X(`${t}: expected ${n}..${r}`);return e}function vr(e,t){if(e===void 0)return{};let n={};for(let[r,o]of Object.entries(ve(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 X(`${t}.${r}: expected string or string[]`);return n}function Ie(e){return{safeParse(t){try{return{success:!0,data:e(t)}}catch(n){if(n instanceof X)return{success:!1,error:{message:n.message}};throw n}}}}function Ar(e,t){let n=ve(e,t);if(n.protocol!=="http")throw new X(`${t}.protocol: expected "http"`);return{protocol:"http",host:Se(n.host,`${t}.host`,1),port:Pe(n.port,`${t}.port`,1,65535)}}var Du=Ie(e=>Ar(e,"target")),Fu=Ie(e=>{let t=ve(e,"hello");return{agentVersion:Se(t.agentVersion,"hello.agentVersion",1,64),target:Ar(t.target,"hello.target"),maxStreams:t.maxStreams===void 0?32:Pe(t.maxStreams,"hello.maxStreams",1,256)}}),xr=Ie(e=>{let t=ve(e,"helloAck");return{tunnelId:Se(t.tunnelId,"helloAck.tunnelId",1),heartbeatMs:Pe(t.heartbeatMs,"helloAck.heartbeatMs",1),maxStreams:Pe(t.maxStreams,"helloAck.maxStreams",1),maxFrame:Pe(t.maxFrame,"helloAck.maxFrame",1)}}),Er=Ie(e=>{let t=ve(e,"open"),n=Se(t.path,"open.path");if(!n.startsWith("/"))throw new X('open.path: expected a path starting with "/"');let r={method:Se(t.method,"open.method",1,16),path:n,headers:vr(t.headers,"open.headers")};if(t.hasBody!==void 0){if(typeof t.hasBody!="boolean")throw new X("open.hasBody: expected boolean");r.hasBody=t.hasBody}return r}),Rr=Ie(e=>{let t=ve(e,"responseHeaders");return{status:Pe(t.status,"responseHeaders.status",100,599),headers:vr(t.headers,"responseHeaders.headers")}});function _r(e){return Ie(t=>{let n=ve(t,e);return{code:Se(n.code,`${e}.code`,1,64),message:n.message===void 0?"":Se(n.message,`${e}.message`,0,1024)}})}var kr=_r("reset"),Tr=_r("goaway");var Ae=9,He=64*1024,xe=0,Oe=(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))(Oe||{}),Ji=new Set(Object.values(Oe).filter(e=>typeof e=="number"));function $r(e,t=He){if(e.payload.byteLength>t)throw new $(R.frameTooLarge,`frame payload ${e.payload.byteLength} exceeds max ${t}`);let n=new Uint8Array(Ae+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,Ae),n}function Cr(e,t=He){if(e.byteLength<Ae)throw new $(R.frameTooShort,`frame is ${e.byteLength} bytes, header alone is ${Ae}`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=n.getUint8(0);if(!Ji.has(r))throw new $(R.unknownFrameType,`unknown frame type 0x${r.toString(16)}`);let o=n.getUint32(1,!1),s=n.getUint32(5,!1);if(s>t)throw new $(R.frameTooLarge,`declared payload ${s} exceeds max ${t}`);if(e.byteLength!==Ae+s)throw new $(R.frameLengthMismatch,`declared payload ${s} but message carries ${e.byteLength-Ae}`);return{type:r,streamId:o,payload:e.subarray(Ae)}}var Ir="ora-tunnel.v1",Pr=He,Hi=new TextEncoder,Gi=new TextDecoder,Ge=class{constructor(t=He){this.maxFrame=t}maxFrame;subprotocol=Ir;encode(t){return $r(t,this.capFor(t.type))}decode(t){let n=Cr(t,Math.max(this.maxFrame,Pr)),r=this.capFor(n.type);if(n.payload.byteLength>r)throw new $(R.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:Hi.encode(JSON.stringify(r))})}decodeJson(t,n){let r;try{r=JSON.parse(Gi.decode(t.payload))}catch{throw new $(R.badJson,"frame payload is not valid JSON")}let o=Sr(n,r);if(!o.success)throw new $(R.badPayload,o.error.message);return o.data}capFor(t){return t===18?this.maxFrame:Pr}};var Or=1e4;function Mr(e,t,n,r,o){return new Promise((s,i)=>{let a=!1,c=l=>{a||(a=!0,clearTimeout(u),l())},u=setTimeout(()=>{c(()=>{e.close(1002,R.handshakeTimeout),i(new $(R.handshakeTimeout,`no handshake frame within ${o}ms`))})},o);u.unref?.(),e.onError(l=>c(()=>i(l))),e.onClose((l,p)=>c(()=>i(new $(R.connectionClosed,`connection closed during handshake (${l}${p?`: ${p}`:""})`)))),e.onMessage(l=>{c(()=>{try{let p=t.decode(l);if(p.streamId!==xe||p.type!==n)throw new $(R.handshakeProtocol,`expected handshake frame 0x${n.toString(16)}, got 0x${p.type.toString(16)} on stream ${p.streamId}`);s(t.decodeJson(p,r))}catch(p){e.close(1002,R.handshakeProtocol),i(p)}})})})}var dt=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,Rr));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,kr);this.resetPayload=n,this.notifyReset(n);return}default:throw new $(R.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 $(R.streamReset,`${t.code}: ${t.message}`)),this.handlers.onReset?.(t),this.onFinalized(this)}assertWritable(){if(this.resetPayload)throw new $(R.streamReset,`stream ${this.id} was reset (${this.resetPayload.code})`);if(this.localEnded)throw new $(R.streamClosed,`stream ${this.id} already ended locally`)}maybeFinalize(){this.localEnded&&this.remoteEnded&&this.onFinalized(this)}};var pt=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 $(R.connectionClosed,`connection closed (${t}${n?`: ${n}`:""})`))),this.socket.onError(t=>this.teardown(new $(R.connectionClosed,t.message)))}get activeStreamCount(){return this.streams.size}openStream(t){if(this.closed||this.goingAway)throw new $(R.connectionClosed,"connection is closed or draining");if(this.streams.size>=this.opts.maxStreams)throw new $(R.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,xe,{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 $){this.goaway(r.code,r.message),this.close(1002,r.code),this.teardown(r);return}throw r}}dispatch(t){if(t.streamId===xe){t.type===32&&(this.goingAway=!0,this.opts.onGoaway?.(this.opts.codec.decodeJson(t,Tr)));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:R.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:R.badPayload,message:"this side does not accept streams"}));return}if(this.goingAway)return;let n=this.opts.codec.decodeJson(t,Er);if(this.streams.size>=this.opts.maxStreams){this.socket.send(this.opts.codec.encodeJson(20,t.streamId,{code:R.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 dt(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 mt=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 Nr(e){let t=new mt;return e.setHandlers({onData:n=>t.push(Uint8Array.from(n)),onEnd:()=>t.end(),onReset:n=>t.fail(new $(R.streamReset,`${n.code}: ${n.message}`))}),t}async function Lr(e,t){try{for await(let n of t)e.sendData(n);e.sendEnd()}catch(n){throw e.sendReset(R.forwardError,n instanceof Error?n.message:String(n)),n}}var Ke=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=Mr(t,n,2,xr,this.opts.handshakeTimeoutMs??Or);t.send(n.encodeJson(1,xe,r));let s=await o;return this.mux=new pt(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:Nr(t),hasBody:n.hasBody,signal:t.signal});t.sendHeaders({status:r.status,headers:r.headers}),await Lr(t,r.body)}catch(r){try{t.sendReset(R.forwardError,r instanceof Error?r.message:String(r))}catch{}}}};var Zt="tunnels:write + tunnels:connect",Qt=[`--tunnel ora needs ORA_API_KEY: an ora platform key (ora_sk_...) with the ${Zt} 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(`
|
|
29
|
+
`),Ki=1,qi=32,zt=()=>new O("interrupted before the tunnel was ready");function Yi(e){let t;try{t=new URL(e.includes("://")?e:`http://${e}`)}catch{throw new O(`not a local target: ${JSON.stringify(e)}`)}if(t.protocol!=="http:")throw new O(`--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 Fr(e,t={}){let n=Yi(e),r=t.apiKey??process.env.ORA_API_KEY;if(!r)throw new O(Qt);let o=it(t.platformUrl),s;try{s=await at(o,r)}catch(S){throw new O(`${S instanceof Error?S.message:String(S)}
|
|
30
|
+
(--tunnel ora needs a platform key with the ${Zt} scopes)`,{payload:S instanceof re?S.payload:void 0})}if(t.signal?.aborted)throw zt();let i=await Vi(o,s),a=()=>Zi(o,s,i.id,()=>at(o,r)),c,u,l=!1,p=()=>{},d=new Promise(S=>{p=S}),m=new Promise((S,b)=>{t.signal?.aborted&&b(zt()),t.signal?.addEventListener("abort",()=>b(zt()),{once:!0})}),h;try{h=Xi(i),c=await Promise.race([Qi(h,s),m]),u=new Ke({socket:ea(c),codec:new Ge,hello:{agentVersion:`ax/${Fe.version}`,target:{protocol:"http",host:n.host,port:n.port},maxStreams:qi},forwarder:na(n.host,n.port),onConnectionClosed:S=>{l||p(new O(`ora tunnel connection dropped: ${S.message}`))}}),await Promise.race([u.start(),m]),await Vt(h.publicUrl,t.routableMs,t.probeEveryMs,t.signal)}catch(S){l=!0;try{u?u.close(1e3,"ax setup failed"):c?.close()}catch{}throw await a(),S}let g=u,f,y=()=>(f||(l=!0,f=(async()=>{try{g.close(1e3,"ax exit")}catch{}await a()})()),f);return{url:h.publicUrl,close:y,dropped:d}}function Xi(e){if(!e.publicUrl||!e.connection?.url||!e.connection.subprotocol)throw new O("ora created a tunnel but returned no public URL to connect to");if(e.connection.kind!=="ora-ws")throw new O(`ora returned a "${e.connection.kind}" tunnel, which this version of ax cannot connect; upgrade ax`);return e}async function Vi(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,jr.randomBytes)(4).toString("hex")}`,access:"public"})}),r=await n.text(),o={},s;try{o=JSON.parse(r),s=o}catch{}if(!n.ok){let i=o.error??o.message??r.trim().slice(0,200);throw new O(`${zi(n.status)}${i?`: ${i}`:""}`,{payload:s})}if(!o.id)throw new O("ora created a tunnel but returned no id");return o}function zi(e){switch(e){case 401:return"ora rejected the platform key (401). Check ORA_API_KEY";case 403:return`the platform key lacks the ${Zt} 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 Zi(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 Qi(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=l=>{s.removeEventListener("open",a),s.removeEventListener("error",c),s.removeEventListener("close",u),l()},a=()=>i(()=>r(s)),c=()=>i(()=>o(new O(["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(`
|
|
31
|
+
`)))),u=l=>{let{code:p,reason:d}=l;i(()=>o(new O(`ora closed the tunnel connection (${p??"?"} ${d??""})`)))};s.addEventListener("open",a),s.addEventListener("error",c),s.addEventListener("close",u)})}function ea(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===Ki&&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 ta=new Set(["host","connection","keep-alive","transfer-encoding","upgrade","te"]);function na(e,t){return{forward:n=>new Promise((r,o)=>{let s=(0,Dr.request)({host:e,port:t,path:n.path,method:n.method,headers:oa(n.headers)},i=>r({status:i.statusCode??502,headers:sa(i),body:i}));s.on("error",o),ra(n.body,s).catch(i=>{s.destroy(i instanceof Error?i:new Error(String(i))),o(i)})})}}async function ra(e,t){try{for await(let n of e)t.write(n)||await(0,Ur.once)(t,"drain")}finally{t.end()}}function oa(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!ta.has(t.toLowerCase())))}function sa(e){let t={};for(let[n,r]of Object.entries(e.headers))r!==void 0&&(t[n]=r);return t}var en=V(Y(),1);var ia=80,ht,tn=0,qe="";function aa(){let e=en.default.cyan(Ce[tn%Ce.length]),t=Math.max(10,(process.stderr.columns??80)-2),n=qe.length>t?`${qe.slice(0,t-1)}\u2026`:qe;process.stderr.write(`\r\x1B[K${e} ${en.default.dim(n)}`),tn++}var I={start(e){I.stop(),tn=0,qe=e,process.stderr.isTTY&&(ht=setInterval(aa,ia))},update(e){qe=e},stop(){ht&&(clearInterval(ht),ht=void 0,process.stderr.write("\r\x1B[K"))}};var _={OK:0,BELOW_MIN_SCORE:1,USAGE:2,API:3},Wr=`--min-score skipped: the MCP handshake requires credentials, so the target is unscored
|
|
32
|
+
`;function Br(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 ca(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 la(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 ua(e){let t=e?.mcpUrl;return typeof t=="string"&&t?t:void 0}function rn(e){let t=e.tunnelCmd?.trim();return t?["--tunnel-cmd",t]:e.tunnel?.trim()==="ora"?["--tunnel","ora"]:[]}function Jr(e){return e.apiKey?.trim()?["--api-key",C("key")]:[]}function fe(e){return e.json?["--json"]:[]}function Hr(e,t,n){let r=new URL(t.includes("://")?t:`https://${t}`),o=r.host.replace(/^mcp\./,""),s=r.pathname.replace(/\/+$/,"")==="",i="ora cannot inspect an MCP server that needs credentials; score the site that serves it";return s&&o===r.host?{call:w(["audit",C("site domain"),...fe(e)]),why:i}:{call:w(["audit",o,...fe(e),...n?rn(e):[]]),why:i}}function da(e,t,n,r,o){if(n.mcpAuthRequired)return Hr(e,t,o);let s=["audit",t,...fe(e),...o?rn(e):["--force"],...r!==void 0?["--min-score",String(r)]:[],...Jr(e)],i=!n.urlKind||n.urlKind==="domain";return o||!i||r!==void 0&&n.score<r?{call:w(s),why:"after you apply the Top fixes above, rescan"}:{call:w(["journey","--domain",n.domain,...fe(e)]),why:"send a real agent at the site on a task, then read its result"}}async function Gr(e){let t=(b,D,te,L)=>(j(b,{json:e.json,display:te,served:L}),D),n=ca(e.url);if(!n)return t({code:"INVALID_TARGET",message:`Not a scannable URL or domain: ${JSON.stringify(e.url)}`,next:{call:w(["audit",C("domain"),...fe(e)]),why:"a public URL or domain, e.g. docs.example.com"}},_.USAGE);let r=Br(e.minScore,"--min-score",0,100),o=Br(e.maxAge,"--max-age",0,86400);for(let[b,D,te]of[["--min-score",r,"70"],["--max-age",o,"3600"]])if(D.error)return t({code:"INVALID_FLAG",message:D.error,next:{call:w(["audit",n,...fe(e),b,te])}},_.USAGE);let s=la(e),i=w(["audit",n,...fe(e),"--tunnel","ora"]);if("error"in s)return t({code:"INVALID_FLAG",message:s.error,next:{call:i}},_.USAGE);let a=s.kind!=="none";if(!a&&Je(n))return t({code:"LOCAL_TARGET",message:[`${n} 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 7 days)."].join(`
|
|
33
|
+
`),next:{call:i,why:"ora's own tunnel; needs ORA_API_KEY"}},_.USAGE);if(s.kind==="ora"&&!process.env.ORA_API_KEY)return t({code:"MISSING_API_KEY",message:Qt,next:{call:`ORA_API_KEY=<platform key> ${i}`,why:"a key with the tunnels:write + tunnels:connect scopes"}},_.USAGE);let c={call:w(["audit",n,...fe(e),...rn(e),...r.value!==void 0?["--min-score",String(r.value)]:[],...o.value!==void 0?["--max-age",String(o.value)]:[],...e.force?["--force"]:[],...Jr(e)]),why:"retry; if ora rate limited you, wait as long as the message says first"},u=!e.json;u&&I.start(`Auditing ${n} with ora`);let l,p,d=new AbortController,m=async()=>{await l?.close()},h=b=>{process.removeListener("SIGINT",h),process.removeListener("SIGTERM",h),d.abort(),(async()=>{await p?.catch(()=>{}),await m()})().finally(()=>process.exit(b==="SIGINT"?130:143))},g=n;if(s.kind!=="none"){u&&I.update(`Opening a tunnel to ${n}`),process.on("SIGINT",h),process.on("SIGTERM",h);try{p=s.kind==="ora"?Fr(n,{signal:d.signal}):br(s.command),l=await p}catch(b){return I.stop(),process.removeListener("SIGINT",h),process.removeListener("SIGTERM",h),t({code:"TUNNEL_FAILED",message:b instanceof Error?b.message:String(b),next:{call:c.call,why:"retry, or bring your own tunnel with --tunnel-cmd"}},_.USAGE,void 0,b instanceof O?b.payload:void 0)}g=l.url}let f;try{let b=lr(g,{progress:u?D=>I.update(D):void 0,maxAgeSeconds:o.value,force:e.force,ephemeral:a||void 0,apiKey:e.apiKey?.trim()||void 0});f=l?.dropped?await Promise.race([b,l.dropped.then(D=>Promise.reject(D))]):await b}catch(b){if(I.stop(),ar(b)){let L=Hr(e,n,a);if(e.json){let le=b.payload===void 0?{code:b.code,message:b.message}:b.payload;process.stdout.write(`${JSON.stringify(le,null,2)}
|
|
34
|
+
`)}else{console.log(""),console.log(nn.default.yellow(` ${Yt}`));let le=ua(b.payload);le&&console.log(nn.default.dim(` MCP endpoint: ${le}`)),console.log("")}return r.value!==void 0&&process.stderr.write(Wr),T(L,{stderr:e.json}),_.OK}let D=b instanceof Error?b.message:String(b),te=b instanceof q;return t({code:te?b.code||"API_ERROR":"AUDIT_FAILED",message:D,next:c},te?_.API:_.USAGE,L=>`Audit failed: ${L}`,te?b.payload:void 0)}finally{await m(),process.removeListener("SIGINT",h),process.removeListener("SIGTERM",h)}I.stop();let{result:y}=f;if(e.json)process.stdout.write(`${JSON.stringify(y,null,2)}
|
|
35
|
+
`);else for(let b of gr(hr(f,n),{showSkipped:e.showSkipped,showPassing:e.showPassing,tunnel:a}))console.log(b);let S=da(e,n,y,r.value,a);if(r.value!==void 0){if(y.mcpAuthRequired)return process.stderr.write(Wr),T(S,{stderr:e.json}),_.OK;if(y.score<r.value)return e.json||console.log(` Score ${y.score} is below the required minimum ${r.value}
|
|
36
|
+
`),T(S,{stderr:e.json}),_.BELOW_MIN_SCORE}return T(S,{stderr:e.json}),_.OK}var x=V(Y(),1);var qr="https://ora.ai",on="/api/journey/runs",pa=12e4,ma=5e3,ha=180,fa=15*6e4,ga=6e4,ya=5,wa=2e3;function gt(e){if(!e||typeof e!="object")return;let t=e.next_action;if(!t||typeof t!="object")return;let{method:n,url:r,reason:o}=t;return(n==="GET"||n==="POST")&&typeof r=="string"&&typeof o=="string"?t:void 0}var P=class extends Error{code;runUrl;payload;nextAction;constructor(t,n={}){super(t),this.code=n.code??null,this.runUrl=n.runUrl,this.payload=n.payload,this.nextAction=n.nextAction??gt(n.payload)}},Ye=class extends P{constructor(n,r,o,s){super(n,{payload:s});this.status=r;this.retryAfterMs=o}status;retryAfterMs};function Xe(e){return(e??process.env.ORA_API_URL??qr).replace(/\/+$/,"")}async function sn(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 P(`ora request failed: ${r}`)}if(!t.ok){let{message:n,payload:r}=await J(t);throw new P(`ora request failed: ${n}`,{payload:r})}return await t.json()}function Yr(e){return sn(`${Xe(e)}/api/journey/intents`)}function Xr(e){return sn(`${Xe(e)}/api/journey/agents`)}function ba(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 Sa(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}${on}`,{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 P(`ora journey request failed: ${a}`)}if(o.status===401){let{payload:i}=await J(o);throw new P("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)",{code:"NEEDS_KEY",payload:i})}if(o.status===429){let i=await st(o),{payload:a}=await J(o);if(i)throw new P(`ora usage limit reached: ${i}`,{code:"USAGE_LIMIT_REACHED",payload:a});let c=o.headers.get("retry-after"),u=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 P(`ora journey caller limit exceeded${c?` \u2014 retry after ${an(Number(c)*1e3)}`:""} (${u})`,{code:"RATE_LIMITED",payload:a})}if(o.status===503){let{payload:i}=await J(o);throw new P("ora's run engine is unavailable right now \u2014 try again shortly",{code:"ENGINE_UNAVAILABLE",payload:i})}if(!o.ok){let{message:i,payload:a}=await J(o);throw new P(`ora journey request failed: ${i}`,{payload:a})}let s=await o.json();return Be(s.contractVersion),{record:s,cached:s.rate_limited===!0,allowance:ba(o)}}function an(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 va(e){if(!e)return"starting\u2026";if(e.type==="text")return"thinking\u2026";if(e.action==="search")return e.search_query?`searching \u201C${Kr(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} ${Kr(t,48)}`:`${n}\u2026`}function Kr(e,t){return e.length>t?`${e.slice(0,t-1)}\u2026`:e}async function Aa(e,t,n){let r=t.startsWith("http")?t:`${e}${t}`,o=n.idleMs??pa,s=de(o),i=()=>new P(`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(p){if(s.disarm(),s.tripped())throw i();let d=p instanceof Error?p.message:String(p);throw new P(`ora journey stream failed: ${d}`)}if(!a.ok||!a.body){s.disarm();let p=Number(a.headers.get("retry-after")),{message:d,payload:m}=await J(a);throw new Ye(`ora journey stream failed (${a.status}): ${d}`,a.status,Number.isFinite(p)&&p>0?p*1e3:void 0,m)}let c=new TextDecoder,u={},l="";try{e:for await(let p of a.body){s.poke(),l=`${l}${c.decode(p,{stream:!0})}`.replace(/\r\n?/g,`
|
|
37
|
+
`);let d=l.indexOf(`
|
|
38
|
+
|
|
39
|
+
`);for(;d!==-1;){let m=Bt(l.slice(0,d));if(l=l.slice(d+2),d=l.indexOf(`
|
|
40
|
+
|
|
41
|
+
`),!m)continue;let h;try{h=JSON.parse(m.data)}catch{continue}if(m.event==="trajectory"){let g=h.steps??[],f=g.filter(y=>y.type==="tool_call").at(-1);n.progress?.(`step ${g.length} \xB7 ${va(f??g.at(-1))}`),n.onTrajectory?.(g)}else if(m.event==="processing")n.progress?.(typeof h.message=="string"?h.message:"generating insights\u2026");else if(m.event==="result"){u.result=h;break e}else if(m.event==="error"){u.errorMessage=typeof h.message=="string"?h.message:"unknown engine error";break e}}}}catch(p){if(s.tripped())throw i();if(p instanceof P)throw p;let d=p instanceof Error?p.message:String(p);throw new P(`ora journey stream error: ${d}`)}finally{s.disarm(),a.body.cancel().catch(()=>{})}return u}async function xa(e,t,n,r){let o=n.reopenPauseMs??wa,s,i=0;for(let a=0;a<=ya&&Date.now()<r;a++){a>0&&(n.progress?.("stream dropped \u2014 reopening"),await pe(i)),i=o;try{let c=await Aa(e,t,n);if(c.result||c.errorMessage)return c.errorMessage;s=new P("ora journey stream closed before the run ended")}catch(c){if(s=c,c instanceof Ye){if(c.status!==429)throw c;i=Math.min(c.retryAfterMs??o,ga)}}}throw s??new P("ora journey stream was never opened")}function ft(e,t){return sn(`${e}/api/journey/runs/${encodeURIComponent(t)}`)}async function Ea(e,t,n,r){let o=n.pollEveryMs??ma,s=n.pollLimit??ha,i=await ft(e,t);for(let a=0;a<s&&i.status==="running"&&Date.now()<r;a++){n.progress?.("agent working\u2026 (polling)"),await pe(o);try{i=await ft(e,t)}catch{}}return i}async function Vr(e,t){let n=Xe(t.baseUrl);t={...t,apiKey:t.apiKey||process.env.ORA_PARTNER_API_KEY||process.env.ORA_SCAN_API_KEY||void 0},t.apiKey&&ue(n,"ORA_API_URL",qr);let r=await Sa(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??fa),u=t.noStream?{...t,onTrajectory:void 0}:t;try{s=await xa(n,o.stream_url,u,c)}catch(l){if(l instanceof Ye&&l.status!==429)throw l;i=l instanceof Error?l.message:String(l),t.progress?.(`stream unavailable (${i}) \u2014 polling`),await Ea(n,o.id,t,c)}}let a=await Ra(n,o.id,t);if(a.status==="running"){if(s)throw new P(`ora journey run failed: ${s}`);let c=`${n}/api/journey/runs/${o.id}`;throw new P(`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 ${c} shortly`,{code:"RUN_STILL_RUNNING",runUrl:c,nextAction:gt(a)})}return Be(a.contractVersion),{record:o,cached:r.cached,retryAfterMs:r.record.retry_after_ms,allowance:r.allowance,detail:a,engineError:s}}async function Ra(e,t,n){let r=await ft(e,t);for(let o=0;o<3&&r.status==="running";o++)n.progress?.("finalizing\u2026"),await pe(1500),r=await ft(e,t);return r}var U=V(Y(),1);function cn(e){if(!e)return{};let t=e.match(/https?:\/\/([^/\s]+)(\/\S*)?/i);return t?{host:t[1],path:t[2]??"/"}:{}}function Ee(e){return/search/i.test(`${e.tool??""} ${e.action??""}`)}function _a(e){if(Ee(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 ka(e,t){if(Ee(e)){let c=e.input_display??String(e.input?.query??"search"),u=e.output_structured?.links?.length;return{id:e.id,kind:"search",icon:"\u{1F50D}",label:be(`"${c}"`,t),meta:u?`${u} results`:void 0,tone:"ok",notes:[],children:[]}}let{host:n,path:r}=cn(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:_a(e),label:be(`${n??"?"}${r??""}`,t),meta:a,tone:s?"redirect":i?"error":"ok",notes:[],children:[]}}function yt(e,t,n){let r=me(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:be(t,s),tone:"root",notes:[],children:[]},a=new Map,c=[],u,l,p;for(let d of e){if(d.type==="text"&&d.kind==="reasoning"){let g=(d.thinking??d.text??"").trim();g&&c.push(be(g,s));continue}if(d.type!=="tool_call")continue;let m=ka(d,o);m.notes=c,c=[],a.set(d.id,m);let h=i;if(!Ee(d)){let g=d.attribution?.referrer?.step_id,f=d.attribution?.kind,y=g!=null?a.get(g):void 0;y&&y!==m?h=y:f==="web_search"&&u?h=u:f==="previous_artifact"&&l&&(h=l)}h.children.push(m),Ee(d)?u=m:l=m,p=m}return p&&!n&&(p.tone="active",p.meta="\u2026"),{root:i,looseNotes:c}}function wt(e){let t=e.filter(o=>o.kind==="reasoning").length,n=e.filter(o=>o.type==="tool_call"&&Ee(o)).length,r=[`${U.default.bold(String(e.length))} steps`];return t&&r.push(`${U.default.bold(String(t))} reasoning`),n&&r.push(`${U.default.bold(String(n))} search${n===1?"":"es"}`),r.join(U.default.dim(" \xB7 "))}function Ta(e){switch(e){case"root":return{frame:U.default.dim,ink:t=>U.default.bold(t)};case"active":return{frame:U.default.cyan,ink:t=>U.default.cyan(U.default.bold(t))};case"redirect":return{frame:U.default.yellow,ink:U.default.yellow};case"error":return{frame:U.default.red,ink:U.default.red};default:return{frame:U.default.green,ink:U.default.green}}}var zr=e=>U.default.dim(`(\u2026) ${e}`);function Zr(e,t){let{frame:n,ink:r}=Ta(e.tone),s=`${e.icon} ${e.label}${e.meta?` ${e.meta}`:""}`.length+2,i=`${e.icon} ${r(e.label)}${e.meta?` ${U.default.dim(e.meta)}`:""}`,a=e.children.length>0,c=e.notes.map(zr);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((u,l)=>{let p=l===e.children.length-1,d=Zr(u,!0),m=u.notes.length+1;d.forEach((h,g)=>{let f;g===m?f=p?" \u2570\u2500\u2500":" \u251C\u2500\u2500":g<m?f=" \u2502 ":f=p?" ":" \u2502 ",c.push(U.default.dim(f)+h)})}),c}function bt(e){let t=Zr(e.root,!1);return e.looseNotes.length&&(t.push(""),t.push(...e.looseNotes.map(zr))),t}var St=V(Y(),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=St.default.cyan(Ce[this.beat%Ce.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} ${St.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[St.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}
|
|
42
|
+
`;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 z={OK:0,RUN_FAILED:1,USAGE:2,API:3},$a="public caps: 100 runs/24h per target \xB7 20 runs/24h per IP",Ca="keyed caps: 1000 runs/24h per key \xB7 no per-target cap",Pa={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 Qr(e,t,n,r){if(e instanceof P&&e.nextAction)return r(e.nextAction);let o=e instanceof P?e.code:null;if(o==="RUN_STILL_RUNNING"&&e instanceof P&&e.runUrl)return{call:`curl -s ${he(e.runUrl)}`,why:"read the run; starting another one would not finish this one sooner"};switch(o){case"NEEDS_KEY":return{call:n,why:"ora did not recognise the key; partner keys come from ora"};case"RATE_LIMITED":case"USAGE_LIMIT_REACHED":return{call:t,why:"after the wait the message names"};case"ENGINE_UNAVAILABLE":return{call:t,why:"in about a minute"};default:return{call:t,why:"retry; ora may be briefly unreachable"}}}function Ia(e,t){if(t==="failed")return x.default.red("\u2717 run failed");switch(e){case"satisfied":return x.default.green("\u2713 task satisfied");case"partial":return x.default.yellow("\u25D0 partially satisfied");case"unsatisfied":return x.default.red("\u2717 task not satisfied");default:return x.default.dim("\xB7 not gradable")}}function ln(e){return`${e.label} \xB7 ${e.variant}`}function ro(e){return e?Object.entries(e).filter(([,t])=>t?.flagged).map(([t,n])=>`${x.default.yellow("!")} ${N(n.reason||t.replaceAll("_"," "))}`):[]}function eo(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 to(e,t,n){return[` ${wt(e)}`,"",...bt(yt(e,t,n)).map(r=>` ${r}`)]}var Oa=e=>e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e);function Ma(e){return e<.01?`$${e.toFixed(4)}`:e<1?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function Na(e){if(!e)return;let{input_tokens:t,output_tokens:n}=e;if(!(t==null&&n==null))return(t??0)+(n??0)}function La(e){return(e?.trajectory?.steps??[]).filter(t=>t.action==="search").length}function un(e,t,n){return e>=t?x.default.green:e>=n?x.default.yellow:x.default.red}function ja(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:un(s,70,40)})}if(t?.answer_efficiency!=null){let s=Math.round(t.answer_efficiency*100);o.push({label:"answer efficiency",pct:s,paint:un(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:un(i,70,35)})}return o}function Ua(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))}${x.default.dim("\u25B1".repeat(t-r))}`,s=`${e.pct}%`.padStart(4);return` ${x.default.dim(e.label.padEnd(n))} ${o} ${e.paint(x.default.bold(s))}`}function dn(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 Da(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=[],u=1;for(let d of e){i.push(dn(`${d.pct}%`,s,f=>d.paint(x.default.bold(f))));let m=s-2,h=Math.max(1,Math.min(m,Math.round(d.pct/100*m)));a.push(` ${d.paint("\u2594".repeat(h))}${x.default.dim("\u2594".repeat(m-h))} `);let g=G(d.label.toUpperCase(),s).map(f=>dn(f,s,x.default.dim));c.push(g),u=Math.max(u,g.length)}let l=d=>` ${d.join(" ".repeat(r))}`,p=["",l(i),l(a)];for(let d=0;d<u;d++)p.push(l(c.map(m=>m[d]??dn("",s,x.default.dim))));return p}function no(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=["",` ${x.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))),u=`${x.default.dim("\u25B0".repeat(c))}${x.default.dim("\u25B1".repeat(20-c))}`;s.push(` ${x.default.dim(i.label.padEnd(o))} ${u} ${x.default.dim(`${a}%`.padStart(4))}`)}return s}function Fa(e){return x.default.dim(` ${"\u2500".repeat(Math.min(e-4,52))}`)}function Wa(e,t){let n=e.run_signals,r=[];if(n?.reached_anchor!=null){let c=n.reached_anchor?x.default.green("\u2713 reached the site"):x.default.red("\u2717 never reached the site");r.push("",` ${c}`)}let o=ja(e);if(o.length){let c=Da(o,t);if(c)r.push(...c);else{r.push("");for(let u of o)r.push(Ua(u))}}let s=n?.answer_basis;s&&s.sections_total>0&&r.push(...no("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=l=>{let p=l.attribution?.kind;return p==="previous_step"||p==="previous_artifact"?"previous_artifact":p==="web_search"?"web_search":p==="prior_knowledge"&&l.anchor_relation==="exact"&&(!l.url_path||l.url_path==="/")?"task_input":"prior_knowledge"},u={};for(let l of a){let p=c(l);u[p]=(u[p]??0)+1}r.push(...no("url discovery",[{label:"given in the task",n:u.task_input??0},{label:"followed a link",n:u.previous_artifact??0},{label:"found via web search",n:u.web_search??0},{label:"guessed the URL",n:u.prior_knowledge??0}]))}return r}function Ba(e,t){let n=me(60,120),{detail:r}=e,o=r.result,s=["",Fa(n),""];s.push(` ${Ia(r.verdict,r.status)} ${x.default.dim("\xB7")} ${x.default.dim(r.domain??t)}`);let i=[];r.step_count!=null&&i.push(`${r.step_count} steps`);let a=o?.run_signals?.search_count??La(o);a&&i.push(`${a} search${a===1?"":"es"}`),o?.duration_ms!=null&&i.push(`${(o.duration_ms/1e3).toFixed(1)}s`);let c=Na(o);c!=null&&i.push(`${Oa(c)} tokens`),o?.cost_usd!=null&&i.push(Ma(o.cost_usd)),i.length&&s.push(` ${x.default.dim(i.join(" \xB7 "))}`);for(let l of ro(r.flags))s.push(` ${l}`);if(o&&s.push(...Wa(o,n)),o?.insight?.summary){s.push("");for(let l of G(N(o.insight.summary),n-4))s.push(` ${l}`)}let u=o?.insight?.key_observations??[];if(u.length){s.push("",` ${x.default.bold("Observations")}`);for(let l of u){let[p,...d]=G(N(l),n-6);s.push(` ${x.default.cyan("\xB7")} ${p}`);for(let m of d)s.push(` ${m}`)}}return r.status==="failed"&&s.push("",x.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(""),s}async function vt(e){let t=(v,F,je)=>{let ke=we=>`ax ${e.via??"deep-journey"}: ${we}`;return j(v,{json:e.json,display:we=>F===z.API?x.default.red(ke(we)):ke(we),served:je instanceof P?je.payload:void 0}),F},n=e.json?["--json"]:[],r=e.url.trim();if(!r)return t({code:"INVALID_TARGET",message:"a target URL or domain is required",next:{call:w(["journey","--domain",C("domain"),...n])}},z.USAGE);let o=!e.json&&process.stderr.isTTY,s=e.task?.trim()||void 0,i=e.apiKey||process.env.ORA_PARTNER_API_KEY||process.env.ORA_SCAN_API_KEY||void 0,a=(v,F)=>["journey",...s?[s]:[],"--domain",r,...!s&&v?["--intent",v]:[],...F?["--agent",F]:[],...n,...e.noStream?["--no-stream"]:[]],c=e.apiKey?["--api-key",C("key")]:[],u=(v,F)=>w([...a(v,F),...c]),l=(v,F)=>`ORA_PARTNER_API_KEY=<partner key> ${w(a(v,F))}`,p=Xe(),d=(v,F)=>je=>mr(je,{base:p,axEquivalent:{method:"POST",url:on,call:u(v,F)},pageCall:l(v,F)});if(s&&e.intent!==void 0)return t({code:"INVALID_FLAG",message:e.via==="journey"?"a goal of your own and --intent cannot be combined: --intent picks one of ora's curated tasks":"--task and --intent are mutually exclusive \u2014 a free-text task replaces the curated intent",next:{call:u(void 0,e.agent),why:"the task alone"}},z.USAGE);if(s&&!i)return t({code:"NEEDS_KEY",message:e.via==="journey"?"a goal of your own on ora's public journeys needs an ora partner API key (set ORA_PARTNER_API_KEY or pass --api-key); without --agent, --intent or --no-stream it runs on your Front account with ORA_API_KEY":"--task needs an ora partner API key \u2014 set ORA_PARTNER_API_KEY or pass --api-key (keys are issued by ora on request)",next:{call:l(void 0,e.agent),why:"or drop --task to run a curated task without a key"}},z.USAGE);let m=e.intent,h,g=s??"journey";try{let[v,F]=await Promise.all([s?void 0:Yr(),Xr()]);if(v){if(m===void 0)m=v.defaultId;else if(!v.intents.some(Te=>Te.id===m))return t({code:"UNKNOWN_INTENT",message:`unknown intent "${m}". Available intents:
|
|
43
|
+
${v.intents.map(Te=>` ${Te.id.padEnd(12)} ${Te.hint}`).join(`
|
|
44
|
+
`)}`,next:{call:u(v.defaultId,e.agent),why:"or any intent id listed above"}},z.USAGE);let K=v.intents.find(Te=>Te.id===m);g=(K?.template||K?.hint||K?.label||m||"journey").replace(/\{domain\}/g,r)}let ke=F.agents.some(K=>K.harness==="claude-agent-sdk"&&/haiku/i.test(K.model))?F.agents:[Pa,...F.agents],we=ke.find(K=>K.harness==="claude-agent-sdk"&&/haiku/i.test(K.model))?.id??F.defaultId,Ln=e.agent??we,jn=ke.find(K=>K.id===Ln);if(!jn)return t({code:"UNKNOWN_AGENT",message:`unknown agent "${Ln}". Available agents:
|
|
45
|
+
${ke.map(K=>` ${K.id.padEnd(12)} ${ln(K)}`).join(`
|
|
46
|
+
`)}`,next:{call:u(m,we),why:"or any agent id listed above"}},z.USAGE);h=jn}catch(v){return t({code:"API_ERROR",message:v instanceof Error?v.message:String(v),next:Qr(v,u(m,e.agent),l(m,e.agent),d(m,e.agent))},z.API,v)}e.json||console.error(x.default.dim(i?Ca:$a));let f=o&&!e.noStream,y=new Me,S=[],b=`waking ${h.label}`,D=()=>y.draw(to(S,g,!1),b);f?(console.log(),console.log(` ${x.default.cyan("\u25B6")} ${x.default.bold(r)} ${x.default.dim("\xB7")} ${x.default.dim(ln(h))} ${x.default.dim("\xB7")} ${x.default.dim(s?"custom task":m??"default")}`),console.log(),y.open(),D()):o&&I.start(`Sending ${ln(h)} to ${r} (${s?`"${s}"`:m})`);let te=v=>{f?(b=v,D()):o&&I.update(v)},L;try{L=await Vr(r,{intentId:s?void 0:m,task:s,apiKey:i,harness:h.harness,model:h.model,noStream:e.noStream,progress:o?te:void 0,onTrajectory:f?v=>{S=v.map(eo),D()}:void 0})}catch(v){return f?y.close():o&&I.stop(),t({code:v instanceof P&&v.code||"API_ERROR",message:v instanceof Error?v.message:String(v),next:Qr(v,u(m,h.id),l(m,h.id),d(m,h.id))},z.API,v)}f?y.close():o&&I.stop();let le=L.detail.status==="failed",On=gt(L.detail),Mn=On?d(m,h.id)(On):le?{call:u(m,h.id),why:"the run ended in an engine error; re-running is free to try"}:{call:w(["audit",r,...n]),why:"the readiness audit: which checks explain what the agent hit"};if(e.json){console.log(JSON.stringify(L.detail,null,2));for(let v of ro(L.detail.flags))console.error(v);return T(Mn,{stderr:!0}),le?z.RUN_FAILED:z.OK}L.cached?console.error(x.default.yellow(`This target hit its 24h cap \u2014 showing the most recent stored run${L.retryAfterMs?` (fresh run in ${an(L.retryAfterMs)})`:""}.`)):L.allowance.remaining!==void 0&&L.allowance.limit!==void 0&&console.error(x.default.dim(`allowance: ${L.allowance.remaining} of ${L.allowance.limit} target runs left in the 24h window`));let Nn=(L.detail.result?.trajectory?.steps??[]).map(eo);if(Nn.length){console.log();for(let v of to(Nn,g,!0))console.log(v)}for(let v of Ba(L,r))console.log(v);return T(Mn,{stderr:!1}),le?z.RUN_FAILED:z.OK}var Ne=require("fs"),ee=require("path"),Q=V(Y(),1);var Ja="https://ora.ai",Ha=3e4,Z=class extends Error{status;payload;constructor(t,n={}){super(t),this.name="AgentFilesApiError",this.status=n.status??null,this.payload=n.payload}},Ga=/^[a-z0-9._-]+$/;function Ka(e){if(!e.startsWith("/"))return!1;let t=e.slice(1).split("/");return t.length>=1&&t.length<=6&&t.every(n=>Ga.test(n)&&n!=="."&&n!=="..")}function oo(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t--;return e.slice(0,t)}function qa(e){return oo(e.trim().replace(/^https?:\/\//i,""))}async function so(e,t={}){let n=oo(t.baseUrl??process.env.ORA_API_URL??Ja),r=`${n}/api/agent-files/${encodeURIComponent(qa(e))}?include=all`,o;try{o=await fetch(r,{headers:{accept:"application/json"},signal:AbortSignal.timeout(Ha)})}catch(i){throw new Z(`could not reach ora at ${n}: ${i instanceof Error?i.message:String(i)}`)}if(!o.ok){let{message:i,payload:a}=await J(o);throw new Z(i,{status:o.status,payload:a})}let s=await o.json();if(!Array.isArray(s?.files))throw new Z("ora answered without a files list",{status:o.status,payload:s});for(let i of s.files)if(!Ka(i.path))throw new Z(`ora named a file path ax will not write: ${JSON.stringify(i.path)}`,{status:o.status,payload:s});return s}function Ya(e){return typeof e.body=="string"?e.body:`${JSON.stringify(e.content,null,2)}
|
|
47
|
+
`}var Xa=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"]]]),Va="/server-card";function za(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 Za(e,t){let n=(0,ee.resolve)(t),r={writes:[],elsewhere:[],unknown:[]};for(let o of e.files){if(!za(o,e.domain)){r.elsewhere.push(o);continue}let s=Xa.get(o.path);if(s)r.writes.push({target:(0,ee.join)(n,...s),file:o});else if(o.path.endsWith(Va)){let i=(0,ee.join)(n,...o.path.slice(1).split("/"));if((0,ee.relative)(n,i).startsWith(".."))throw new Z(`refusing to write outside ${n}: ${o.path}`);r.writes.push({target:i,file:o})}else r.unknown.push(o)}return r}function io(e,t=process.cwd()){let n=(0,ee.relative)(t,e);return n&&!n.startsWith("..")&&!(0,ee.isAbsolute)(n)?n:e}function Qa(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}function ao(e){if(typeof e!="object"||e===null)return null;let{errorCode:t,code:n}=e;return typeof t=="string"&&t?t:typeof n=="string"&&n?n:null}function ec(e,t){let n=t instanceof Error?t.message:String(t);if(t instanceof Z&&t.status===400)return{code:ao(t.payload)||"INVALID_DOMAIN",message:n,next:{call:w(["generate-files",C("domain"),...e.json?["--json"]:[]]),why:"a public host such as example.com"}};let r=["generate-files",e.domain,...e.json?["--json"]:[],...e.out?["--out",e.out]:[],...e.force?["--force"]:[]];return{code:ao(t instanceof Z?t.payload:void 0)||"API_ERROR",message:n,next:{call:w(r),why:"retry; ora may be briefly unreachable"}}}async function co(e){if(!e.domain?.trim())return j({code:"INVALID_TARGET",message:"a domain is required",next:{call:w(["generate-files",C("domain"),...e.json?["--json"]:[]])}},{json:e.json,display:()=>"Usage: ax generate-files <domain>"}),_.USAGE;let t;try{t=await so(e.domain,{baseUrl:e.baseUrl})}catch(c){let u=ec(e,c),l=c instanceof Z&&c.status!==null&&c.status>=400?c.payload:void 0;return j(u,{json:e.json,display:p=>`generate-files failed: ${p}`,served:l}),c instanceof Z&&c.status===400?_.USAGE:_.API}if(e.json)return process.stdout.write(`${JSON.stringify(t,null,2)}
|
|
48
|
+
`),T({call:w(["generate-files",t.domain,"--out",C("dir")]),why:"write the files instead of printing them"},{stderr:!0}),_.OK;let n=e.out??".",{writes:r,elsewhere:o,unknown:s}=Za(t,n);for(let c of s)console.error(Q.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,Ne.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(` ${io(c.target)}`);return T({call:w(["generate-files",e.domain,...e.out?["--out",e.out]:[],"--force"]),why:"overwrite them, or pass --out <dir> to write somewhere else"},{stderr:!0}),_.USAGE}for(let{target:c,file:u}of r)(0,Ne.mkdirSync)((0,ee.dirname)(c),{recursive:!0}),(0,Ne.writeFileSync)(c,Ya(u));let a=c=>{for(let u of c){let[l,...p]=Qa(u,74,"");console.log(Q.default.dim(` - ${l}`));for(let d of p)console.log(Q.default.dim(` ${d}`))}};console.log(""),console.log(` ${Q.default.bold(t.domain)} ${Q.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:u}of r)console.log(` ${Q.default.green("wrote")} ${io(c)} ${Q.default.dim(`${u.spec.name} ${u.spec.version}`)}`),a(u.notes),console.log("");for(let c of o)console.log(` ${Q.default.yellow("not written")} ${c.url} ${Q.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(` ${Q.default.bold("Not drafted")}`),a(t.notes),console.log("")),console.log(Q.default.dim(` Publish them at https://${t.domain}/ from your web root - these are drafts, review each before you ship it.`)),console.log(""),T({call:w(["audit",t.domain,"--force"]),why:"after you publish them, rescan to verify"},{stderr:!1}),_.OK}var xt=V(Y(),1);var k=V(Y(),1);var At=()=>me(60,120);function tc(e){if(e.type==="tool_call"){let t=e.input_display??e.summary??"";if(Ee(e))return t?`searching ${be(t,40)}`:"searching\u2026";let{host:n}=cn(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 nc=e=>e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e);function rc(e){return e<.01?`$${e.toFixed(4)}`:e<1?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function oc(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(`${nc(t.totalTokens)} tokens`),t?.costUsd!=null&&r.push(rc(t.costUsd)),["",` ${k.default.dim("\u2500".repeat(Math.min(At()-4,52)))}`,` ${n?k.default.green("\u2713"):k.default.red("\u2717")} ${k.default.bold(n?"completed":e.outcome)}${r.length?` ${k.default.dim(r.join(" \xB7 "))}`:""}`]}function sc(e,t=22){let n=Math.min(100,Math.max(0,e)),r=Math.round(n/100*t);return(n>=70?k.default.green:n>=50?k.default.yellow:k.default.red)("\u2588".repeat(r))+k.default.dim("\u2591".repeat(t-r))}function ic(e){return e==="high"?k.default.red("\u25CF high "):e==="medium"?k.default.yellow("\u25CF medium"):e==="low"?k.default.dim("\u25CF low "):k.default.dim("\u25CF ")}function ac(e){let t=[""];if(e.visibility_score!=null){let n=e.visibility_score,r=n>=70?k.default.green:n>=50?k.default.yellow:k.default.red,o=e.intent_satisfied?k.default.green("\u2713 intent satisfied"):k.default.yellow("\u2717 intent not satisfied");t.push(` ${k.default.bold("Visibility")} ${sc(n)} ${r(k.default.bold(`${n}/100`))} ${o}`)}if(e.summary){t.push("");for(let n of G(e.summary,At()-4))t.push(` ${k.default.dim(n)}`)}if(e.friction_points?.length){t.push("",` ${k.default.bold("Friction")}`);for(let n of e.friction_points){let[r,...o]=G(n,At()-6);t.push(` ${k.default.yellow("\xB7")} ${r}`);for(let s of o)t.push(` ${s}`)}}if(e.recommendations?.length){t.push("",` ${k.default.bold("Recommendations")}`);for(let n of e.recommendations){t.push(` ${ic(n.priority)} ${k.default.bold(n.title)}`);for(let r of G(n.detail,At()-8))t.push(` ${k.default.dim(r)}`)}}return t.push(""),t}function cc(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)}var pn=e=>e.json?["--json"]:[];function lo(e){return e.domain?{call:w(["audit",e.domain,...pn(e)]),why:"the readiness audit: which checks explain what the agent hit"}:{call:w(["journey",e.intent,"--domain",C("domain"),...pn(e)]),why:"name the site so the run can be traced back to it"}}function lc(e,t){let n=["journey",e.intent,...e.domain?["--domain",e.domain]:[],"--harness",e.harness,...e.model?["--model",e.model]:[],...pn(e)],r=t instanceof Error?t.message:String(t);return process.env.ORA_API_KEY?t instanceof We?{code:"KEY_DESTINATION_REFUSED",message:r,next:{call:w(n),why:Qn}}:{code:"PLATFORM_ERROR",message:r,next:{call:w(n),why:"retry; if it fails the same way, check ORA_API_KEY and ORA_PLATFORM_URL"}}:{code:"MISSING_API_KEY",message:r,next:{call:`ORA_API_KEY=<platform key> ${w(n)}`,why:"a goal of your own runs on ora's platform and needs a platform key; with no goal, ax journey --domain <site> runs one of ora's curated tasks free"}}}async function uo(e){let t={intent:e.intent,domain:e.domain,harness:e.harness,model:e.model},n=a=>{let c=lc(e,a);return j(c,{json:e.json,display:u=>`Journey failed: ${u}`,served:a instanceof re?a.payload:void 0}),2};if(e.json)try{let a=await Jt(t);return process.stdout.write(`${cc(a)}
|
|
49
|
+
`),T(lo(e),{stderr:!0}),a.result?.outcome==="success"?0:1}catch(a){return n(a)}let r=new Me,o=[],s=!1,i=()=>[` ${wt(o)}`,"",...bt(yt(o,e.intent,s)).map(a=>` ${a}`)];console.log(),console.log(` ${k.default.cyan("\u25B6")} ${e.domain?k.default.bold(e.domain):k.default.dim("(no domain)")} ${k.default.dim("\xB7")} ${k.default.dim(e.harness)}`),console.log(),r.open(),r.draw(i(),"waking the agent");try{let a=await Jt(t,{snapshot:c=>{o=c;let u=c[c.length-1];r.draw(i(),u?tc(u):"working")},finished:()=>{s=!0,r.draw(i(),"scoring the journey")}});r.close(),s=!0,a.trajectory.length&&(o=a.trajectory);for(let c of i())console.log(c);if(a.result)for(let c of oc(a.result,a.usage))console.log(c);if(a.insight)for(let c of ac(a.insight))console.log(c);else a.result&&(console.log(k.default.dim(" (insight not available for this run)")),console.log());return T(lo(e),{stderr:!1}),a.result?.outcome==="success"?0:1}catch(a){return r.close(),n(a)}}var hn="claude-code",ho={goal:{type:"positional",description:"What the agent should do, in plain words. Leave it out to run one of ora's curated tasks, free",required:!1},domain:{type:"string",description:"Site the agent works on (e.g. stripe.com)"},harness:{type:"string",description:`Agent harness for a goal of your own (default ${hn})`},model:{type:"string",description:"Model for a goal of your own (the harness default when omitted)"},intent:{type:"string",description:"One of ora's curated tasks, e.g. pricing, signup, api-docs (a free run)"},agent:{type:"string",description:"Agent from ora's public roster for a free run (default cas-haiku, Claude Code on Haiku)"},"api-key":{type:"string",description:"ora partner API key: lets a free run take a goal of your own; also read from ORA_PARTNER_API_KEY, then ORA_SCAN_API_KEY"},"no-stream":{type:"boolean",description:"A free run prints only its result, not the live view",default:!1},json:{type:"boolean",description:"Print JSON on stdout instead of the report",default:!1}};function fn(e){return e.stream===!1||e["no-stream"]===!0}var uc=["intent","agent","api-key","no-stream"],po=["harness","model"];function dc(e){let{goal:t,publicFlags:n,platformFlags:r}=e;if(n.length>0&&r.length>0){let o=n.map(i=>`--${i}`).join(", "),s=r.map(i=>`--${i}`).join(", ");return{error:`${o} ${n.length===1?"is":"are"} for ora's free journeys and ${s} for ora's platform; use one kind`,drop:n.map(i=>`--${i}`)}}return n.length>0?{route:"public"}:r.length>0?{route:"platform"}:t===void 0?{route:"public"}:!e.platformKey&&e.partnerKey?{route:"public"}:{route:"platform"}}function mn(e,t){let n=new Set;for(let r of e){if(r==="--")break;r.startsWith("--")&&n.add(r.slice(2).split("=")[0].replace(/^no-(?!stream)/,""))}return t.filter(r=>n.has(r))}var pc=new Set(Object.entries(ho).filter(([,e])=>e.type==="string").map(([e])=>`--${e}`));function mo(e,t){let n=[];for(let r=0;r<e.length;r++){let o=e[r];if(o==="--"){n.push(...e.slice(r));break}let s=o.includes("=")?o.slice(0,o.indexOf("=")):o;t.includes(s)?!o.includes("=")&&pc.has(s)&&r++:n.push(o)}return n}function mc(e){let{json:t}=e;if(!e.domain?.trim()){let n="--domain names the site the agent works on",r={call:w(["journey","--domain",C("domain"),...t?["--json"]:[]]),why:"ora picks the task"};return j({code:"INVALID_TARGET",message:n,next:r},{json:t}),_.USAGE}return vt({url:e.domain,intent:e.intent,task:e.goal,apiKey:e.apiKey,agent:e.agent,json:t,noStream:e.noStream,via:"journey"})}async function hc(e,t){let{goal:n,json:r}=e,o=dc({goal:n,publicFlags:mn(t,uc),platformFlags:mn(t,po),platformKey:!!process.env.ORA_API_KEY,partnerKey:!!(e.apiKey||process.env.ORA_PARTNER_API_KEY||process.env.ORA_SCAN_API_KEY)});if("error"in o){let s={call:w(["journey",...mo(t,o.drop)]),why:"for ora's platform"};return j({code:"INVALID_FLAG",message:o.error,next:s},{json:r}),_.USAGE}if(o.route==="public")return mc(e);if(n===void 0){let s=mn(t,po).map(c=>`--${c}`),i=`${s.join(", ")} ${s.length===1?"picks":"pick"} the agent for a goal of your own; with no goal, ax runs one of ora's curated tasks free`,a={call:w(["journey",...mo(t,s)]),why:"ora picks the task"};return j({code:"INVALID_FLAG",message:i,next:a},{json:r}),_.USAGE}return uo({intent:n,domain:e.domain,harness:e.harness??hn,model:e.model,json:r})}var fo="Send a real AI agent at a site and watch it live: free on one of ora's curated tasks, or on a goal of your own with a platform key",gn={meta:{name:"journey",description:fo},args:ho,async run({args:e,rawArgs:t}){process.exitCode=await hc({goal:e.goal,intent:e.intent,agent:e.agent,apiKey:e["api-key"],noStream:fn(e),domain:e.domain,harness:e.harness,model:e.model,json:!!e.json},t)}};function go(){let e=xt.default.dim,t=n=>xt.default.underline(xt.default.bold(n));return[e(`${fo} (ax journey)`),"",t("USAGE"),""," ax journey --domain <site> [--intent <id>] [--agent <id>] [--no-stream] [--json]",' ax journey "<goal>" [--domain <site>] [--harness <h>] [--model <m>] [--json]',""," With no goal, ax runs one of ora's curated tasks on ora.ai's public journeys: free, no key."," With a goal, the journey runs on ora's platform with your platform key.","",t("FREE, NO GOAL OF YOUR OWN"),"",` --domain <site> ${e("Site the agent works on (required)")}`,` --intent <id> ${e("Curated task id, e.g. pricing, signup, api-docs (ora picks one when omitted)")}`,` --agent <id> ${e("Agent from ora's public roster (default cas-haiku, Claude Code on Haiku)")}`,` --api-key <k> ${e("ora partner API key: allows a goal of your own here; also read from ORA_PARTNER_API_KEY, then ORA_SCAN_API_KEY")}`,` --no-stream ${e("Print only the result, not the live view")}`,` --json ${e("Print the finished run as JSON")}`,` ${e("these flags cannot be combined with --harness or --model")}`,` ${e("exit codes: 0 the run finished (any verdict) \xB7 1 the run failed \xB7 2 usage \xB7 3 API error")}`,` ${e("ax deep-journey <url> is the older name for this; it still works and will be removed in a future major release")}`,"",t("A GOAL OF YOUR OWN"),"",` --domain <site> ${e("Site the agent works on (e.g. stripe.com)")}`,` --harness <h> ${e(`Agent harness: ${hn} (default), codex, openclaw, hermess, claude-agent, eve, ...`)}`,` --model <m> ${e("Model override (the harness default when omitted)")}`,` --json ${e("Print the run as JSON")}`,` ${e("needs ORA_API_KEY (see .env.example)")}`,` ${e("exit codes: 0 the run succeeded \xB7 1 it finished without success \xB7 2 error")}`].join(`
|
|
50
|
+
`)}var yo="ora",wo="Workflows",bo={call:w(["audit",C("domain")]),why:"step one: score the site"};async function So(e={}){let t=`${$e(e.baseUrl)}/docs/cli`,n;try{let{bytes:o}=await ct(yo,e.baseUrl);n=new TextDecoder().decode(o)}catch(o){let s=o instanceof Error?o.message:String(o);return j({code:o instanceof H?o.code:"REGISTRY_ERROR",message:s,next:{call:w(["learn"]),why:`retry, or read ${t}`}},{json:!1,display:i=>`ax learn: ${i}`}),_.API}let r=rr(n,wo);return r?(process.stdout.write(`${r}
|
|
51
|
+
`),T(bo,{stderr:!0}),_.OK):(console.log(`The ${yo} skill has no ${wo} section yet. The ax workflow is in the CLI guide: ${t}`),T(bo,{stderr:!0}),_.OK)}var Et=require("fs"),yn=require("path"),Ve=V(Y(),1);var vo=".claude/skills";function fc(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 Ao(e){try{if(!e.name){let r=await Ht(),o=r[0]?{call:w(["skill",r[0].name,"--install"]),why:"or any name in the list"}:{call:w(["learn"]),why:"the registry is empty; print the ax workflow instead"};if(e.json)return process.stdout.write(`${JSON.stringify(r,null,2)}
|
|
52
|
+
`),T(o,{stderr:!0}),_.OK;console.log("");for(let s of r){let i=s.digest?Ve.default.dim(` ${s.digest.slice(0,19)}\u2026`):"";if(console.log(` ${Ve.default.bold(s.name)}${i}`),s.description)for(let a of fc(s.description,76," "))console.log(Ve.default.dim(a));console.log("")}return T(o,{stderr:!1}),_.OK}let{entry:t,bytes:n}=await ct(e.name);if(e.install){let r=(0,yn.join)(e.dir??vo,t.name);(0,Et.mkdirSync)(r,{recursive:!0});let o=(0,yn.join)(r,"SKILL.md");return(0,Et.writeFileSync)(o,n),console.log(`Installed ${t.name} to ${o}`),t.digest&&console.log(Ve.default.dim(`verified ${t.digest}`)),T({call:w(["learn"]),why:"the workflow: scan, read the report, run a journey, read its result"},{stderr:!1}),_.OK}return process.stdout.write(n),T({call:w(["skill",t.name,"--install"]),why:`write it to ${vo}`},{stderr:!0}),_.OK}catch(t){let n=t instanceof Error?t.message:String(t),r=t instanceof H&&t.code==="UNKNOWN_SKILL",o=e.json?["--json"]:[],s=w(["skill",...e.name?[e.name]:[],...o,...e.install?["--install"]:[],...e.dir?["--dir",e.dir]:[]]);return j({code:t instanceof H?t.code:"REGISTRY_ERROR",message:n,next:r?{call:w(["skill",...o]),why:"list the skills the registry has"}:{call:s,why:"retry; the registry may be briefly unreachable"}},{json:e.json,display:i=>`Skill command failed: ${i}`,served:t instanceof H?t.payload:void 0}),r?_.USAGE:_.API}}var M=class extends Error{constructor(t,n){super(t,n),this.name="CdpError"}},xo=1e4,Eo=5e3,bn=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 M(`timed out connecting to ${t}`))},Eo);n.addEventListener("open",()=>{clearTimeout(s),r()},{once:!0}),n.addEventListener("error",()=>{clearTimeout(s),o(new M(`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 M(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 M(t));this.pending.clear()}}send(t,n={},r={}){if(this.closed)return Promise.reject(new M(this.closeReason??"the connection is closed"));let o=this.nextId++,s=r.timeoutMs??xo;return new Promise((i,a)=>{let c=setTimeout(()=>{this.pending.delete(o),a(new M(`${t} timed out after ${s}ms`))},s);this.pending.set(o,{resolve:i,reject:a,timer:c});let u={id:o,method:t,params:n};r.sessionId&&(u.sessionId=r.sessionId);try{this.socket.send(JSON.stringify(u))}catch(l){this.pending.delete(o),clearTimeout(c),a(new M(`could not send ${t}`,{cause:l}))}})}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 vn(e,t=Eo){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 M(`no debuggable Chrome answered at ${n}`,{cause:s})}if(!r.ok)throw new M(`${n}/json/version returned HTTP ${r.status}`);let o=await r.json().catch(()=>null);if(!o?.webSocketDebuggerUrl)throw new M(`${n}/json/version carried no webSocketDebuggerUrl`);return{webSocketDebuggerUrl:o.webSocketDebuggerUrl,product:o.Browser??""}}var Rt=class e{connection;product;constructor(t,n){this.connection=t,this.product=n}static async connect(t){let n=await bn.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 Sn(this.connection,o,n,t.entryUrl);return await s.prepare(t.initScripts??[],t.viewport),s}close(){this.connection.close()}},gc=8,yc=1024*1024,wc=new Set(["Image","Media","Font"]),Sn=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=wn(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;(wc.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:bc(o.headers??{})});return}if(n!=="Script"||this.scriptsStarted>=gc)return;let s=typeof o.url=="string"?o.url:"",i=wn(s);i&&(i!==this.entryHost&&i!==wn(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,yc)})}).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 M(`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 M(`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=xo){let r=await this.send("Runtime.evaluate",{expression:t,awaitPromise:!0,returnByValue:!0},n),o=r.exceptionDetails;if(o)throw new M(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(){let t=await this.evaluate('Array.from(document.querySelectorAll("script:not([src])")).map(function (s) { return { type: s.getAttribute("type"), text: s.textContent || "" }; })').catch(()=>null);return Array.isArray(t)?t.map(n=>({type:typeof n?.type=="string"?n.type:void 0,text:typeof n?.text=="string"?n.text:""})):[]}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 bc(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.toLowerCase(),s=r.split(`
|
|
53
|
+
`).map(i=>i.trim()).filter(i=>i.length>0).join(", ");t[o]=t[o]===void 0?s:`${t[o]}, ${s}`}return t}function wn(e){try{return new URL(e).host}catch{return""}}var Sc=new Set([2,3]),vc=8192,Ac=864e10;function xc(e){if(typeof e!="string")return null;let t=e.trim();if(t.length===0||t.length>vc)return null;let n;try{n=Buffer.from(t,"base64")}catch{return null}if(n.length<=69||!Sc.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>Ac?null:{origin:i,feature:a,expiry:c,isSubdomain:s.isSubdomain===!0,isThirdParty:s.isThirdParty===!0}}function Ec(e){let t=e.toLowerCase().replace(/[^a-z]/g,"");return t==="webmcp"||t.includes("modelcontext")}function Rc(e,t,n){let r,o;try{r=new URL(e),o=new URL(t)}catch{return!1}if(r.protocol!==o.protocol||r.port!==o.port)return!1;let s=r.hostname.toLowerCase(),i=o.hostname.toLowerCase();return s===i?!0:n&&i.endsWith(`.${s}`)}function Ro(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=xc(s);if(!i)continue;let a=Ec(i.feature),c=i.expiry*1e3>n.getTime(),u=Rc(i.origin,t,i.isSubdomain),l=a&&c&&u,p=l?3:a?2:1;(!o||p>o.rank)&&(o={parsed:i,eligible:l,rank:p})}return o?{present:!0,payloadEligible:o.eligible,origin:o.parsed.origin,feature:o.parsed.feature,expiresAt:new Date(o.parsed.expiry*1e3).toISOString()}:{present:!0,payloadEligible:!1}}function _o(e){return e?e.split(",").map(t=>t.trim()).filter(t=>t.length>0):[]}var An="capture-incomplete:";function _c(e){return e.imperative!==null||e.polyfillPackages.length>0}function ko(e){return e.blocked?"blocked":e.loadError?"load-error":e.nativeToolCount!==null&&e.nativeToolCount>0?"active":e.toolCount>0?"testing-only":e.nativeToolCount===0?"api-empty":e.nativeApi||e.shimTakenOver||_c(e.staticSignals)?"declared-inactive":"absent"}function To(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 $o={"shared-experience":30,"task-completion":25,"tool-quality":25,trust:20},Co={"page-experience":{title:"Page experience",category:"shared-experience",weight:16,docSlug:"page-experience"},"human-parity":{title:"Human parity",category:"shared-experience",weight:8,docSlug:"human-parity"},"visible-effect":{title:"Visible effect",category:"shared-experience",weight:6,docSlug:"visible-effect"},"tool-selection":{title:"Tool selection",category:"task-completion",weight:12,docSlug:"tool-selection"},"coverage-vs-site-type":{title:"Coverage vs. site type",category:"task-completion",weight:7,docSlug:"coverage-vs-site-type"},"invoke-success-rate":{title:"Invoke success rate",category:"task-completion",weight:6,docSlug:"invoke-success-rate"},"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:4,docSlug:"annotations-present"},"annotation-mismatch":{title:"Annotation mismatch",category:"trust",weight:4,docSlug:"annotation-mismatch"},"injection-surface":{title:"Injection surface",category:"trust",weight:3,docSlug:"injection-surface"},"untrusted-content-hint":{title:"Untrusted content hint",category:"trust",weight:3,docSlug:"untrusted-content-hint"},"hint-vs-observed":{title:"Hint vs. observed",category:"trust",weight:3,docSlug:"hint-vs-observed"},"consequential-hint":{title:"Consequential hint",category:"trust",weight:3,docSlug:"consequential-hint"}},Re="3";var kc=100,Io=4096,Tc=512,xn=32768,$c=50,ze=200,En=128,Rn=1e3,_n=4e3,_t=1024,Po="__oraWebmcpCapture",Oo=`(function () {
|
|
48
54
|
"use strict";
|
|
49
55
|
try {
|
|
50
56
|
var W = typeof globalThis !== "undefined" ? globalThis : window;
|
|
51
|
-
if (W.${
|
|
52
|
-
|
|
53
|
-
var SHIM_VERSION = ${JSON.stringify(
|
|
54
|
-
var MAX_TOOLS = ${
|
|
55
|
-
var MAX_DESCRIPTION_CHARS = ${
|
|
56
|
-
var
|
|
57
|
-
var
|
|
57
|
+
if (W.${Po}) return;
|
|
58
|
+
|
|
59
|
+
var SHIM_VERSION = ${JSON.stringify(Re)};
|
|
60
|
+
var MAX_TOOLS = ${kc};
|
|
61
|
+
var MAX_DESCRIPTION_CHARS = ${Io};
|
|
62
|
+
var MAX_TITLE_CHARS = ${Tc};
|
|
63
|
+
var MAX_SCHEMA_CHARS = ${xn};
|
|
64
|
+
var MAX_ERRORS = ${$c};
|
|
58
65
|
// Internal bound only: a page looping on addEventListener must not grow
|
|
59
66
|
// the shim's retained set without limit.
|
|
60
67
|
var MAX_LISTENERS = 50;
|
|
@@ -261,7 +268,10 @@ ${C.map(L=>` ${L.id.padEnd(12)} ${Et(L)}`).join(`
|
|
|
261
268
|
|
|
262
269
|
record.description = description;
|
|
263
270
|
record.descriptionTruncated = descriptionTruncated;
|
|
271
|
+
var rawTitle = readProp(tool, "title");
|
|
272
|
+
record.title = typeof rawTitle === "string" ? rawTitle.slice(0, MAX_TITLE_CHARS) : null;
|
|
264
273
|
record.inputSchema = safeCopy(readProp(tool, "inputSchema"), MAX_SCHEMA_CHARS);
|
|
274
|
+
record.outputSchema = safeCopy(readProp(tool, "outputSchema"), MAX_SCHEMA_CHARS);
|
|
265
275
|
record.annotations = safeCopy(readProp(tool, "annotations"), MAX_SCHEMA_CHARS);
|
|
266
276
|
record.hasExecute = hasExecute(tool);
|
|
267
277
|
record.entryPoint = entryPoint;
|
|
@@ -392,14 +402,13 @@ ${C.map(L=>` ${L.id.padEnd(12)} ${Et(L)}`).join(`
|
|
|
392
402
|
return safeCopy(value, MAX_SCHEMA_CHARS);
|
|
393
403
|
}
|
|
394
404
|
|
|
395
|
-
// The draft's RegisteredTool list (section 4.
|
|
405
|
+
// The draft's RegisteredTool list (section 4.2.6): the CURRENT tool map,
|
|
396
406
|
// sorted ascending by name in code-unit order. Unregistered records are
|
|
397
407
|
// audit evidence, not live tools, so they are filtered; a name live under
|
|
398
408
|
// both sources is returned twice rather than deduped (the real map could
|
|
399
|
-
// never hold both, but picking a winner here would invent one).
|
|
400
|
-
// is ""
|
|
401
|
-
//
|
|
402
|
-
// missing title (spec issue 224 is unresolved).
|
|
409
|
+
// never hold both, but picking a winner here would invent one). A
|
|
410
|
+
// missing title is "", what the draft's getTools() currently reports
|
|
411
|
+
// (spec issue 224 is unresolved).
|
|
403
412
|
function getToolsList() {
|
|
404
413
|
var list = [];
|
|
405
414
|
for (var i = 0; i < entries.length; i++) {
|
|
@@ -407,9 +416,10 @@ ${C.map(L=>` ${L.id.padEnd(12)} ${Et(L)}`).join(`
|
|
|
407
416
|
if (entry.unregistered) continue;
|
|
408
417
|
list.push({
|
|
409
418
|
name: entry.name,
|
|
410
|
-
title: "",
|
|
419
|
+
title: typeof entry.title === "string" ? entry.title : "",
|
|
411
420
|
description: entry.description,
|
|
412
421
|
inputSchema: projectStoredValue(entry.inputSchema),
|
|
422
|
+
outputSchema: projectStoredValue(entry.outputSchema),
|
|
413
423
|
annotations: projectStoredValue(entry.annotations),
|
|
414
424
|
window: W,
|
|
415
425
|
origin: pinnedOrigin
|
|
@@ -589,7 +599,9 @@ ${C.map(L=>` ${L.id.padEnd(12)} ${Et(L)}`).join(`
|
|
|
589
599
|
name: e.name,
|
|
590
600
|
description: e.description,
|
|
591
601
|
descriptionTruncated: e.descriptionTruncated,
|
|
602
|
+
title: e.title === undefined ? null : e.title,
|
|
592
603
|
inputSchema: e.inputSchema,
|
|
604
|
+
outputSchema: e.outputSchema,
|
|
593
605
|
annotations: e.annotations,
|
|
594
606
|
hasExecute: e.hasExecute,
|
|
595
607
|
entryPoint: e.entryPoint,
|
|
@@ -613,7 +625,7 @@ ${C.map(L=>` ${L.id.padEnd(12)} ${Et(L)}`).join(`
|
|
|
613
625
|
// Non-writable and non-configurable: the capture payload is the audit's
|
|
614
626
|
// evidence, so a page must not be able to replace snapshot() and report
|
|
615
627
|
// whatever tools it wishes it had.
|
|
616
|
-
nativeDefineProperty(W, ${JSON.stringify(
|
|
628
|
+
nativeDefineProperty(W, ${JSON.stringify(Po)}, {
|
|
617
629
|
value: {
|
|
618
630
|
shimVersion: SHIM_VERSION,
|
|
619
631
|
installedAt: now(),
|
|
@@ -630,9 +642,129 @@ ${C.map(L=>` ${L.id.padEnd(12)} ${Et(L)}`).join(`
|
|
|
630
642
|
// Nothing left to report to; never let the shim break the page.
|
|
631
643
|
}
|
|
632
644
|
}
|
|
633
|
-
})();`,
|
|
634
|
-
var MAX_FORMS = ${
|
|
635
|
-
var MAX_DESCRIPTION_CHARS = ${
|
|
645
|
+
})();`,Mo=`(function () {
|
|
646
|
+
var MAX_FORMS = ${ze};
|
|
647
|
+
var MAX_DESCRIPTION_CHARS = ${Io};
|
|
648
|
+
var MAX_FIELDS = ${En};
|
|
649
|
+
var pageFieldsLeft = ${Rn};
|
|
650
|
+
var pageOptionsLeft = ${_n};
|
|
651
|
+
var MAX_TEXT = ${_t};
|
|
652
|
+
var MAX_NAME = 256;
|
|
653
|
+
var MAX_NUMBER = 64;
|
|
654
|
+
var MAX_OPTION = 256;
|
|
655
|
+
var MAX_LABELS = 8;
|
|
656
|
+
var MAX_LABEL_NODES = 4096;
|
|
657
|
+
var CONTROL = { INPUT: 1, SELECT: 1, TEXTAREA: 1 };
|
|
658
|
+
var LABELABLE = { BUTTON: 1, INPUT: 1, METER: 1, OUTPUT: 1, PROGRESS: 1, SELECT: 1, TEXTAREA: 1 };
|
|
659
|
+
|
|
660
|
+
function capped(value, cap, state, identity) {
|
|
661
|
+
if (value === null || value === undefined) return null;
|
|
662
|
+
var text = String(value);
|
|
663
|
+
if (text.length <= cap) return text;
|
|
664
|
+
if (identity) state.truncated = true;
|
|
665
|
+
return text.slice(0, cap);
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
function labelText(label) {
|
|
669
|
+
var out = "";
|
|
670
|
+
var visited = 0;
|
|
671
|
+
var node = label.firstChild;
|
|
672
|
+
while (node && visited < MAX_LABEL_NODES && out.length <= MAX_TEXT) {
|
|
673
|
+
visited++;
|
|
674
|
+
if (node.nodeType === 3) out += node.nodeValue;
|
|
675
|
+
if (node.nodeType === 1 && !LABELABLE[node.tagName] && node.firstChild) {
|
|
676
|
+
node = node.firstChild;
|
|
677
|
+
continue;
|
|
678
|
+
}
|
|
679
|
+
while (node && node !== label && !node.nextSibling) node = node.parentNode;
|
|
680
|
+
node = !node || node === label ? null : node.nextSibling;
|
|
681
|
+
}
|
|
682
|
+
return out.trim().slice(0, MAX_TEXT);
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
function labelsOf(el) {
|
|
686
|
+
var texts = [];
|
|
687
|
+
var labels = el.labels || [];
|
|
688
|
+
for (var i = 0; i < labels.length && texts.length < MAX_LABELS; i++) {
|
|
689
|
+
if (labels[i].control && labels[i].control !== el) continue;
|
|
690
|
+
var text = labelText(labels[i]);
|
|
691
|
+
if (text) texts.push(text);
|
|
692
|
+
}
|
|
693
|
+
return texts;
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
function disabledByFieldset(el) {
|
|
697
|
+
var child = el;
|
|
698
|
+
for (var node = el.parentNode; node && node.nodeType === 1; node = node.parentNode) {
|
|
699
|
+
if (node.tagName === "FIELDSET" && node.hasAttribute("disabled")) {
|
|
700
|
+
var legend = null;
|
|
701
|
+
for (var c = node.firstElementChild; c && !legend; c = c.nextElementSibling) {
|
|
702
|
+
if (c.tagName === "LEGEND") legend = c;
|
|
703
|
+
}
|
|
704
|
+
if (child !== legend) return true;
|
|
705
|
+
}
|
|
706
|
+
child = node;
|
|
707
|
+
}
|
|
708
|
+
return false;
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
function readField(el, state) {
|
|
712
|
+
var tag = el.tagName.toLowerCase();
|
|
713
|
+
var type = tag === "input" ? String(el.type || "text").toLowerCase() : tag;
|
|
714
|
+
var numeric = type === "number" || type === "range";
|
|
715
|
+
var choice = type === "checkbox" || type === "radio";
|
|
716
|
+
var field = {
|
|
717
|
+
tag: tag,
|
|
718
|
+
type: type,
|
|
719
|
+
name: capped(el.getAttribute("name") || "", MAX_NAME, state, true),
|
|
720
|
+
disabled: !!el.disabled || disabledByFieldset(el),
|
|
721
|
+
readOnly: !!el.readOnly,
|
|
722
|
+
required: el.hasAttribute("required"),
|
|
723
|
+
multiple: el.hasAttribute("multiple"),
|
|
724
|
+
paramDescription: capped(el.getAttribute("toolparamdescription"), MAX_TEXT, state, false),
|
|
725
|
+
labels: labelsOf(el),
|
|
726
|
+
ariaDescription: capped(el.getAttribute("aria-description"), MAX_TEXT, state, false),
|
|
727
|
+
min: numeric ? capped(el.getAttribute("min"), MAX_NUMBER, state, true) : null,
|
|
728
|
+
max: numeric ? capped(el.getAttribute("max"), MAX_NUMBER, state, true) : null,
|
|
729
|
+
step: numeric ? capped(el.getAttribute("step"), MAX_NUMBER, state, true) : null,
|
|
730
|
+
value: numeric ? capped(el.getAttribute("value"), MAX_NUMBER, state, true) : null,
|
|
731
|
+
pattern: tag === "input" ? capped(el.getAttribute("pattern"), MAX_TEXT, state, true) : null,
|
|
732
|
+
checkedValue: choice ? capped(el.value, MAX_OPTION, state, true) : null,
|
|
733
|
+
options: []
|
|
734
|
+
};
|
|
735
|
+
if (tag === "select") {
|
|
736
|
+
var options = el.options || [];
|
|
737
|
+
for (var j = 0; j < options.length; j++) {
|
|
738
|
+
if (pageOptionsLeft <= 0) {
|
|
739
|
+
state.truncated = true;
|
|
740
|
+
break;
|
|
741
|
+
}
|
|
742
|
+
pageOptionsLeft--;
|
|
743
|
+
field.options.push({
|
|
744
|
+
value: capped(options[j].value, MAX_OPTION, state, true),
|
|
745
|
+
text: capped(options[j].textContent, MAX_OPTION, state, false)
|
|
746
|
+
});
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
return field;
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
function readFields(form, state) {
|
|
753
|
+
var fields = [];
|
|
754
|
+
var elements = form.elements || [];
|
|
755
|
+
for (var k = 0; k < elements.length; k++) {
|
|
756
|
+
var el = elements[k];
|
|
757
|
+
if (!CONTROL[el.tagName]) continue;
|
|
758
|
+
if (fields.length >= MAX_FIELDS || pageFieldsLeft <= 0) {
|
|
759
|
+
state.truncated = true;
|
|
760
|
+
break;
|
|
761
|
+
}
|
|
762
|
+
pageFieldsLeft--;
|
|
763
|
+
fields.push(readField(el, state));
|
|
764
|
+
}
|
|
765
|
+
return fields;
|
|
766
|
+
}
|
|
767
|
+
|
|
636
768
|
var forms = [];
|
|
637
769
|
var nodes = document.querySelectorAll("form[toolname]");
|
|
638
770
|
for (var i = 0; i < nodes.length && forms.length < MAX_FORMS; i++) {
|
|
@@ -640,17 +772,26 @@ ${C.map(L=>` ${L.id.padEnd(12)} ${Et(L)}`).join(`
|
|
|
640
772
|
var description = node.getAttribute("tooldescription") || "";
|
|
641
773
|
var toolName = node.getAttribute("toolname") || "";
|
|
642
774
|
if (!toolName.trim()) continue;
|
|
775
|
+
var state = { truncated: false };
|
|
776
|
+
var fields = [];
|
|
777
|
+
try {
|
|
778
|
+
fields = readFields(node, state);
|
|
779
|
+
} catch (fieldReadError) {
|
|
780
|
+
state.truncated = true;
|
|
781
|
+
}
|
|
643
782
|
forms.push({
|
|
644
783
|
toolName: toolName,
|
|
645
784
|
toolDescription: description.slice(0, MAX_DESCRIPTION_CHARS),
|
|
646
785
|
action: node.getAttribute("action") || "",
|
|
647
786
|
method: (node.getAttribute("method") || "get").toLowerCase(),
|
|
648
|
-
fieldCount: node.querySelectorAll("input, select, textarea").length
|
|
787
|
+
fieldCount: node.querySelectorAll("input, select, textarea").length,
|
|
788
|
+
fields: fields,
|
|
789
|
+
fieldsTruncated: state.truncated
|
|
649
790
|
});
|
|
650
791
|
}
|
|
651
792
|
return { forms: forms };
|
|
652
|
-
})()`;var
|
|
653
|
-
`)),s=new Set;for(let a of r){let c=a.toLowerCase();for(let
|
|
793
|
+
})()`;var Cc=new Set(["hidden","file","submit","image","reset","button"]),Pc=new Set(["text","search","url","tel","email","password"]),No="Dates MUST be provided in 'YYYY-MM-DD' format.",Ic=new Map([["time","^([01][0-9]|2[0-3]):[0-5][0-9]$"],["month","^[0-9]{4}-(0[1-9]|1[0-2])$"],["week","^[0-9]{4}-W(0[1-9]|[1-4][0-9]|5[0-3])$"],["datetime-local","^[0-9]{4}-(0[1-9]|1[0-2])-[0-9]{2}T([01][0-9]|2[0-3]):[0-5][0-9]$"],["color","^#[0-9a-zA-Z]{6}$"]]),Oc=/^-?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][-+]?\d+)?$/,Mc=1e-9,Nc=11,Lc=6e3;function kt(e){if(e===null||!Oc.test(e))return null;let t=Number(e);return Number.isFinite(t)?t:null}function jo(e){let t=Rn,n=_n,r={charsLeft:Lc};return e.slice(0,ze).map(o=>{let s=Array.isArray(o.fields)?o.fields:[],i=s.reduce((c,u)=>c+(Uo(u)&&Array.isArray(u.options)?u.options.length:0),0),a=s.length<=En&&s.length<=t&&i<=n;return t-=Math.min(s.length,t),n-=Math.min(i,n),a?jc(o,r):{__truncated:!0}})}function jc(e,t){if(!Array.isArray(e.fields)||e.fieldsTruncated!==!1)return{__truncated:!0};let n=new Map;for(let l of e.fields){if(!Uc(l)||!Dc(l))continue;let p=n.get(l.name);p?p.push(l):n.set(l.name,[l])}let r=[],o=[],s=[];for(let[l,p]of n){let d=Fc(p,s);d&&(r.push([l,d]),p.some(m=>m.required===!0)&&o.push(l))}let i={type:"object",properties:Object.fromEntries(r),required:o};if(s.reduce((l,[,p])=>l+Nc+JSON.stringify(p).length,JSON.stringify(i).length)>xn)return{__truncated:!0};let c=s.filter(([,l])=>l.length<=_t),u=c.reduce((l,[,p])=>l+p.length,0);if(u>t.charsLeft)return{__truncated:!0};t.charsLeft-=u;for(let[l,p]of c)Bc(p)&&(l.pattern=p);return i}function Uo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Uc(e){return Uo(e)&&(e.tag==="input"||e.tag==="select"||e.tag==="textarea")&&typeof e.type=="string"&&typeof e.name=="string"&&Array.isArray(e.labels)&&Array.isArray(e.options)}function Dc(e){return e.disabled===!0||e.readOnly===!0?!1:e.tag!=="input"||!Cc.has(e.type)}function Fc(e,t){let n=r=>e.every(o=>o.tag==="input"&&o.type===r);return n("radio")?Lo(e):n("checkbox")?e.length===1?Le({type:"boolean"},e[0]):{type:"array",items:Lo(e),uniqueItems:!0}:e.length===1?Wc(e[0],t):null}function Lo(e){let t=e.map(n=>ge(n.checkedValue)??"on");return{type:"string",anyOf:e.map((n,r)=>{let o=Fo(n);return o?{type:"string",const:t[r],title:o}:{type:"string",const:t[r]}}),enum:t}}function Wc(e,t){if(e.tag==="select"){let s=e.options.filter(a=>typeof a?.value=="string"&&typeof a?.text=="string"),i={type:"string",anyOf:s.map(a=>({type:"string",const:a.value,title:a.text})),enum:s.map(a=>a.value)};return Le(e.multiple===!0?{type:"array",items:i,uniqueItems:!0}:i,e)}if(e.tag==="textarea")return Le({type:"string"},e);if(e.type==="number"||e.type==="range")return Le(Jc(e,e.type==="range"),e);if(e.type==="date"){let s=Do(e);return{type:"string",format:"date",description:s?`${s} (${No})`:No}}let n=Ic.get(e.type);if(n)return Le({type:"string",format:n},e);let r=Le({type:"string"},e),o=Pc.has(e.type)?ge(e.pattern):null;return o!==null&&t.push([r,o]),r}function Bc(e){if(e.length>_t)return!1;try{return RegExp(e,"v"),RegExp(`^(?:${e})$`,"v"),!0}catch(t){if(t instanceof SyntaxError)return!1;throw t}}function Jc(e,t){let n=kt(ge(e.min)),r=kt(ge(e.max)),o=t?n??0:n,s=t?Math.max(r??100,o??0):r,i={type:"number"};o!==null&&(i.minimum=o),s!==null&&(i.maximum=s);let a=Hc(ge(e.step),t),c=n??kt(ge(e.value))??0;return a!==null&&Gc(c,a)&&(i.multipleOf=a),i}function Hc(e,t){if(e!==null&&e.toLowerCase()==="any")return t?1:null;let n=kt(e);return n!==null&&n>0?n:1}function Gc(e,t){let n=e/t;return Math.abs(n-Math.round(n))<Mc}function Le(e,t){let n=Do(t);return n===null?e:{...e,description:n}}function Do(e){return ge(e.paramDescription)||Fo(e)||ge(e.ariaDescription)||null}function Fo(e){return e.labels.filter(t=>typeof t=="string"&&t!=="").join("; ")}function ge(e){return typeof e=="string"?e:null}function Kc(e,t,n){return!!(t["cf-mitigated"]==="challenge"||e===403&&n.includes("cf-browser-verification")||e===503&&n.includes("challenge-platform"))}function Wo(e,t,n){return!!(Kc(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 qc=new Set(["application/ecmascript","application/javascript","application/x-ecmascript","application/x-javascript","text/ecmascript","text/javascript","text/javascript1.0","text/javascript1.1","text/javascript1.2","text/javascript1.3","text/javascript1.4","text/javascript1.5","text/jscript","text/livescript","text/x-ecmascript","text/x-javascript"]);function kn(e){if(e===void 0)return!0;let t=e.trim().toLowerCase();return t===""||t==="module"||qc.has(t)}var Jo=["@mcp-b/global","@mcp-b/react-webmcp","usewebmcp"];function Yc(e){let t=e.toLowerCase(),n=/document\.modelcontext\b/.test(t),r=/navigator\.modelcontext\b/.test(t),o=/modelcontext\??\.registertool/.test(t)||(n||r||/\.modelcontext\b/.test(t))&&/\.registertool\s*\(/.test(t),s=/modelcontext\??\.providecontext/.test(t),i=Jo.find(c=>t.includes(c));return!o&&!s&&!i?null:{marker:o?n?"document.modelContext.registerTool":r?"navigator.modelContext.registerTool":"modelContext.registerTool":s?"modelContext.provideContext":`${i} package`,deprecatedAliasOnly:o&&r&&!n,removedApiOnly:!o&&s}}var Xc=["webmcp","web model context protocol"];function Bo(e){let t=e.toLowerCase();return Xc.some(n=>t.includes(n))}function Ho(e,t,n){let r=[t,...n.map(a=>a.body)],o=Yc(r.join(`
|
|
794
|
+
`)),s=new Set;for(let a of r){let c=a.toLowerCase();for(let u of Jo)c.includes(u)&&s.add(u)}let i=Bo(e)||r.some(Bo);return{imperative:o,polyfillPackages:[...s],keywordMention:i}}var qo=15e3,Vc=3e4,zc=2e3,Yo=250,Xo={fast:5e3,deep:1e4},Zc={fast:12e3,deep:2e4},Qc=2*1024*1024,Vo=512,zo=512,el=60,tl=15e5,Zo={width:1280,height:720},Go={imperative:null,polyfillPackages:[],keywordMention:!1},nl=`(function () {
|
|
654
795
|
var tokens = [];
|
|
655
796
|
try {
|
|
656
797
|
var metas = document.querySelectorAll('meta[http-equiv="origin-trial" i]');
|
|
@@ -668,7 +809,7 @@ ${C.map(L=>` ${L.id.padEnd(12)} ${Et(L)}`).join(`
|
|
|
668
809
|
// A hostile getter on either global; absence is the honest answer.
|
|
669
810
|
}
|
|
670
811
|
return { nativeApi: nativeApi, metaTokens: tokens };
|
|
671
|
-
})()`,
|
|
812
|
+
})()`,rl=`(async function () {
|
|
672
813
|
try {
|
|
673
814
|
var modelContext = document.modelContext || navigator.modelContext;
|
|
674
815
|
if (!modelContext || typeof modelContext.getTools !== "function") return null;
|
|
@@ -677,14 +818,14 @@ ${C.map(L=>` ${L.id.padEnd(12)} ${Et(L)}`).join(`
|
|
|
677
818
|
} catch (e) {
|
|
678
819
|
return null;
|
|
679
820
|
}
|
|
680
|
-
})()`,
|
|
821
|
+
})()`,Qo=`(function () {
|
|
681
822
|
try {
|
|
682
823
|
var g = window.__oraWebmcpCapture;
|
|
683
824
|
return g ? g.snapshot() : null;
|
|
684
825
|
} catch (e) {
|
|
685
826
|
return null;
|
|
686
827
|
}
|
|
687
|
-
})()`,
|
|
828
|
+
})()`,ol=`(function () {
|
|
688
829
|
try {
|
|
689
830
|
var g = window.__oraWebmcpCapture;
|
|
690
831
|
if (!g) return "none";
|
|
@@ -694,24 +835,31 @@ ${C.map(L=>` ${L.id.padEnd(12)} ${Et(L)}`).join(`
|
|
|
694
835
|
} catch (e) {
|
|
695
836
|
return "error";
|
|
696
837
|
}
|
|
697
|
-
})()`;function
|
|
698
|
-
`)[
|
|
699
|
-
`)}
|
|
700
|
-
`):
|
|
701
|
-
`)[
|
|
702
|
-
`)
|
|
838
|
+
})()`;function es(e,t){return e.filter(n=>!n.unregistered).map(n=>({name:n.name.slice(0,Vo),title:typeof n.title=="string"?n.title.slice(0,zo):null,description:n.description,via:"imperative",entryPoint:n.source==="provideContext"?"provideContext":n.entryPoint,pageUrl:t,inputSchema:n.inputSchema,...n.outputSchema===null||n.outputSchema===void 0?{}:{outputSchema:n.outputSchema},annotations:il(n.annotations),hasExecute:n.hasExecute,registrationMs:n.registrationMs}))}function sl(e,t){let n=e.slice(0,ze),r=jo(n);return n.map((o,s)=>({name:o.toolName.slice(0,Vo),description:o.toolDescription,via:"declarative",entryPoint:"form",pageUrl:t,inputSchema:r[s],annotations:{},hasExecute:!0,registrationMs:null}))}function il(e){if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e,n={};for(let r of["readOnlyHint","destructiveHint","idempotentHint","openWorldHint","untrustedContentHint","consequentialHint","debugging"])typeof t[r]=="boolean"&&(n[r]=t[r]);return typeof t.title=="string"&&(n.title=t.title.slice(0,zo)),n}function al(e){if(!e)return[];let t=[...e.registrationErrors];return e.takenOver.length>0&&t.push(`${An} the page replaced modelContext on ${e.takenOver.join(", ")}, so imperative tools may be under-reported`),e.extraToolCount>0&&t.push(`${An} the capture's tool cap was reached and ${e.extraToolCount} further registration attempts were not stored`),t}function cl(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()!=="tools")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 ll(e,t,n,r,o){let s=Date.now(),i={finalUrl:t,navMs:0,blocked:!1,nativeApi:!1,nativeToolCount:null,originTrialTokens:[],permissionsPolicy:null,html:"",inlineJs:"",scripts:[],screenshot:null,loadError:null},a=null;try{a=await e.newContext({entryUrl:t,viewport:Zo});let c;try{c=await a.goto(t,$t(r,qo))}catch(S){return{...i,navMs:Date.now()-s,loadError:Tt(S)}}let u=Date.now()-s;await a.waitForLoad($t(r,5e3));let l=c?.headers??{},p=c?.status??0,d=(await a.content()).slice(0,Qc),m=(await a.inlineScripts()).filter(S=>kn(S.type)).map(S=>S.text).join(`
|
|
839
|
+
`),h=await a.evaluate(nl).catch(()=>null)??{},g=h.nativeApi===!0,f=g?await ml(a,n,r):null,y=o?await gl(a,r):null;return{finalUrl:a.url(),navMs:u,blocked:Wo(p,l,d),nativeApi:g,nativeToolCount:f,originTrialTokens:[..._o(l["origin-trial"]),...Array.isArray(h.metaTokens)?h.metaTokens:[]],permissionsPolicy:l["permissions-policy"]??null,html:d,inlineJs:m,scripts:a.collectedScripts(),screenshot:y,loadError:null}}catch(c){return{...i,navMs:Date.now()-s,loadError:Tt(c)}}finally{await a?.close()}}async function ul(e,t,n,r,o){let s=null;try{s=await e.newContext({initScripts:[Oo],entryUrl:t,viewport:Zo});try{await s.goto(t,$t(r,qo))}catch(u){return{snapshot:null,declarative:null,quietMs:0,loadError:Tt(u)}}let i=await dl(s,n,r,o),a=await s.evaluate(Qo).catch(()=>null),c=await s.evaluate(Mo).catch(()=>null);return{snapshot:a,declarative:c,quietMs:i,loadError:null}}catch(i){return{snapshot:null,declarative:null,quietMs:0,loadError:Tt(i)}}finally{await s?.close()}}async function dl(e,t,n,r){let o=Date.now(),s=Math.min(Zc[t],Math.max(0,n-o)),i=Math.min(Xo[t],s),a=null,c=o,u=!1;for(;Date.now()-o<s;){let l=await e.evaluate(ol).catch(()=>null);typeof l=="string"&&/^[1-9]\d*:/.test(l)&&(u=!0),l!==a&&(a=typeof l=="string"?l:null,c=Date.now(),r&&await hl(e,r));let p=Date.now();if(pl({elapsedMs:p-o,quietMs:p-c,hasRegistered:u,initialWaitMs:i,maxWaitMs:s})||(await ns(Math.min(Yo,Math.max(0,n-Date.now()))),Date.now()>=n))break}return Date.now()-o}function pl(e){return e.elapsedMs>=e.maxWaitMs?!0:e.hasRegistered?e.quietMs>=zc:e.elapsedMs>=e.initialWaitMs}async function ml(e,t,n){let r=Date.now(),o=Math.min(Xo[t],Math.max(0,n-r)),s=null;for(;Date.now()-r<o;){let i=await e.evaluate(rl).catch(()=>null);if(typeof i=="number"&&Number.isSafeInteger(i)&&i>=0&&(s=i,i>0))return i;if(await ns(Math.min(Yo,Math.max(0,n-Date.now()))),Date.now()>=n)break}return s}async function hl(e,t){let n=await e.evaluate(Qo).catch(()=>null);n&&t(es(n.tools,e.url()))}async function fl(e,t,n,r,o){let s=Date.now(),i=s+Vc,a=await ll(e,t,n,i,r),u=a.loadError!==null||a.blocked?{snapshot:null,declarative:null,quietMs:0,loadError:null}:await ul(e,t,n,i,o),l=a.loadError??u.loadError,p=u.snapshot,d=(u.declarative?.forms??[]).filter(te=>te.toolName.trim()!==""),m=a.finalUrl||t,h=p?es(p.tools,m):[],g=sl(d,m),f=[...h,...g],y=yl(a.html,a.inlineJs,a.scripts),S=Ro(a.originTrialTokens,Ko(m)??Ko(t)??"",new Date),b={loadError:l,blocked:a.blocked,nativeApi:a.nativeApi,nativeToolCount:a.nativeToolCount,declarativeToolCount:g.length,toolCount:h.length,shimTakenOver:(p?.takenOver.length??0)>0,staticSignals:y},D=ko(b);return{page:{url:t,finalUrl:m,verdict:D,status:To(D,f),tools:f,declarativeFormCount:g.length,consumer:{nativeApi:a.nativeApi,nativeToolCount:a.nativeToolCount,originTrial:S,permissionsPolicy:a.permissionsPolicy,iframeAllow:cl(a.permissionsPolicy)},staticSignals:y,apiSurface:{toolchangeEvents:p?.toolchangeEvents??0,provideContextCalls:p?.provideContextCalls??0,registrationErrors:al(p)},timing:{navMs:a.navMs,quietMs:u.quietMs,totalMs:Date.now()-s},error:l},screenshot:a.blocked?null:a.screenshot}}async function ts(e){let{url:t,endpoint:n,mode:r="fast",screenshot:o=!0,onTools:s}=e,i=Date.now(),a=new Date().toISOString(),c=await Rt.connect(n);try{let u=await fl(c,t,r,o,s);return{url:t,pages:[u.page],chromeVersion:c.product,shimVersion:Re,capturedAt:a,durationMs:Date.now()-i,screenshot:u.screenshot}}finally{c.close()}}async function gl(e,t){let n=await e.screenshot(el,$t(t,5e3));if(!n||n.byteLength===0||n.byteLength>tl)return null;let r=e.viewportSize();return{data:n.toString("base64"),mimeType:"image/jpeg",width:r?.width??0,height:r?.height??0}}function yl(e,t,n){if(!e)return Go;try{return Ho(e,t,n)}catch{return Go}}function Ko(e){try{return new URL(e).origin}catch{return null}}function Tt(e){return(e instanceof Error?e.message:String(e)).split(`
|
|
840
|
+
`)[0].slice(0,300)}function $t(e,t){return Math.max(250,Math.min(t,e-Date.now()))}function ns(e){return new Promise(t=>setTimeout(t,e))}var os=require("child_process"),oe=require("fs"),ss=require("os"),$n=require("path");var is=9222;async function as(e){if(e)try{return{ok:!0,endpoint:await vn(e),close:async()=>{},launched:!1}}catch(t){let n=Tn(t);return{ok:!1,message:[`No debuggable Chrome answered at ${e}.`,...n.startsWith("no debuggable Chrome answered")?[]:[n],"",...wl(is)].join(`
|
|
841
|
+
`)}}try{let t=await kl();return{ok:!0,endpoint:t.endpoint,close:t.close,launched:!0}}catch(t){return{ok:!1,message:Tn(t)}}}function cs(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(`
|
|
842
|
+
`):null}function wl(e){return["The audit drives a Chrome you already have; it never downloads one.","Start one with a debugging port and a scratch profile:","",` ${ls(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 ls(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 Tn(e){return e instanceof M||e instanceof Error?e.message:String(e)}function bl(){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 Sl(){for(let e of bl())try{if((0,oe.statSync)(e).isFile())return e}catch{}return null}var vl=["--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 Al(){return process.env.AX_WEBMCP_NO_SANDBOX==="1"}var rs=2e4,xl=3e3,El=4,Rl=150;function _l(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 kl(){let e=Sl();if(!e)throw new M(Cl());let t=(0,oe.mkdtempSync)((0,$n.join)((0,ss.tmpdir)(),"ax-webmcp-")),n=(0,os.spawn)(e,[...vl,...Al()?["--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 _l(n,xl),await $l(t)};process.once("SIGINT",r),process.once("SIGTERM",r);try{let s=await Tl(t,n);return{endpoint:await vn(`127.0.0.1:${s}`),close:o}}catch(s){throw await o(),s instanceof M?s:new M(Tn(s))}}async function Tl(e,t){let n=(0,$n.join)(e,"DevToolsActivePort"),r=Date.now()+rs;for(;Date.now()<r;){if(t.exitCode!==null)throw new M(`Chrome exited with code ${t.exitCode} before it was ready.`);try{let o=(0,oe.readFileSync)(n,"utf8").split(`
|
|
843
|
+
`)[0]?.trim(),s=Number(o);if(Number.isInteger(s)&&s>0)return s}catch{}await new Promise(o=>setTimeout(o,100))}throw new M(`Chrome did not publish a debugging port within ${rs/1e3}s.`)}async function $l(e){for(let t=0;t<El;t++){try{if((0,oe.rmSync)(e,{recursive:!0,force:!0}),!(0,oe.existsSync)(e))return}catch{}await new Promise(n=>setTimeout(n,Rl))}try{(0,oe.rmSync)(e,{recursive:!0,force:!0})}catch{}}function Cl(){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:","",` ${ls(is)}`].join(`
|
|
844
|
+
`)}var us="https://ora.ai",Pl=12e4,W=class extends Error{code;retryAfterMs;payload;constructor(t,n={}){super(t),this.name="WebmcpIngestError",this.code=n.code??null,this.retryAfterMs=n.retryAfterMs??null,this.payload=n.payload}},ds=4*1024*1024,ps=10,ms=100,hs=32768,fs=4096,gs=512;function ys(e){if(e.shimVersion!==Re)return`this build captures with shim version ${e.shimVersion}, which is not the version it was built against (${Re})`;if(e.pages.length>ps)return`capture covers ${e.pages.length} pages; the limit is ${ps}`;for(let t of e.pages){if(t.tools.length>ms)return`${t.url} registered ${t.tools.length} tools; the limit is ${ms} per page`;for(let n of t.tools){if(n.name.length>gs)return`tool name on ${t.url} is ${n.name.length} characters; the limit is ${gs}`;if(n.description.length>fs)return`description for "${n.name}" is ${n.description.length} characters; the limit is ${fs}`;for(let[r,o]of[["inputSchema",n.inputSchema],["annotations",n.annotations]]){let s=Il(o);if(s===null)return`${r} for "${n.name}" could not be serialized (a cycle, or a value JSON cannot carry)`;if(s.length>hs)return`${r} for "${n.name}" serializes to ${s.length} characters; the limit is ${hs}`}}}return null}function ws(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 Il(e){try{return JSON.stringify(e)??"null"}catch{return null}}async function bs(e,t,n={}){let r=(n.baseUrl??process.env.ORA_API_URL??us).replace(/\/+$/,"");n.apiKey&&ue(r,"ORA_API_URL",us);let o=n.idleMs??Pl,s=de(o),i=()=>new W(`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")>ds)throw s.disarm(),new W(`this capture serializes to ${Math.round(Buffer.byteLength(a,"utf8")/1024)} KB; the ingest limit is ${ds/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(u){throw s.disarm(),s.tripped()?i():new W(`ora ingest request failed: ${u instanceof Error?u.message:String(u)}`)}if(!c.ok||!c.body)throw s.disarm(),await Ol(c);return Ml(c,s,n,i)}async function Ol(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 W(`ora rate limit exceeded${s} (10/min and 20 per 24h per IP). An ora partner or scan API key lifts the daily limit: set ORA_PARTNER_API_KEY or pass --api-key.`,{code:n??"RATE_LIMITED",retryAfterMs:o,payload:t})}return n==="SHIM_VERSION_MISMATCH"?new W(`This ax build captures with a shim ora no longer scores, so the audit was refused.
|
|
703
845
|
Upgrade with \`npm i -g ax@latest\` (or \`npx ax@latest webmcp-audit \u2026\`) and run it again.
|
|
704
846
|
|
|
705
|
-
ora said: ${t?.error??"shim version mismatch"}`,{code:n}):e.status===503?new
|
|
847
|
+
ora said: ${t?.error??"shim version mismatch"}`,{code:n,payload:t}):e.status===503?new W(`ora cannot score right now: ${Nl(t?.error??"scoring is unavailable")} Nothing was spent against your rate limit; try again shortly.`,{code:n??"SCORING_UNAVAILABLE",payload:t}):new W(`ora ingest failed: ${t?.error??await er(e)}`,{code:n,payload:t})}async function Ml(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,`
|
|
706
848
|
`);let c=s.indexOf(`
|
|
707
849
|
|
|
708
|
-
`);for(;c!==-1;){let
|
|
850
|
+
`);for(;c!==-1;){let u=Ll(s.slice(0,c));if(s=s.slice(c+2),c=s.indexOf(`
|
|
709
851
|
|
|
710
|
-
`),!
|
|
852
|
+
`),!u)continue;let l;try{l=JSON.parse(u)}catch{continue}if(n.onEvent?.(l),l.type==="error")throw new W(`ora audit failed: ${l.message}`,{code:l.status,payload:l});if(l.type==="done"){i=l.audit;break e}}}}catch(a){throw t.tripped()?r():a instanceof W?a:new W(`ora ingest stream failed: ${a instanceof Error?a.message:String(a)}`)}finally{t.disarm()}if(!i)throw new W("ora ingest stream ended before the audit completed");return i}function Nl(e){let t=e.trim();return/[.!?]$/.test(t)?t:`${t}.`}function Ll(e){let t=[];for(let n of e.split(`
|
|
711
853
|
`))n.startsWith("data:")&&t.push(n.slice(5).replace(/^ /,""));return t.join(`
|
|
712
|
-
`)}var
|
|
713
|
-
${
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
`),K.BELOW_MIN_SCORE}return K.OK}function Ya(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 Vr(){if(typeof process.loadEnvFile!="function")return!1;try{return process.loadEnvFile(),!0}catch{return!1}}var V="ax",Va={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 Ln({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"]})}},Xa={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})}},za={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 on the Haiku model ora's roster lists"},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, then ORA_SCAN_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"]})}},Qa={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})}},Za={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})}},ec={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 partner or scan API key that lifts the daily ingest limit; also read from ORA_PARTNER_API_KEY, then ORA_SCAN_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 Yr({url:e.url,json:!!e.json,showPassing:!!e["show-passing"],minScore:e["min-score"],chromeEndpoint:e["chrome-endpoint"],apiKey:e["api-key"]})}};function zr(){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 (needs a platform key)")}`,` 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 partner or scan API key that lifts the daily ingest limit; also read from ORA_PARTNER_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("exit codes: 0 ok \xB7 1 below --min-score \xB7 2 usage \xB7 3 API error")}`,"",` ${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, then ORA_SCAN_API_KEY")}`,` --agent <id> ${t("Agent to run (default: cas-haiku \u2014 Claude Code on the Haiku model ora's roster lists)")}`,` --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 and task, 20 runs/24h per IP")}`,` ${t("exit codes: 0 run succeeded (any verdict) \xB7 1 run failed \xB7 2 usage \xB7 3 API unreachable/rate-limited")}`,"",` ${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("exit codes: 0 written \xB7 2 usage or files already exist \xB7 3 API error")}`,"",` ${t("skill options:")}`,` --install ${t("Write <dir>/<name>/SKILL.md instead of printing it")}`,` --dir <path> ${t("Install directory (default .claude/skills)")}`,` --json ${t("Print the raw registry index as JSON")}`,"",` ${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(`
|
|
717
|
-
|
|
854
|
+
`)}var A=V(Y(),1);var Cn=12,jl=["fail","warning","unmeasured","na","pass"],Pn={fail:["\u2716",A.default.red],warning:["\u25B2",A.default.yellow],unmeasured:["?",A.default.magenta],na:["\u2013",A.default.dim],pass:["\u2714",A.default.green]},Ul={fail:"Failing",warning:"Warnings",unmeasured:"Not measured",na:"Not applicable",pass:"Passing"},Dl=["shared-experience","task-completion","tool-quality","trust"],Fl={"shared-experience":"Shared experience","task-completion":"Task completion","tool-quality":"Tool quality",trust:"Trust"};function Ss(e,t={}){let n=me(80,120);return["",...Wl(e,n),"",...Jl(e.availability,n),"",...Hl(e,n),"",...Kl(e),"",...Yl(e.findings,n,t.showPassing===!0),...zl(e.simulation,n),"",...Zl(e,n)]}function Wl(e,t){let n=[` ${A.default.bold(N(e.url))}`],r=`${e.toolCount} tool${e.toolCount===1?"":"s"}`,o=[Bl(e.verdict),r,`Chrome ${N(e.chromeVersion)}`];return e.error&&o.push(A.default.red(N(e.error))),n.push(` ${A.default.dim(o.join(" \xB7 "))}`),n.map(s=>vs(s,t))}function Bl(e){switch(e){case"active":return A.default.green("active");case"testing-only":case"declared-inactive":case"api-empty":return A.default.yellow(e);case"blocked":case"load-error":return A.default.red(e);default:return A.default.dim(e)}}function Jl(e,t){let[n,r]=e.status==="ready"?["agent-ready",A.default.green]:e.status==="not-ready"?["not agent-ready",A.default.red]:["availability unknown",A.default.yellow],o=[` ${r(A.default.bold(n))}`];for(let s of e.reasons)o.push(...G(N(s.detail),t-4).map(i=>` ${A.default.dim(i)}`));return o}function Hl(e,t){let n=e.score===null?"\u2014":String(e.score),r=[` ${A.default.bold(`${n}/100`)} ${Gl(e)}`],o=e.availability.reasons.some(s=>s.id==="declarative-only");return e.grade===null&&e.score!==null&&!o&&r.push(...G(`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(s=>` ${A.default.dim(s)}`)),r}function Gl(e){return e.grade!==null?A.default.bold(A.default.green(`grade ${e.grade}`)):A.default.dim("grade withheld")}function Kl(e){let t=[` ${A.default.bold("Pillars")}`];for(let n of Dl){let r=e.categoryScores[n]??0,o=$o[n],s=e.applicableCategories.includes(n),i=s?ql(r):A.default.dim("\u2591".repeat(Cn)),a=s?`weight ${o}`:`weight ${o} \xB7 nothing measured`;t.push(` ${Fl[n].padEnd(18)} ${i} ${String(r).padStart(3)}% ${A.default.dim(a)}`)}return t}function ql(e){let t=Math.round(Math.min(100,Math.max(0,e))/100*Cn);return`${(e>=75?A.default.green:e>=40?A.default.yellow:A.default.red)("\u2588".repeat(t))}${A.default.dim("\u2591".repeat(Cn-t))}`}function Yl(e,t,n){let r=[` ${A.default.bold("Checks")}`];for(let o of jl){let s=e.filter(i=>i.status===o);if(s.length!==0){if(o==="pass"&&!n){r.push(` ${A.default.dim(`${s.length} passing (--show-passing to list)`)}`);continue}r.push("",` ${A.default.bold(Ul[o])} (${s.length})`);for(let i of s)r.push(...Xl(i,t))}}return e.length===0&&r.push(` ${A.default.dim("no checks reported")}`),r}function Xl(e,t){let[n,r]=Pn[e.status],o=Vl(e.checkId),i=[` ${r(n)} ${o}${e.toolName?A.default.dim(` ${N(e.toolName)}`):""}`];return e.details&&i.push(...G(N(e.details),t-10).map(a=>` ${A.default.dim(a)}`)),e.evidence&&i.push(...G(N(e.evidence),t-10).map(a=>` ${A.default.dim(a)}`)),i}function Vl(e){return Co[e]?.title??e}function zl(e,t){if(!e)return[];let n=["",` ${A.default.bold("Tool selection")}`];if(e.skipped)return n.push(...G(N(e.skipReason??"The selection simulation did not run."),t-4).map(o=>` ${A.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 ${A.default.dim(N(e.model))}`);for(let o of e.steps){let[s,i]=o.ok?Pn.pass:Pn.fail,a=o.chosenTool?N(o.chosenTool):A.default.dim("nothing");n.push(` ${i(s)} ${vs(N(o.intent),t-30)} ${A.default.dim("\u2192")} ${a}`)}return n}function Zl(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?G(n,t-4).map(r=>` ${A.default.dim(r)}`):[]}function vs(e,t){return e.length>t?`${e.slice(0,t-1)}\u2026`:e}var ie={OK:0,BELOW_MIN_SCORE:1,USAGE:2,API:3};function Ql(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 eu(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}}function ce(e,t=e.minScore){return["webmcp-audit",e.url.trim(),...e.json?["--json"]:[],...e.showPassing?["--show-passing"]:[],...t!==void 0?["--min-score",t]:[],...e.chromeEndpoint?["--chrome-endpoint",e.chromeEndpoint]:[],...e.apiKey?["--api-key",C("key")]:[]]}function tu(e,t){return t instanceof W&&t.code==="SHIM_VERSION_MISMATCH"?{call:"npm i -g ax@latest",why:"this ax captures with a shim ora no longer scores; then run it again"}:t instanceof W&&t.code==="RATE_LIMITED"?{call:w(ce(e)),why:"after the wait the message names"}:{call:w(ce(e)),why:"retry; ora may be briefly unreachable"}}function As(e,t,n){return Je(t)||n?{call:w(ce(e)),why:"after you fix the failing checks above, run it again"}:{call:w(["audit",new URL(t).host,...e.json?["--json"]:[]]),why:"the readiness audit of the whole site"}}async function xs(e){let t=(d,m,h,g)=>(j(d,{json:e.json,display:h,served:g}),m),n=Ql(e.url);if(!n)return t({code:"INVALID_TARGET",message:`Not an auditable URL: ${JSON.stringify(e.url)}`,next:{call:w(["webmcp-audit","http://localhost:3000",...e.json?["--json"]:[]])}},ie.USAGE,d=>`${d}
|
|
855
|
+
Pass the page you want audited, e.g. http://localhost:3000`);let r=eu(e.minScore);if(r.error)return t({code:"INVALID_FLAG",message:r.error,next:{call:w(ce(e,"70"))}},ie.USAGE);let o=await as(e.chromeEndpoint);if(!o.ok){let d=ce({...e,chromeEndpoint:void 0});return t({code:"NO_CHROME",message:o.message,next:{call:w([...d,"--chrome-endpoint",C("host:port")]),why:"a Chrome started with --remote-debugging-port, or install Chrome"}},ie.USAGE)}e.json||I.start(o.launched?`Starting Chrome and capturing ${n}`:`Capturing ${n}`);let s;try{s=await ts({url:n,endpoint:o.endpoint,onTools:d=>{e.json||I.update(`Capturing ${n} \u2014 ${d.length} tools`)}})}catch(d){I.stop();let m=d instanceof Error?d.message:String(d);return t({code:"CAPTURE_FAILED",message:m,next:{call:w(ce(e)),why:"retry the capture"}},ie.API,h=>`Capture failed: ${h}`)}finally{await o.close()}let i=s.pages[0];if(i?.error)return I.stop(),t({code:"PAGE_UNREACHABLE",message:`Could not capture ${n}: ${i.error}`,next:{call:w(ce(e)),why:"start the dev server first"}},ie.USAGE,d=>`${d}
|
|
856
|
+
Is the dev server running?`);let a=ys(s);if(a)return I.stop(),t({code:"CAPTURE_REFUSED",message:`ora would refuse this capture: ${a}`,next:{call:w(ce(e)),why:"after you fix what the message names"}},ie.USAGE);let{capture:c,droppedScreenshot:u}=ws(s);e.json||I.update("Scoring with ora");let l;try{l=await bs(n,c,{apiKey:e.apiKey||process.env.ORA_PARTNER_API_KEY||process.env.ORA_SCAN_API_KEY||void 0,onEvent:d=>{e.json||I.update(nu(d))}})}catch(d){I.stop();let m=d instanceof Error?d.message:String(d),h=d instanceof W;return t({code:h&&d.code||"SCORING_FAILED",message:m,next:tu(e,d)},ie.API,g=>h?g:`Scoring failed: ${g}`,h?d.payload:void 0)}if(I.stop(),e.json)console.log(JSON.stringify(l,null,2));else for(let d of Ss(l,{showPassing:e.showPassing}))console.log(d);u&&console.error("Note: the screenshot exceeded ora's 2 MB limit and was not sent, so page-experience could not be graded.");let p=cs(s);if(p&&console.error(`
|
|
857
|
+
${p}`),r.value!==void 0){if(l.score===null)return e.json||console.error(`
|
|
858
|
+
ora returned no score, so --min-score cannot be evaluated.`),T({call:w(ce(e)),why:"ora returned no score to gate on; retry, or drop --min-score"},{stderr:!0}),ie.API;if(l.score<r.value)return e.json||console.log(`
|
|
859
|
+
Score ${l.score} is below the required minimum ${r.value}
|
|
860
|
+
`),T(As(e,n,!0),{stderr:e.json}),ie.BELOW_MIN_SCORE}return T(As(e,n,!1),{stderr:e.json}),ie.OK}function nu(e){switch(e.type){case"phase":return`Scoring with ora \u2014 ${e.phase}`;case"tool-discovered":return`Scoring with ora \u2014 found ${N(e.tool.name)}`;case"finding":return`Scoring with ora \u2014 ${e.finding.checkId}`;case"simulation-step":return`Scoring with ora \u2014 simulating "${N(e.step.intent)}"`;default:return"Scoring with ora"}}var se="ax",Rs={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 Gr({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"]})}},_s={meta:{name:"deep-journey",description:"Deprecated: now ax journey --domain <url>. Runs a real AI agent at a site on a curated task, or with a partner API key a free-text one, via ora's public API (exit codes: 0 ok, 1 run failed, 2 usage, 3 API error)",hidden:!0},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 on the Haiku model ora's roster lists"},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, then ORA_SCAN_API_KEY"},"no-stream":{type:"boolean",description:"Hide the live trajectory view and print only the final result",default:!1}},async run({args:e}){let t=e.task,n=e.intent,r=e.agent,o=w(["journey",...t?[t]:[],"--domain",e.url,...n&&!t?["--intent",n]:[],...r?["--agent",r]:[]]);console.error(_e.default.dim(`ax deep-journey is now ${o}. This name keeps working and will be removed in a future major release.`)),process.exitCode=await vt({url:e.url,intent:e.intent,task:e.task,apiKey:e["api-key"],agent:e.agent,json:!!e.json,noStream:fn(e),via:"deep-journey"})}},ks={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 co({domain:e.domain,out:e.out,force:!!e.force,json:!!e.json})}},Ts={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 Ao({name:e.name,install:!!e.install,dir:e.dir,json:!!e.json})}},$s={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 partner or scan API key that lifts the daily ingest limit; also read from ORA_PARTNER_API_KEY, then ORA_SCAN_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 xs({url:e.url,json:!!e.json,showPassing:!!e["show-passing"],minScore:e["min-score"],chromeEndpoint:e["chrome-endpoint"],apiKey:e["api-key"]})}},Cs={meta:{name:"learn",description:"Print the ax workflow from ora's skill: score a site, read the report, run a journey, read its result"},args:{},async run(){process.exitCode=await So()}},ye=()=>`ora.ai at ${$e()} (set by ORA_API_URL)`,In=()=>`ora's platform API at ${it()} (set by ORA_PLATFORM_URL), with ORA_API_KEY`;function Ps(){let e=_e.default.dim;return[` ${e("Workflow:")}`,` 1. ax audit <domain> ${e("score the site and list what to fix")}`,` 2. read the report ${e("start with its Top fixes, ranked by ora")}`,` 3. ax journey --domain <domain> ${e("send a real agent at the site on a task")}`,` 4. read its result ${e("whether the agent finished, and where it got stuck")}`,` ${e("Every result and error ends with a Next: line, the call to make next.")}`,` ${e("ax learn prints these steps from ora's skill.")}`,""]}var ru=new Map([[Rs,{talksTo:()=>`${ye()}; with --tunnel ora, also ${In()}`,usageNext:{call:w(["audit",C("domain")])}}],[$s,{talksTo:()=>`a Chrome on this machine for the capture, then ${ye()} to score it`,usageNext:{call:w(["webmcp-audit","http://localhost:3000"])}}],[_s,{talksTo:ye,usageNext:{call:w(["journey","--domain",C("domain")])}}],[gn,{talksTo:()=>`${ye()} with no goal of your own (free); ${In()} with a goal`,usage:go,usageNext:{call:w(["journey","--domain",C("domain")]),why:"ora picks the task"}}],[ks,{talksTo:ye,usageNext:{call:w(["generate-files",C("domain")])}}],[Ts,{talksTo:()=>`ora's skill registry on ${ye()}`,usageNext:{call:"ax skill"}}],[Cs,{talksTo:()=>`ora's skill registry on ${ye()}`,usageNext:{call:"ax learn"}}]]);function ou(e){return[` ${_e.default.dim("Talks to:")} ${e.talksTo()}`,"",...Ps()].join(`
|
|
861
|
+
`)}function Is(){let e=_e.default.green("$"),t=_e.default.dim;return["",` ${_e.default.bold(se)} ${t(`v${Fe.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")}`,` journey ${t("--domain <d>")} ${t("Send a real agent at a site on one of ora's curated tasks, drawn live; free, no key")}`,` journey ${t("<goal>")} ${t("The same on a goal of your own (needs a platform key)")}`,` 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")}`,` learn ${t("Print the ax workflow from ora's skill")}`,"",` ${t("Talks to:")}`,` ${ye()}`,` ${t("audit, webmcp-audit, journey with no goal, generate-files, skill, learn")}`,` ${In()}`,` ${t("journey with a goal, and audit --tunnel ora")}`,"",` ${t("Examples:")}`,` ${e} ${se} audit https://docs.example.com`,` ${e} ${se} audit https://docs.example.com --min-score 70 ${t("# CI gate")}`,` ${e} ${se} audit https://docs.example.com --json`,` ${e} ${se} audit localhost:3000 --tunnel ora ${t("# audit a local dev server")}`,` ${e} ${se} webmcp-audit http://localhost:3000`,` ${e} ${se} journey --domain stripe.com --intent pricing ${t("# free, no key")}`,` ${e} ${se} journey "Find the API docs and how to authenticate" --domain stripe.com`,` ${e} ${se} generate-files example.com --out public`,` ${e} ${se} learn`,"",` ${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 partner or scan API key that lifts the daily ingest limit; also read from ORA_PARTNER_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("exit codes: 0 ok \xB7 1 below --min-score \xB7 2 usage \xB7 3 API error")}`,"",` ${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("exit codes: 0 written \xB7 2 usage or files already exist \xB7 3 API error")}`,"",` ${t("skill options:")}`,` --install ${t("Write <dir>/<name>/SKILL.md instead of printing it")}`,` --dir <path> ${t("Install directory (default .claude/skills)")}`,` --json ${t("Print the raw registry index as JSON")}`,"",` ${t("journey options, free (no goal of your own):")}`,` --domain <d> ${t("Site the agent works on (e.g. stripe.com)")}`,` --intent <id> ${t("Curated task id, e.g. pricing, signup, api-docs (server default when omitted)")}`,` --agent <id> ${t("Agent to run (default: cas-haiku, Claude Code on the Haiku model ora's roster lists)")}`,` --api-key <k> ${t("ora partner API key: a goal of your own + 1000 runs/24h; also read from ORA_PARTNER_API_KEY, then ORA_SCAN_API_KEY")}`,` --no-stream ${t("Hide the live trajectory view and print only the final result")}`,` --json ${t("Print the terminal run detail as JSON")}`,` ${t("public caps: 100 runs/24h per target and task, 20 runs/24h per IP")}`,` ${t("exit codes: 0 run succeeded (any verdict) \xB7 1 run failed \xB7 2 usage \xB7 3 API unreachable/rate-limited")}`,` ${t("ax deep-journey <url> still runs this, and will be removed in a future major release")}`,"",` ${t("journey options, on ora's platform (a goal of your own):")}`,` --domain <d> ${t("Site the agent works on (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)")}`,"",...Ps()].join(`
|
|
862
|
+
`)}var Es={meta:{name:se,version:Fe.version,description:"Score any site's agent readiness \u2014 and watch real AI agents navigate it"},subCommands:{audit:Rs,"webmcp-audit":$s,"deep-journey":_s,journey:gn,skill:Ts,"generate-files":ks,learn:Cs},setup(){process.argv[2]||(console.log(Is()),process.exit(0))}};Xn();var su=new Set(["--help","-h"]);Kn(Es,{showUsage:async(e,t)=>{let n=process.argv.slice(2).some(o=>su.has(o)),r=ru.get(e);if(e===Es)console.log(Is());else if(n&&r){let o=r.usage?r.usage():(await Lt(e,t)).trimEnd();console.log(`${o}
|
|
863
|
+
|
|
864
|
+
${ou(r)}`)}else r?.usage?console.log(`${r.usage()}
|
|
865
|
+
`):await Nt(e,t);n||T(r?.usageNext??{call:w(["audit",C("domain")])},{stderr:!0})}});
|