ax 0.6.0 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +9 -4
- package/README.md +115 -3
- package/dist/api/deep-journey.d.ts +7 -1
- package/dist/index.cjs +1 -0
- package/dist/index.js +1 -0
- package/dist/main.cjs +593 -36
- package/package.json +6 -2
package/dist/main.cjs
CHANGED
|
@@ -1,40 +1,597 @@
|
|
|
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
|
-
`))}function
|
|
8
|
-
`);let d=
|
|
2
|
+
"use strict";var Ln=Object.create;var at=Object.defineProperty;var Wn=Object.getOwnPropertyDescriptor;var Dn=Object.getOwnPropertyNames;var Bn=Object.getPrototypeOf,Un=Object.prototype.hasOwnProperty;var Jn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Fn=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Dn(t))!Un.call(e,r)&&r!==n&&at(e,r,{get:()=>t[r],enumerable:!(o=Wn(t,r))||o.enumerable});return e};var U=(e,t,n)=>(n=e!=null?Ln(Bn(e)):{},Fn(t||!e||!e.__esModule?at(n,"default",{value:e,enumerable:!0}):n,e));var D=Jn((us,Pe)=>{"use strict";var pe=process||{},ft=pe.argv||[],de=pe.env||{},ir=!(de.NO_COLOR||ft.includes("--no-color"))&&(!!de.FORCE_COLOR||ft.includes("--color")||pe.platform==="win32"||(pe.stdout||{}).isTTY&&de.TERM!=="dumb"||!!de.CI),sr=(e,t,n=e)=>o=>{let r=""+o,i=r.indexOf(t,e.length);return~i?e+ar(r,t,n,i)+t:e+r+t},ar=(e,t,n,o)=>{let r="",i=0;do r+=e.substring(i,o)+n,i=o+t.length,o=e.indexOf(t,i);while(~o);return r+e.substring(i)},yt=(e=ir)=>{let t=e?sr:()=>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")}};Pe.exports=yt();Pe.exports.createColors=yt});var Hn=/\d/,Gn=["-","_","/","."];function qn(e=""){if(!Hn.test(e))return e!==e.toLowerCase()}function ct(e,t){let n=t??Gn,o=[];if(!e||typeof e!="string")return o;let r="",i,s;for(let a of e){let c=n.includes(a);if(c===!0){o.push(r),r="",i=void 0;continue}let l=qn(a);if(s===!1){if(i===!1&&l===!0){o.push(r),r=a,i=l;continue}if(i===!0&&l===!1&&r.length>1){let u=r.at(-1);o.push(r.slice(0,Math.max(0,r.length-1))),r=u+a,i=l;continue}}r+=a,i=l,s=c}return o.push(r),o}function Kn(e){return e?e[0].toUpperCase()+e.slice(1):""}function Vn(e){return e?e[0].toLowerCase()+e.slice(1):""}function Yn(e,t){return e?(Array.isArray(e)?e:ct(e)).map(n=>Kn(t?.normalize?n.toLowerCase():n)).join(""):""}function ne(e,t){return Vn(Yn(e||"",t))}function se(e,t){return e?(Array.isArray(e)?e:ct(e)).map(n=>n.toLowerCase()).join(t??"-"):""}function lt(e){return se(e||"","_")}var pt=require("util");function re(e){return Array.isArray(e)?e:e===void 0?[]:[e]}function Re(e,t=""){let n=[];for(let o of e)for(let[r,i]of o.entries())n[r]=Math.max(n[r]||0,i.length);return e.map(o=>o.map((r,i)=>t+r[i===0?"padStart":"padEnd"](n[i])).join(" ")).join(`
|
|
3
|
+
`)}function _(e){return typeof e=="function"?e():e}var J=class extends Error{code;constructor(e,t){super(e),this.name="CLIError",this.code=t}};function Xn(e=[],t={}){let n=new Set(t.boolean||[]),o=new Set(t.string||[]),r=t.alias||{},i=t.default||{},s=new Map,a=new Map;for(let[m,y]of Object.entries(r)){let x=y;for(let T of x)s.set(m,T),a.has(T)||a.set(T,[]),a.get(T).push(m),s.set(T,m),a.has(m)||a.set(m,[]),a.get(m).push(T)}let c={};function l(m){if(n.has(m))return"boolean";let y=a.get(m)||[];for(let x of y)if(n.has(x))return"boolean";return"string"}function u(m){if(o.has(m))return!0;let y=a.get(m)||[];for(let x of y)if(o.has(x))return!0;return!1}let p=new Set([...n,...o,...Object.keys(r),...Object.values(r).flat(),...Object.keys(i)]);for(let m of p)c[m]||(c[m]={type:l(m),default:i[m]});for(let[m,y]of s.entries())m.length===1&&c[y]&&!c[y].short&&(c[y].short=m);let g=[],d={};for(let m=0;m<e.length;m++){let y=e[m];if(y==="--"){g.push(...e.slice(m));break}if(y.startsWith("--no-")){let x=y.slice(5);d[x]=!0;continue}g.push(y)}let f;try{f=(0,pt.parseArgs)({args:g,options:Object.keys(c).length>0?c:void 0,allowPositionals:!0,strict:!1})}catch{f={values:{},positionals:g}}let h={_:[]};h._=f.positionals;for(let[m,y]of Object.entries(f.values)){let x=y;l(m)==="boolean"&&typeof y=="string"?x=y!=="false":u(m)&&typeof y=="boolean"&&(x=""),h[m]=x}for(let[m]of Object.entries(d)){h[m]=!1;let y=s.get(m);y&&(h[y]=!1);let x=a.get(m);if(x)for(let T of x)h[T]=!1}for(let[m,y]of s.entries())h[m]!==void 0&&h[y]===void 0&&(h[y]=h[m]),h[y]!==void 0&&h[m]===void 0&&(h[m]=h[y]),h[m]!==h[y]&&i[y]===h[y]&&(h[y]=h[m]);return h}var zn=(()=>{let e=globalThis.process?.env??{};return e.NO_COLOR==="1"||e.TERM==="dumb"||e.TEST||e.CI})(),ue=(e,t=39)=>n=>zn?n:`\x1B[${e}m${n}\x1B[${t}m`,ae=ue(1,22),j=ue(36),le=ue(90),ce=ue(4,24);function Qn(e,t){let n={boolean:[],string:[],alias:{},default:{}},o=mt(t);for(let a of o){if(a.type==="positional")continue;a.type==="string"||a.type==="enum"?n.string.push(a.name):a.type==="boolean"&&n.boolean.push(a.name),a.default!==void 0&&(n.default[a.name]=a.default),a.alias&&(n.alias[a.name]=a.alias);let c=ne(a.name),l=se(a.name);if(c!==a.name||l!==a.name){let u=re(n.alias[a.name]||[]);c!==a.name&&!u.includes(c)&&u.push(c),l!==a.name&&!u.includes(l)&&u.push(l),u.length>0&&(n.alias[a.name]=u)}}let r=Xn(e,n),[...i]=r._,s=new Proxy(r,{get(a,c){return a[c]??a[ne(c)]??a[se(c)]}});for(let[,a]of o.entries())if(a.type==="positional"){let c=i.shift();if(c!==void 0)s[a.name]=c;else{if(a.default===void 0&&a.required!==!1)throw new J(`Missing required positional argument: ${a.name.toUpperCase()}`,"EARG");s[a.name]=a.default}}else if(a.type==="enum"){let c=s[a.name],l=a.options||[];if(c!==void 0&&l.length>0&&!l.includes(c))throw new J(`Invalid value for argument: ${j(`--${a.name}`)} (${j(c)}). Expected one of: ${l.map(u=>j(u)).join(", ")}.`,"EARG")}else if(a.required&&s[a.name]===void 0)throw new J(`Missing required argument: --${a.name}`,"EARG");return s}function mt(e){let t=[];for(let[n,o]of Object.entries(e||{}))t.push({...o,name:n,alias:re(o.alias)});return t}async function Zn(e){return Promise.all(e.map(t=>_(t)))}async function _e(e,t){let n=await _(e.args||{}),o=Qn(t.rawArgs,n),r={rawArgs:t.rawArgs,args:o,data:t.data,cmd:e},i=await Zn(e.plugins??[]),s,a;try{for(let u of i)await u.setup?.(r);typeof e.setup=="function"&&await e.setup(r);let l=await _(e.subCommands);if(l&&Object.keys(l).length>0){let u=gt(t.rawArgs,n),p=t.rawArgs[u];if(p){let g=await Te(l,p);if(!g)throw new J(`Unknown command ${j(p)}`,"E_UNKNOWN_COMMAND");await _e(g,{rawArgs:t.rawArgs.slice(u+1)})}else{let g=await _(e.default);if(g){if(e.run)throw new J("Cannot specify both 'run' and 'default' on the same command.","E_DEFAULT_CONFLICT");let d=await Te(l,g);if(!d)throw new J(`Default sub command ${j(g)} not found in subCommands.`,"E_UNKNOWN_COMMAND");await _e(d,{rawArgs:t.rawArgs})}else if(!e.run)throw new J("No command specified.","E_NO_COMMAND")}}typeof e.run=="function"&&(s=await e.run(r))}catch(l){a=l}let c=[];if(typeof e.cleanup=="function")try{await e.cleanup(r)}catch(l){c.push(l)}for(let l of[...i].reverse())try{await l.cleanup?.(r)}catch(u){c.push(u)}if(a)throw a;if(c.length===1)throw c[0];if(c.length>1)throw new Error("Multiple cleanup errors",{cause:c});return{result:s}}async function Ee(e,t,n){let o=await _(e.subCommands);if(o&&Object.keys(o).length>0){let r=gt(t,await _(e.args||{})),i=t[r],s=await Te(o,i);if(s)return Ee(s,t.slice(r+1),e)}return[e,n]}async function Te(e,t){if(t in e)return _(e[t]);for(let n of Object.values(e)){let o=await _(n),r=await _(o?.meta);if(r?.alias&&re(r.alias).includes(t))return o}}function gt(e,t){for(let n=0;n<e.length;n++){let o=e[n];if(o==="--")return-1;if(o.startsWith("-")){!o.includes("=")&&er(o,t)&&n++;continue}return n}return-1}function er(e,t){let n=e.replace(/^-{1,2}/,""),o=ne(n);for(let[r,i]of Object.entries(t))if(!(i.type!=="string"&&i.type!=="enum")&&(o===ne(r)||(Array.isArray(i.alias)?i.alias:i.alias?[i.alias]:[]).includes(n)))return!0;return!1}async function tr(e,t){try{console.log(await rr(e,t)+`
|
|
4
|
+
`)}catch(n){console.error(n)}}var nr=/^no[-A-Z]/;async function rr(e,t){let n=await _(e.meta||{}),o=mt(await _(e.args||{})),r=await _(t?.meta||{}),i=`${r.name?`${r.name} `:""}`+(n.name||process.argv[1]),s=[],a=[],c=[],l=[];for(let d of o)if(d.type==="positional"){let f=d.name.toUpperCase(),h=d.required!==!1&&d.default===void 0;a.push([j(f+Ce(d)),ut(d,h)]),l.push(h?`<${f}>`:`[${f}]`)}else{let f=d.required===!0&&d.default===void 0,h=[...(d.alias||[]).map(m=>`-${m}`),`--${d.name}`].join(", ")+Ce(d);if(s.push([j(h),ut(d,f)]),d.type==="boolean"&&(d.default===!0||d.negativeDescription)&&!nr.test(d.name)){let m=[...(d.alias||[]).map(y=>`--no-${y}`),`--no-${d.name}`].join(", ");s.push([j(m),[d.negativeDescription,f?le("(Required)"):""].filter(Boolean).join(" ")])}f&&l.push(`--${d.name}`+Ce(d))}if(e.subCommands){let d=[],f=await _(e.subCommands);for(let[h,m]of Object.entries(f)){let y=await _((await _(m))?.meta);if(y?.hidden)continue;let x=re(y?.alias),T=[h,...x].join(", ");c.push([j(T),y?.description||""]),d.push(h,...x)}l.push(d.join("|"))}let u=[],p=n.version||r.version;u.push(le(`${n.description} (${i+(p?` v${p}`:"")})`),"");let g=s.length>0||a.length>0;return u.push(`${ce(ae("USAGE"))} ${j(`${i}${g?" [OPTIONS]":""} ${l.join(" ")}`)}`,""),a.length>0&&(u.push(ce(ae("ARGUMENTS")),""),u.push(Re(a," ")),u.push("")),s.length>0&&(u.push(ce(ae("OPTIONS")),""),u.push(Re(s," ")),u.push("")),c.length>0&&(u.push(ce(ae("COMMANDS")),""),u.push(Re(c," ")),u.push("",`Use ${j(`${i} <command> --help`)} for more information about a command.`)),u.filter(d=>typeof d=="string").join(`
|
|
5
|
+
`)}function Ce(e){let t=e.valueHint?`=<${e.valueHint}>`:"",n=t||`=<${lt(e.name)}>`;return!e.type||e.type==="positional"||e.type==="boolean"?t:e.type==="enum"&&e.options?.length?`=<${e.options.join("|")}>`:n}function ut(e,t){let n=t?le("(Required)"):"",o=e.default===void 0?"":le(`(Default: ${e.default})`);return[e.description,n,o].filter(Boolean).join(" ")}async function ht(e,t={}){let n=t.rawArgs||process.argv.slice(2),o=t.showUsage||tr;try{let r=await or(e);if(r.help.length>0&&n.some(i=>r.help.includes(i)))await o(...await Ee(e,n)),process.exit(0);else if(n.length===1&&r.version.includes(n[0])){let i=typeof e.meta=="function"?await e.meta():await e.meta;if(!i?.version)throw new J("No version specified","E_NO_VERSION");console.log(i.version)}else await _e(e,{rawArgs:n})}catch(r){r instanceof J?(await o(...await Ee(e,n)),console.error(r.message)):console.error(r,`
|
|
6
|
+
`),process.exit(1)}}async function or(e){let t=await _(e.args||{}),n=new Set,o=new Set;for(let[r,i]of Object.entries(t)){n.add(r);for(let s of re(i.alias))o.add(s)}return{help:dt("help","h",n,o),version:dt("version","v",n,o)}}function dt(e,t,n,o){return n.has(e)||o.has(e)?[]:n.has(t)||o.has(t)?[`--${e}`]:[`--${e}`,`-${t}`]}var $e=U(D(),1);var Ie={name:"ax",version:"0.7.1",description:"Score any site's agent readiness and watch real AI agents navigate it \u2014 powered by ora",type:"module",packageManager:"pnpm@10.34.5",bin:{ax:"./dist/main.cjs"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"}},main:"./dist/index.cjs",types:"./dist/index.d.ts",files:["dist",".env.example"],engines:{node:">=22.4.0"},scripts:{build:"rm -rf dist && tsup && tsc -p tsconfig.lib.json","contract:gen":"node scripts/contract-gen.mjs",smoke:"node scripts/smoke.mjs","smoke:webmcp":"node scripts/smoke-webmcp.mjs","verify:pack":"node scripts/verify-pack.mjs",test:"vitest","test:ci":"vitest run --coverage","test:capture":"vitest run src/webmcp/capture.live.test.ts",lint:"biome check .","lint:fix":"biome check --write .",typecheck:"tsc --noEmit",prepublishOnly:"npm run build"},devDependencies:{"@biomejs/biome":"^2.5.7","@commitlint/cli":"^21.2.2","@commitlint/config-conventional":"^21.2.2","@types/node":"^26.2.0","@vitest/coverage-v8":"^3",citty:"^0.2.2","openapi-typescript":"^6.7.6",picocolors:"^1",tsup:"^8",typescript:"^7.0.2",vitest:"^3"},publishConfig:{access:"public"},pnpm:{onlyBuiltDependencies:["@biomejs/biome","esbuild"]},license:"MIT",homepage:"https://ora.ai",repository:{type:"git",url:"git+https://github.com/eralabs-ai/ora-cli.git"},keywords:["ai","agents","agent-readiness","agent-experience","llms.txt","ora","cli","scan"]};var Oe="1.23.0";function bt(e){let[t=0,n=0]=e.split(".").map(o=>Number.parseInt(o,10));return[t,n]}function lr(e){if(!e||!/^\d+\.\d+\.\d+$/.test(e))return!1;let[t,n]=bt(e),[o,r]=bt(Oe);return t>o||t===o&&n>r}var wt=!1;function oe(e){wt||!lr(e)||(wt=!0,process.stderr.write(`ora reports contract ${e}; this CLI was built against ${Oe}. Newer fields may be missing from the output - upgrade with: npm i -g ax@latest
|
|
7
|
+
`))}function H(e){let t=new AbortController,n=!1,o,r=()=>{clearTimeout(o),o=setTimeout(()=>{n=!0,t.abort()},e)};return r(),{signal:t.signal,poke:r,disarm:()=>clearTimeout(o),tripped:()=>n}}async function G(e){try{let t=await e.json();return t.message||t.error||`HTTP ${e.status}`}catch{return`HTTP ${e.status}`}}var V=e=>new Promise(t=>setTimeout(t,e));var ur="https://ora.ai",dr=6e4,pr=2e3,mr=45,Me=14,O=class extends Error{};function vt(e){return e?{authorization:`Bearer ${e}`}:{}}async function St(e,t={}){let n=(t.baseUrl??process.env.ORA_API_URL??ur).replace(/\/+$/,"");t={...t,apiKey:t.apiKey||process.env.ORA_SCAN_API_KEY||void 0},t.progress?.(`Auditing ${e} with ora`);let o=await hr(n,e,t);oe(o.result.contractVersion);let r=o.result;return xt(r)&&(r=await br(n,r,t)),{result:r,verdict:o.verdict}}function gr(e,t,n){let o=new URLSearchParams({domain:t,format:"audit"});return n.force&&o.set("force","1"),n.ephemeral&&o.set("ephemeral","1"),n.maxAgeSeconds!==void 0&&o.set("maxAgeSeconds",String(n.maxAgeSeconds)),`${e}/api/scan/stream?${o}`}async function hr(e,t,n){let o=n.idleMs??dr,r=H(o),i=()=>new O(`ora audit timed out \u2014 no progress for ${Math.round(o/1e3)}s`),s;try{s=await fetch(gr(e,t,n),{headers:{accept:"text/event-stream",...vt(n.apiKey)},signal:r.signal})}catch(g){if(r.disarm(),r.tripped())throw i();let d=g instanceof Error?g.message:String(g);throw new O(`ora audit request failed: ${d}`)}if(s.status===429){r.disarm();let g=s.headers.get("retry-after");throw new O(`ora rate limit exceeded${g?` \u2014 retry after ${g}s`:""} (burst: 10 scans/min/IP; daily: 30 scans + 6 force per 24h). An ora-issued scan API key lifts these limits: set ORA_SCAN_API_KEY or pass --api-key.`)}if(!s.ok||!s.body)throw r.disarm(),new O(`ora audit failed: ${await G(s)}`);let a=yr(),c=new TextDecoder,l="",u,p;try{e:for await(let g of s.body){r.poke(),l=`${l}${c.decode(g,{stream:!0})}`.replace(/\r\n?/g,`
|
|
8
|
+
`);let d=l.indexOf(`
|
|
9
9
|
|
|
10
|
-
`);for(;d!==-1;){let
|
|
10
|
+
`);for(;d!==-1;){let f=fr(l.slice(0,d));if(l=l.slice(d+2),d=l.indexOf(`
|
|
11
11
|
|
|
12
|
-
`),!
|
|
12
|
+
`),!f)continue;let h;try{h=JSON.parse(f)}catch{continue}let m=a(h);if(m&&n.progress?.(m),h.type==="error")throw new O(`ora audit failed: ${typeof h.message=="string"?h.message:"scan error"}`);if(h.type==="scan_complete"&&h.result?u=h.result:h.type==="summary_ready"&&typeof h.agenticSummary=="string"&&(p=h.agenticSummary),u&&p)break e}}}catch(g){if(r.tripped())throw i();if(g instanceof O)throw g;let d=g instanceof Error?g.message:String(g);throw new O(`ora audit stream error: ${d}`)}finally{r.disarm(),s.body.cancel().catch(()=>{})}if(!u)throw new O("ora audit stream ended before completing");return{result:u,verdict:p}}function fr(e){let t=[];for(let n of e.split(`
|
|
13
13
|
`))n.startsWith("data:")&&t.push(n.slice(5).replace(/^ /,""));return t.join(`
|
|
14
|
-
`)}function
|
|
15
|
-
`))}function
|
|
16
|
-
output: ${
|
|
17
|
-
`)),
|
|
18
|
-
`);else for(let d of
|
|
19
|
-
`),
|
|
20
|
-
`),
|
|
21
|
-
`))
|
|
22
|
-
`)}:null}async function
|
|
23
|
-
`);let
|
|
24
|
-
|
|
25
|
-
`);for(;
|
|
26
|
-
|
|
27
|
-
`),!d)continue;let
|
|
28
|
-
`);let
|
|
29
|
-
|
|
30
|
-
`);for(;
|
|
31
|
-
|
|
32
|
-
`),!d)continue;let
|
|
33
|
-
${
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
`),
|
|
39
|
-
`),
|
|
40
|
-
`)}var
|
|
14
|
+
`)}function yr(){let e=0,t=0,n="";return o=>{switch(o.type){case"kind_detecting":return"Detecting URL kind\u2026";case"kind_detected":return typeof o.kind=="string"?`Detected ${o.kind}, scanning\u2026`:void 0;case"scan_init":Array.isArray(o.checkRoster)&&(e=o.checkRoster.length);return;case"discovery_phase":return typeof o.label=="string"?o.label:void 0;case"check_complete":{if(t+=1,typeof o.checkName=="string"&&(n=o.checkName),e<=0)return`Running checks\u2026 (${t})`;let r=Math.min(t,e),i=Math.min(Me,Math.max(0,Math.round(r/e*Me)));return`${`${"\u2588".repeat(i)}${"\u2591".repeat(Me-i)}`} ${r}/${e}${n?` \xB7 ${n}`:""}`}case"scan_complete":return"Finishing up\u2026";default:return}}}function xt(e){return e.analysisStatus==="complete"||e.analysisStatus==="stuck"?!1:e.analysisStatus==="partial"?!0:(e.pendingChecks?.length??0)>0}async function br(e,t,n){let o=`${e}/api/score/${encodeURIComponent(t.domain)}?format=audit`,r=n.pollEveryMs??pr,i=n.pollLimit??mr,s=t;for(let a=0;a<i&&xt(s);a++){let c=s.pendingChecks?.length??0;n.progress?.(c?`Analyzing\u2026 ${c} check${c===1?"":"s"} pending`:"Analyzing\u2026"),await V(r);try{let l=await fetch(o,{headers:{accept:"application/json",...vt(n.apiKey)},signal:AbortSignal.timeout(15e3)});l.ok&&(s=await l.json())}catch{}}return s}function wr(e,t){let n=t.filter(o=>!o.skipped);return{name:e,checks:t,passed:n.filter(o=>o.passed).length,total:n.length,skipped:t.length-n.length}}function vr(e){let t=e.status==="pass",n=e.status==="na"||e.status==="pending",o={id:e.id,name:e.name,passed:t,status:e.status};return n&&(o.skipped=!0),n&&e.naReason?o.detail=e.naReason:e.details&&(o.detail=e.details),typeof e.estScoreGain=="number"&&(o.estScoreGain=e.estScoreGain),e.specUrl&&(o.specUrl=e.specUrl),!t&&!n&&e.recommendation&&(o.hint=e.recommendation),o}function At(e,t){let{result:n}=e,o=(n.layers??[]).map(s=>wr(s.name,(s.checks??[]).map(vr))),r={target:n.domain||t,score:n.score,grade:n.grade,summary:e.verdict,sections:o,topFixes:n.topFixes??[],reportUrl:n.url,analysisStatus:n.analysisStatus},i=n;return i.servedFromCache&&typeof i.resultAgeSeconds=="number"&&(r.cacheAgeSeconds=i.resultAgeSeconds),n.mcpAuthRequired&&(r.mcpAuthRequired=!0),r}var v=U(D(),1),Sr=80,xr=120,me=10;function Ar(){return Math.min(xr,Math.max(Sr,process.stdout.columns??100))}function je(e,t){return e.length<t?e+" ".repeat(t-e.length):e}function $t(e,t){if(t<=0||e.length<=t)return[e];let n=[],o="";for(let r of e.split(/\s+/))for(o=o?`${o} ${r}`:r;o.length>t;){let i=o.lastIndexOf(" ");i>0&&o.length-i-1<=t?(n.push(o.slice(0,i)),o=o.slice(i+1)):(n.push(o.slice(0,t)),o=o.slice(t))}return o&&n.push(o),n.length?n:[""]}function Ne(e,t){let n=(s,a,c)=>v.default.dim(s+e.map(l=>"\u2500".repeat(l.width+2)).join(a)+c),o=v.default.dim("\u2502"),r=(s,a)=>{let c=s.map((p,g)=>$t(typeof p=="string"?p:p[0],e[g].width)),l=Math.max(1,...c.map(p=>p.length)),u=[];for(let p=0;p<l;p++){let g=c.map((d,f)=>{let h=je(d[p]??"",e[f].width),m=a??(typeof s[f]=="string"?e[f].paint:s[f][1]);return` ${m?m(h):h} `});u.push(o+g.join(o)+o)}return u},i=[n("\u250C","\u252C","\u2510")];return i.push(...r(e.map(s=>s.title),v.default.bold)),i.push(n("\u251C","\u253C","\u2524")),t.forEach((s,a)=>{i.push(...r(s)),a<t.length-1&&i.push(n("\u251C","\u253C","\u2524"))}),i.push(n("\u2514","\u2534","\u2518")),i}function kr(e,t){let o=Math.max(46,e-4-13),r=14,i=Math.min(26,Math.max(5,...t.map(l=>l.length))),s=o-1-i;s<r*2&&(i=Math.max(12,i-(r*2-s)),s=o-1-i);let a=Math.max(r,Math.ceil(s/2)),c=Math.max(r,s-a);return[{title:"",width:1},{title:"Check",width:i,paint:v.default.bold},{title:"What's wrong",width:a},{title:"How to fix",width:c,paint:v.default.cyan}]}function kt(e,t,n,o){let i=Math.max(40,e-4-7),s=Math.min(30,Math.max(n[0].length,...t.map(a=>a.length)));return[{title:n[0],width:s,paint:o},{title:n[1],width:Math.max(20,i-s),paint:o}]}function $r(e,t){if(t<=0)return v.default.dim("\u2500".repeat(me));let n=Math.min(me,Math.max(0,Math.round(e/t*me)));return v.default.green("\u2588".repeat(n))+v.default.dim("\u2591".repeat(me-n))}function Rr(e,t,n,o){let r=[""],i=e.total>0?`${e.passed}/${e.total} passed`:"no applicable checks",s=e.skipped>0?` \xB7 ${e.skipped} skipped`:"";r.push(` ${v.default.bold(je(e.name,n))} ${$r(e.passed,e.total)} ${v.default.dim(i+s)}`);let a=e.checks.filter(c=>!c.passed&&!c.skipped);if(a.length){r.push(` ${v.default.red("\u2717")} ${v.default.bold(`Issues (${a.length})`)}`);let c=Ne(kr(t,a.map(u=>u.name)),a.map(u=>[u.status==="warning"?["\u26A0",v.default.yellow]:["\u2717",v.default.red],u.name,[u.detail??"",p=>p],u.hint??""]));r.push(...c.map(u=>` ${u}`));let l=a.filter(u=>u.specUrl);for(let u of l)r.push(v.default.dim(` \u21B3 ${u.id} spec: ${u.specUrl}`))}if(o.showPassing){let c=e.checks.filter(l=>l.passed&&!l.skipped);if(c.length){r.push(` ${v.default.green("\u2713")} ${v.default.bold(`Passed (${c.length})`)}`);let l=Ne(kt(t,c.map(u=>u.name),["Check","Details"]),c.map(u=>[u.name,u.detail??""]));r.push(...l.map(u=>` ${u}`))}}if(o.showSkipped){let c=e.checks.filter(l=>l.skipped);if(c.length){r.push(` ${v.default.dim(`\u25CB Skipped (${c.length})`)}`);let l=Ne(kt(t,c.map(u=>u.name),["Check","Reason"],v.default.dim),c.map(u=>[u.name,u.detail??""]));r.push(...l.map(u=>` ${u}`))}}return r}function Cr(e){if(!e.topFixes.length)return[];let t=["",` ${v.default.bold("Top fixes")} ${v.default.dim("(ranked by ora)")}`],n=e.topFixes.reduce((o,r)=>Math.max(o,r.id.length),0);return e.topFixes.forEach((o,r)=>{let i=typeof o.estScoreGain=="number"?v.default.green(`\u2248 +${o.estScoreGain} pts`):v.default.dim("\u2014"),s=o.bonus?v.default.dim(" (bonus)"):"";t.push(` ${r+1}. ${v.default.bold(je(o.id,n))} ${i}${s}`)}),t}function _r(e){return e<90?`${e}s`:e<5400?`${Math.round(e/60)} min`:`${Math.round(e/3600)}h`}function Rt(e,t={}){let n=Ar(),o=e.sections.reduce((l,u)=>Math.max(l,u.name.length),0),r=[""],i=e.score>=70?v.default.green:e.score>=50?v.default.yellow:v.default.red;if(r.push(` ${v.default.bold(e.target)} ${i(v.default.bold(`${e.score}/100 ${e.grade}`))}`),t.tunnel&&r.push(v.default.dim(" tunnel audit \u2014 disposable result, excluded from rankings; off-site checks (registry listings, brand search) usually fail for a throwaway hostname")),e.mcpAuthRequired&&r.push(v.default.yellow(" \u26A0 MCP handshake requires credentials \u2014 target is unscored (0/F means could not evaluate, not failed everything)")),e.summary)for(let l of $t(e.summary,n-4))r.push(` ${v.default.dim(l)}`);for(let l of e.sections)r.push(...Rr(l,n,o,t));r.push(...Cr(e));let s=e.sections.reduce((l,u)=>l+u.passed,0),a=e.sections.reduce((l,u)=>l+u.skipped,0),c=[];if(!t.showPassing&&s>0&&c.push(` Run with --show-passing to list all ${s} passing checks`),!t.showSkipped&&a>0&&c.push(` ${a} check${a===1?"":"s"} skipped \u2014 run with --show-skipped to see them`),e.analysisStatus==="partial"?c.push(" Analysis still finishing \u2014 re-run shortly for the final score"):e.analysisStatus==="stuck"&&c.push(" Scan did not fully resolve \u2014 re-run with --force to complete it"),typeof e.cacheAgeSeconds=="number"&&c.push(` cached result (${_r(e.cacheAgeSeconds)} old) \xB7 pass --force for a fresh scan`),e.reportUrl&&c.push(` Full report: ${e.reportUrl}`),c.length){r.push("");for(let l of c)r.push(v.default.dim(l))}return r.push(""),r}var Ct=require("child_process"),Q=class extends Error{},Er=3e4,Tr=9e4,Pr=1e4;function Le(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 Ir(e){for(let t of e.matchAll(/https:\/\/[^\s"'|]+/g))try{let n=new URL(t[0]);if(n.pathname==="/"&&!n.search&&!Le(n.hostname))return n.origin}catch{}}async function _t(e,t=Er){let n=await Mr(e,t);try{await Or(n.url,Tr)}catch(o){throw n.close(),o}return n}async function Or(e,t){let n=Date.now()+t;for(;Date.now()<n;){try{if((await fetch(e,{redirect:"manual",signal:AbortSignal.timeout(Pr)})).status<500)return}catch{}await new Promise(o=>setTimeout(o,5e3))}throw new Q([`tunnel opened but never became routable within ${Math.round(t/1e3)}s.`,"Some networks and DNS filters block tunnel vendors' domains entirely -","if this repeats, try another network, DNS resolver, or tunnel tool."].join(`
|
|
15
|
+
`))}function Mr(e,t){return new Promise((n,o)=>{let r=process.platform!=="win32",i=(0,Ct.spawn)(e,{shell:!0,detached:r,stdio:["ignore","pipe","pipe"]}),s=!1,a="",c=()=>{try{r&&i.pid?process.kill(-i.pid,"SIGTERM"):i.kill("SIGTERM")}catch{}},l=p=>{s||(s=!0,clearTimeout(u),c(),o(p))},u=setTimeout(()=>l(new Q(`tunnel command did not print a public https URL within ${Math.round(t/1e3)}s: ${e}`)),t);i.on("error",p=>l(new Q(p.message))),i.on("exit",p=>{let g=a.trim()?`
|
|
16
|
+
output: ${a.trim().slice(-300)}`:"";l(new Q(`tunnel command exited before printing a public https URL (code ${p??"unknown"}): ${e}${g}`))});for(let p of[i.stdout,i.stderr])p?.setEncoding("utf8"),p?.on("data",g=>{a=(a+g).slice(-2e3);let d=Ir(a);d&&!s&&(s=!0,clearTimeout(u),i.removeAllListeners("exit"),n({url:d,close:c}))})})}var We=U(D(),1);function q(e,t){let n=process.stdout.columns??100;return Math.min(t,Math.max(e,n))}function Y(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function P(e,t){let n=[],o="";for(let r of e.replace(/\s+/g," ").trim().split(" "))o&&o.length+1+r.length>t?(n.push(o),o=r):o=o?`${o} ${r}`:r;return o&&n.push(o),n}var Z=["\u25C7","\u25C7","\u25C8","\u25C8","\u25C6","\u25C6","\u25C8","\u25C8"];function R(e){return e.replace(/[\u0000-\u001f\u007f-\u009f]/g," ")}var Nr=80,ge,De=0,ie="";function jr(){let e=We.default.cyan(Z[De%Z.length]),t=Math.max(10,(process.stderr.columns??80)-2),n=ie.length>t?`${ie.slice(0,t-1)}\u2026`:ie;process.stderr.write(`\r\x1B[K${e} ${We.default.dim(n)}`),De++}var A={start(e){A.stop(),De=0,ie=e,process.stderr.isTTY&&(ge=setInterval(jr,Nr))},update(e){ie=e},stop(){ge&&(clearInterval(ge),ge=void 0,process.stderr.write("\r\x1B[K"))}};var E={OK:0,BELOW_MIN_SCORE:1,USAGE:2,API:3};function Et(e,t,n,o){if(e===void 0)return{};let r=Number(e);return e.trim()===""||!Number.isInteger(r)||r<n||r>o?{error:`${t} must be an integer between ${n} and ${o}, got ${JSON.stringify(e)}`}:{value:r}}function Lr(e){let t=e.trim().replace(/\/+$/,"");if(!(!t||/\s/.test(t)))try{let n=new URL(t.includes("://")?t:`https://${t}`);return!n.hostname.includes(".")&&n.hostname!=="localhost"?void 0:t}catch{return}}async function Tt(e){let t=Lr(e.url);if(!t)return console.error(`Not a scannable URL or domain: ${JSON.stringify(e.url)}`),E.USAGE;let n=Et(e.minScore,"--min-score",0,100),o=Et(e.maxAge,"--max-age",0,86400);for(let d of[n,o])if(d.error)return console.error(d.error),E.USAGE;let r=e.tunnelCmd?.trim()||process.env.ORA_TUNNEL_CMD?.trim(),i=!!r;if(!i&&Le(t))return console.error([`${t} only exists on this machine, and ora audits public URLs.`,"Either audit a publicly reachable deployment of this site (e.g. a preview URL),","or run it through a tunnel you provide:"," ax audit localhost:3000 --tunnel-cmd 'ngrok http 3000 --log stdout'","Any command that prints a public https URL works; the result is stored as","ephemeral (excluded from rankings, deleted after a few days)."].join(`
|
|
17
|
+
`)),E.USAGE;let s=!e.json;s&&A.start(`Auditing ${t} with ora`);let a,c=()=>a?.close(),l=d=>{c(),process.exit(d==="SIGINT"?130:143)},u=t;if(i&&r){s&&A.update(`Opening a tunnel to ${t}`);try{a=await _t(r)}catch(d){return A.stop(),console.error(d instanceof Error?d.message:String(d)),E.USAGE}process.on("SIGINT",l),process.on("SIGTERM",l),u=a.url}let p;try{p=await St(u,{progress:s?d=>A.update(d):void 0,maxAgeSeconds:o.value,force:e.force,ephemeral:i||void 0,apiKey:e.apiKey?.trim()||void 0})}catch(d){return A.stop(),console.error(`Audit failed: ${d instanceof Error?d.message:String(d)}`),d instanceof O?E.API:E.USAGE}finally{c(),process.removeListener("SIGINT",l),process.removeListener("SIGTERM",l)}A.stop();let{result:g}=p;if(e.json)process.stdout.write(`${JSON.stringify(g,null,2)}
|
|
18
|
+
`);else for(let d of Rt(At(p,t),{showSkipped:e.showSkipped,showPassing:e.showPassing,tunnel:i}))console.log(d);if(n.value!==void 0){if(g.mcpAuthRequired)return process.stderr.write(`--min-score skipped: the MCP handshake requires credentials, so the target is unscored
|
|
19
|
+
`),E.OK;if(g.score<n.value)return e.json||console.log(` Score ${g.score} is below the required minimum ${n.value}
|
|
20
|
+
`),E.BELOW_MIN_SCORE}return E.OK}var w=U(D(),1);var Wr="https://api.agentfront.sh",Dr=12e4;async function Br(e,t){let n=await fetch(`${e}/auth/token`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:"{}"});if(n.status===401)throw new Error("ora rejected the API key (401). Check ORA_API_KEY.");let o=await n.json().catch(()=>({}));if(!n.ok||!o.token)throw new Error(`ora auth failed (${n.status})${o.error?`: ${o.error}`:""}`);return o.token}async function Ur(e,t,n){let o={intent:n.intent};n.domain&&(o.domain=n.domain),n.harness&&(o.harness=n.harness),n.model&&(o.model=n.model),n.executionKind&&(o.execution_kind=n.executionKind);let r=await fetch(`${e}/experiment/v1/runs`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify(o)});if(r.status===429)throw new Error("ora rate limit hit (429). Wait a moment and retry.");let i=await r.text(),s;try{s=JSON.parse(i)}catch{throw new Error(`ora returned a non-JSON response (${r.status})`)}if(!r.ok||!s.runId)throw new Error(`ora run failed (${r.status}): ${s.message??s.error??i}`);return s}function Be(e){let t="message",n=[];for(let o of e.split(`
|
|
21
|
+
`))o.startsWith(":")||(o.startsWith("event:")?t=o.slice(6).trim():o.startsWith("data:")&&n.push(o.slice(5).replace(/^ /,"")));return n.length?{event:t,data:n.join(`
|
|
22
|
+
`)}:null}async function Jr(e,t,n,o,r){let i=n.startsWith("http")?n:`${e}${n}`,s=H(r),a=await fetch(i,{headers:{authorization:`Bearer ${t}`,accept:"text/event-stream"},signal:s.signal});if(!a.ok||!a.body)throw s.disarm(),new Error(`ora run stream failed (${a.status})`);let c=new TextDecoder,l={steps:[],trajectory:[]},u="";try{e:for await(let p of a.body){s.poke(),u=`${u}${c.decode(p,{stream:!0})}`.replace(/\r\n?/g,`
|
|
23
|
+
`);let g=u.indexOf(`
|
|
24
|
+
|
|
25
|
+
`);for(;g!==-1;){let d=Be(u.slice(0,g));if(u=u.slice(g+2),g=u.indexOf(`
|
|
26
|
+
|
|
27
|
+
`),!d)continue;let f;try{f=JSON.parse(d.data)}catch{continue}if(Fr(l,d.event,f,o),l.summary&&l.insight)break e}}}catch(p){throw s.tripped()?new Error(`ora run stream timed out after ${r}ms of silence`):p}finally{s.disarm(),a.body.cancel().catch(()=>{})}return l}function Fr(e,t,n,o){switch(t){case"trajectory":{let r=n.steps;Array.isArray(r)&&(e.trajectory=r,o.snapshot?.(e.trajectory));return}case"step":{let r=n.step;r&&(e.steps.push(r),o.step?.(r,Number(n.seq??e.steps.length)));return}case"result":{let r=n.result;r&&(e.summary=r,o.finished?.(r));return}case"insight":{let r=n.insight;r&&(e.insight=r,o.scored?.(r));return}default:return}}async function Hr(e,t,n){for(let o=0;;o++){let r;try{let i=await fetch(`${e}/experiment/v1/runs?pageSize=50`,{headers:{authorization:`Bearer ${t}`}});if(!i.ok)return;r=(await i.json()).results?.find(a=>a.id===n)}catch{return}if(!r)return;if(r.total_tokens!=null||r.cost_usd!=null)return{totalTokens:r.total_tokens??void 0,inputTokens:r.input_tokens??void 0,outputTokens:r.output_tokens??void 0,cacheReadTokens:r.cache_read_tokens??void 0,cacheCreationTokens:r.cache_creation_tokens??void 0,costUsd:r.cost_usd??void 0};if(o>0)return;await V(1200)}}async function Ue(e,t={}){let n=(e.baseUrl??process.env.ORA_PLATFORM_URL??Wr).replace(/\/+$/,""),o=e.apiKey??process.env.ORA_API_KEY;if(!o)throw new Error("Missing ORA_API_KEY. Set it in your environment or a local .env file (see .env.example).");let r=await Br(n,o),i=await Ur(n,r,e),s={runId:i.runId,intent:e.intent,domain:e.domain,harness:e.harness};if(i.status==="succeeded"&&!i.streamUrl)return{...s,steps:[],trajectory:[]};t.opened?.(i.runId);let a=await Jr(n,r,i.streamUrl??`/experiment/v1/runs/${i.runId}/stream`,t,e.idleMs??Dr),c=a.summary?await Hr(n,r,i.runId):void 0;return{...s,result:a.summary,insight:a.insight,usage:c,steps:a.steps,trajectory:a.trajectory}}var Gr="https://ora.ai",qr=12e4,Kr=5e3,Vr=180,C=class extends Error{};function Je(e){return(e??process.env.ORA_API_URL??Gr).replace(/\/+$/,"")}async function Fe(e){let t;try{t=await fetch(e,{headers:{accept:"application/json"},signal:AbortSignal.timeout(15e3)})}catch(n){let o=n instanceof Error?n.message:String(n);throw new C(`ora request failed: ${o}`)}if(!t.ok)throw new C(`ora request failed: ${await G(t)}`);return await t.json()}function Ot(e){return Fe(`${Je(e)}/api/journey/intents`)}function Mt(e){return Fe(`${Je(e)}/api/journey/agents`)}function Yr(e){let t=o=>{let r=e.headers.get(o);if(r===null)return;let i=Number.parseInt(r,10);return Number.isFinite(i)?i:void 0},n=t("x-ratelimit-reset");return{limit:t("x-ratelimit-limit"),remaining:t("x-ratelimit-remaining"),resetAtMs:n!==void 0?n*1e3:void 0}}async function Xr(e,t,n){let o={intent:n.task?{custom:n.task,domain:t}:{...n.intentId?{intent_id:n.intentId}:{},domain:t},harness:n.harness,model:n.model},r;try{r=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(o),signal:AbortSignal.timeout(3e4)})}catch(s){let a=s instanceof Error?s.message:String(s);throw new C(`ora journey request failed: ${a}`)}if(r.status===401)throw new C("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(r.status===429){let s=r.headers.get("retry-after"),a=n.apiKey?"keyed allowance: 1000 runs per 24h per key":"burst: 20/min/IP; daily: 200 runs per 24h per IP \u2014 an ora partner API key raises this to 1000/24h per key: set ORA_PARTNER_API_KEY or pass --api-key";throw new C(`ora journey caller limit exceeded${s?` \u2014 retry after ${He(Number(s)*1e3)}`:""} (${a})`)}if(r.status===503)throw new C("ora's run engine is unavailable right now \u2014 try again shortly");if(!r.ok)throw new C(`ora journey request failed: ${await G(r)}`);let i=await r.json();return oe(i.contractVersion),{record:i,cached:i.rate_limited===!0,allowance:Yr(r)}}function He(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 zr(e){if(!e)return"starting\u2026";if(e.type==="text")return"thinking\u2026";if(e.action==="search")return e.search_query?`searching \u201C${Pt(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} ${Pt(t,48)}`:`${n}\u2026`}function Pt(e,t){return e.length>t?`${e.slice(0,t-1)}\u2026`:e}async function Qr(e,t,n){let o=t.startsWith("http")?t:`${e}${t}`,r=n.idleMs??qr,i=H(r),s=()=>new C(`ora journey stream timed out \u2014 no frames for ${Math.round(r/1e3)}s`),a;try{a=await fetch(o,{headers:{accept:"text/event-stream"},signal:i.signal})}catch(p){if(i.disarm(),i.tripped())throw s();let g=p instanceof Error?p.message:String(p);throw new C(`ora journey stream failed: ${g}`)}if(!a.ok||!a.body)throw i.disarm(),new C(`ora journey stream failed: ${await G(a)}`);let c=new TextDecoder,l={},u="";try{e:for await(let p of a.body){i.poke(),u=`${u}${c.decode(p,{stream:!0})}`.replace(/\r\n?/g,`
|
|
28
|
+
`);let g=u.indexOf(`
|
|
29
|
+
|
|
30
|
+
`);for(;g!==-1;){let d=Be(u.slice(0,g));if(u=u.slice(g+2),g=u.indexOf(`
|
|
31
|
+
|
|
32
|
+
`),!d)continue;let f;try{f=JSON.parse(d.data)}catch{continue}if(d.event==="trajectory"){let h=f.steps??[],m=h.filter(y=>y.type==="tool_call").at(-1);n.progress?.(`step ${h.length} \xB7 ${zr(m??h.at(-1))}`),n.onTrajectory?.(h)}else if(d.event==="processing")n.progress?.(typeof f.message=="string"?f.message:"generating insights\u2026");else if(d.event==="result"){l.result=f;break e}else if(d.event==="error"){l.errorMessage=typeof f.message=="string"?f.message:"unknown engine error";break e}}}}catch(p){if(i.tripped())throw s();if(p instanceof C)throw p;let g=p instanceof Error?p.message:String(p);throw new C(`ora journey stream error: ${g}`)}finally{i.disarm(),a.body.cancel().catch(()=>{})}return l}function he(e,t){return Fe(`${e}/api/journey/runs/${encodeURIComponent(t)}`)}async function It(e,t,n){let o=n.pollEveryMs??Kr,r=n.pollLimit??Vr,i=await he(e,t);for(let s=0;s<r&&i.status==="running";s++){n.progress?.("agent working\u2026 (polling)"),await V(o);try{i=await he(e,t)}catch{}}return i}async function Nt(e,t){let n=Je(t.baseUrl);t={...t,apiKey:t.apiKey||process.env.ORA_PARTNER_API_KEY||process.env.ORA_SCAN_API_KEY||void 0};let o=await Xr(n,e,t),{record:r}=o;o.cached&&t.progress?.("target at its 24h cap \u2014 fetching the most recent stored run");let i;if(!t.noStream&&r.status==="running")try{i=(await Qr(n,r.stream_url,t)).errorMessage}catch{t.progress?.("stream went quiet \u2014 switching to polling"),await It(n,r.id,t)}else t.noStream&&r.status==="running"&&await It(n,r.id,t);let s=await Zr(n,r.id,t);if(s.status==="running")throw i?new C(`ora journey run failed: ${i}`):new C(`run ${r.id} is still executing \u2014 the ${t.noStream?"poll budget ran out":"stream ended"} before a terminal result. Check ${n}/api/journey/runs/${r.id} shortly`);return oe(s.contractVersion),{record:r,cached:o.cached,retryAfterMs:o.record.retry_after_ms,allowance:o.allowance,detail:s,engineError:i}}async function Zr(e,t,n){let o=await he(e,t);for(let r=0;r<3&&o.status==="running";r++)n.progress?.("finalizing\u2026"),await V(1500),o=await he(e,t);return o}var $=U(D(),1);function Ge(e){if(!e)return{};let t=e.match(/https?:\/\/([^/\s]+)(\/\S*)?/i);return t?{host:t[1],path:t[2]??"/"}:{}}function X(e){return/search/i.test(`${e.tool??""} ${e.action??""}`)}function eo(e){if(X(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 to(e,t){if(X(e)){let c=e.input_display??String(e.input?.query??"search"),l=e.output_structured?.links?.length;return{id:e.id,kind:"search",icon:"\u{1F50D}",label:Y(`"${c}"`,t),meta:l?`${l} results`:void 0,tone:"ok",notes:[],children:[]}}let{host:n,path:o}=Ge(e.input_display??String(e.input?.url??"")),r=e.status,i=r!=null&&r>=300&&r<400,s=!!e.is_error||r!=null&&r>=400,a;if(i)a=`\u21B3 ${r}`;else if(s)a=`\u2717 ${r??"error"}`;else{let c=["\u2713"];r&&c.push(String(r)),e.duration_ms&&c.push(`${(e.duration_ms/1e3).toFixed(1)}s`),a=c.join(" ")}return{id:e.id,kind:"fetch",icon:eo(e),label:Y(`${n??"?"}${o??""}`,t),meta:a,tone:i?"redirect":s?"error":"ok",notes:[],children:[]}}function fe(e,t,n){let o=q(60,120),r=Math.min(52,Math.max(24,o-40)),i=Math.max(30,o-24),s={id:-1,kind:"intent",icon:"\u25C6",label:Y(t,i),tone:"root",notes:[],children:[]},a=new Map,c=[],l,u,p;for(let g of e){if(g.type==="text"&&g.kind==="reasoning"){let h=(g.thinking??g.text??"").trim();h&&c.push(Y(h,i));continue}if(g.type!=="tool_call")continue;let d=to(g,r);d.notes=c,c=[],a.set(g.id,d);let f=s;if(!X(g)){let h=g.attribution?.referrer?.step_id,m=g.attribution?.kind,y=h!=null?a.get(h):void 0;y&&y!==d?f=y:m==="web_search"&&l?f=l:m==="previous_artifact"&&u&&(f=u)}f.children.push(d),X(g)?l=d:u=d,p=d}return p&&!n&&(p.tone="active",p.meta="\u2026"),{root:s,looseNotes:c}}function ye(e){let t=e.filter(r=>r.kind==="reasoning").length,n=e.filter(r=>r.type==="tool_call"&&X(r)).length,o=[`${$.default.bold(String(e.length))} steps`];return t&&o.push(`${$.default.bold(String(t))} reasoning`),n&&o.push(`${$.default.bold(String(n))} search${n===1?"":"es"}`),o.join($.default.dim(" \xB7 "))}function no(e){switch(e){case"root":return{frame:$.default.dim,ink:t=>$.default.bold(t)};case"active":return{frame:$.default.cyan,ink:t=>$.default.cyan($.default.bold(t))};case"redirect":return{frame:$.default.yellow,ink:$.default.yellow};case"error":return{frame:$.default.red,ink:$.default.red};default:return{frame:$.default.green,ink:$.default.green}}}var jt=e=>$.default.dim(`(\u2026) ${e}`);function Lt(e,t){let{frame:n,ink:o}=no(e.tone),i=`${e.icon} ${e.label}${e.meta?` ${e.meta}`:""}`.length+2,s=`${e.icon} ${o(e.label)}${e.meta?` ${$.default.dim(e.meta)}`:""}`,a=e.children.length>0,c=e.notes.map(jt);return c.push(n(`\u256D${"\u2500".repeat(i)}\u256E`)),c.push(`${n(t?"\u2524":"\u2502")} ${s} ${n("\u2502")}`),c.push(n(a?`\u2570\u2500\u252C${"\u2500".repeat(i-2)}\u256F`:`\u2570${"\u2500".repeat(i)}\u256F`)),e.children.forEach((l,u)=>{let p=u===e.children.length-1,g=Lt(l,!0),d=l.notes.length+1;g.forEach((f,h)=>{let m;h===d?m=p?" \u2570\u2500\u2500":" \u251C\u2500\u2500":h<d?m=" \u2502 ":m=p?" ":" \u2502 ",c.push($.default.dim(m)+f)})}),c}function be(e){let t=Lt(e.root,!1);return e.looseNotes.length&&(t.push(""),t.push(...e.looseNotes.map(jt))),t}var we=U(D(),1);var ee=class{rows=0;beat=0;bornAt=Date.now();ticker;live=!!process.stdout.isTTY;content=[];headline="";open(){this.live&&!this.ticker&&(this.ticker=setInterval(()=>this.pulse(),100))}draw(t,n){this.content=t,this.headline=n,this.repaint()}close(){this.ticker&&(clearInterval(this.ticker),this.ticker=void 0),this.live&&this.rows>0&&(process.stdout.write(`\x1B[${this.rows}A\r\x1B[0J`),this.rows=0)}banner(){let t=we.default.cyan(Z[this.beat%Z.length]),n=Math.floor((Date.now()-this.bornAt)/1e3),o=`${this.headline} ${n}s`,r=Math.max(10,(process.stdout.columns??80)-6),i=o.length>r?`${o.slice(0,r-1)}\u2026`:o;return` ${t} ${we.default.bold(i)}`}clamp(t){let n=Math.max(2,(process.stdout.rows??24)-3);if(t.length<=n)return t;let o=n-1,r=t.length-o;return[we.default.dim(` \u22EF ${r} earlier line${r===1?"":"s"}`),...t.slice(-o)]}repaint(){if(!this.live)return;let t=[this.banner(),"",...this.clamp(this.content)],n=this.rows>0?`\x1B[${this.rows}A`:"";for(let o of t)n+=`\x1B[2K${o}
|
|
33
|
+
`;t.length<this.rows&&(n+="\x1B[0J"),this.rows=t.length,process.stdout.write(n)}pulse(){!this.live||this.rows===0||(this.beat++,process.stdout.write(`\x1B[${this.rows}A\r\x1B[2K${this.banner()}\x1B[${this.rows}B\r`))}};var B={OK:0,RUN_FAILED:1,USAGE:2,API:3},ro="public caps: 100 runs/24h per target \xB7 200 runs/24h per IP",oo="keyed caps: 1000 runs/24h per key \xB7 no per-target cap";function qe(e){return console.error(w.default.red(`ax deep-journey: ${e}`)),B.API}function io(e,t){if(t==="failed")return w.default.red("\u2717 run failed");switch(e){case"satisfied":return w.default.green("\u2713 task satisfied");case"partial":return w.default.yellow("\u25D0 partially satisfied");case"unsatisfied":return w.default.red("\u2717 task not satisfied");default:return w.default.dim("\xB7 not gradable")}}function Ke(e){return`${e.label} \xB7 ${e.variant}`}function Wt(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 Dt(e,t,n){return[` ${ye(e)}`,"",...be(fe(e,t,n)).map(o=>` ${o}`)]}var so=e=>e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e);function ao(e){return e<.01?`$${e.toFixed(4)}`:e<1?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function co(e){if(!e)return;let{input_tokens:t,output_tokens:n}=e;if(!(t==null&&n==null))return(t??0)+(n??0)}function lo(e){return(e?.trajectory?.steps??[]).filter(t=>t.action==="search").length}function Ve(e,t,n){return e>=t?w.default.green:e>=n?w.default.yellow:w.default.red}function uo(e){let t=e.trajectory?.steps??[],n=t.filter(i=>i.type==="tool_call"&&(i.action==="fetch"||i.action==="api_call")),o=t.filter(i=>i.type==="tool_call"&&i.action&&i.action!=="search"),r=[];if(n.length){let i=n.filter(a=>a.attribution?.kind==="web_search").length/n.length,s=Math.round((1-i)*100);r.push({label:"on-site discovery",pct:s,paint:Ve(s,70,40)})}if(o.length){let i=o.filter(a=>a.status!=null&&a.status>=200&&a.status<300).length,s=Math.round(i/o.length*100);r.push({label:"reliability",pct:s,paint:s===100?w.default.green:Ve(s,85,60)})}if(n.length){let i=e.run_signals?.link_following_rate??n.filter(a=>a.attribution?.kind==="previous_artifact").length/n.length,s=Math.round(i*100);r.push({label:"link following",pct:s,paint:Ve(s,70,35)})}return r}function po(e,t=20){let n=Math.max(0,Math.min(t,Math.round(e.pct/100*t))),o=`${e.paint("\u25B0".repeat(n))}${w.default.dim("\u25B1".repeat(t-n))}`,r=`${e.pct}%`.padStart(4);return` ${w.default.dim(e.label.padEnd(17))} ${o} ${e.paint(w.default.bold(r))}`}function mo(e){return w.default.dim(` ${"\u2500".repeat(Math.min(e-4,52))}`)}function go(e){let t=e.run_signals,n=[];if(t?.reached_anchor!=null){let i=t.reached_anchor?w.default.green("\u2713 reached the site"):w.default.red("\u2717 never reached the site");n.push("",` ${i}`)}let o=uo(e);if(o.length){n.push("");for(let i of o)n.push(po(i))}let r=t?.journey_layers??e.insight?.journey_layers;return r?.length&&n.push("",` ${w.default.dim("layers")} ${r.map(i=>w.default.bold(i)).join(w.default.dim(" \u203A "))}`),n}function ho(e,t){let n=q(60,120),{detail:o}=e,r=o.result,i=["",mo(n),""];i.push(` ${io(o.verdict,o.status)} ${w.default.dim("\xB7")} ${w.default.dim(o.domain??t)}`);let s=[];o.step_count!=null&&s.push(`${o.step_count} steps`);let a=r?.run_signals?.search_count??lo(r);a&&s.push(`${a} search${a===1?"":"es"}`),r?.duration_ms!=null&&s.push(`${(r.duration_ms/1e3).toFixed(1)}s`);let c=co(r);if(c!=null&&s.push(`${so(c)} tokens`),r?.cost_usd!=null&&s.push(ao(r.cost_usd)),s.length&&i.push(` ${w.default.dim(s.join(" \xB7 "))}`),r&&i.push(...go(r)),r?.insight?.summary){i.push("");for(let u of P(R(r.insight.summary),n-4))i.push(` ${u}`)}let l=r?.insight?.key_observations??[];if(l.length){i.push("",` ${w.default.bold("Observations")}`);for(let u of l){let[p,...g]=P(R(u),n-6);i.push(` ${w.default.cyan("\xB7")} ${p}`);for(let d of g)i.push(` ${d}`)}}return o.status==="failed"&&i.push("",w.default.dim(e.engineError?` Engine error: ${e.engineError} \u2014 re-running is free to try.`:" The run ended in an engine error; re-running is free to try.")),i.push("",w.default.dim(` For the 4-layer readiness audit, run: ax audit ${t}`)),i}async function Bt(e){let t=e.url.trim();if(!t)return console.error("ax deep-journey: a target URL or domain is required"),B.USAGE;let n=!e.json&&process.stderr.isTTY,o=e.task?.trim()||void 0,r=e.apiKey||process.env.ORA_PARTNER_API_KEY||process.env.ORA_SCAN_API_KEY||void 0;if(o&&e.intent!==void 0)return console.error("ax deep-journey: --task and --intent are mutually exclusive \u2014 a free-text task replaces the curated intent"),B.USAGE;if(o&&!r)return console.error("ax deep-journey: --task needs an ora partner API key \u2014 set ORA_PARTNER_API_KEY or pass --api-key (keys are issued by ora on request)"),B.USAGE;let i=e.intent,s,a=o??"journey";try{let[m,y]=await Promise.all([o?void 0:Ot(),Mt()]);if(m){if(i===void 0)i=m.defaultId;else if(!m.intents.some(F=>F.id===i))return console.error(`ax deep-journey: unknown intent "${i}". Available intents:
|
|
34
|
+
${m.intents.map(F=>` ${F.id.padEnd(12)} ${F.hint}`).join(`
|
|
35
|
+
`)}`),B.USAGE;let N=m.intents.find(F=>F.id===i);a=N?.template||N?.hint||N?.label||i||"journey"}let x=e.agent??y.defaultId,T=y.agents.find(N=>N.id===x);if(!T)return console.error(`ax deep-journey: unknown agent "${x}". Available agents:
|
|
36
|
+
${y.agents.map(N=>` ${N.id.padEnd(12)} ${Ke(N)}`).join(`
|
|
37
|
+
`)}`),B.USAGE;s=T}catch(m){return qe(m instanceof Error?m.message:String(m))}e.json||console.error(w.default.dim(r?oo:ro));let c=n&&!e.noStream,l=new ee,u=[],p=`waking ${s.label}`,g=()=>l.draw(Dt(u,a,!1),p);c?(console.log(),console.log(` ${w.default.cyan("\u25B6")} ${w.default.bold(t)} ${w.default.dim("\xB7")} ${w.default.dim(Ke(s))} ${w.default.dim("\xB7")} ${w.default.dim(o?"custom task":i??"default")}`),console.log(),l.open(),g()):n&&A.start(`Sending ${Ke(s)} to ${t} (${o?`"${o}"`:i})`);let d=m=>{c?(p=m,g()):n&&A.update(m)},f;try{f=await Nt(t,{intentId:o?void 0:i,task:o,apiKey:r,harness:s.harness,model:s.model,noStream:e.noStream,progress:n?d:void 0,onTrajectory:c?m=>{u=m.map(Wt),g()}:void 0})}catch(m){return c?l.close():n&&A.stop(),m instanceof C?qe(m.message):qe(m instanceof Error?m.message:String(m))}if(c?l.close():n&&A.stop(),e.json)return console.log(JSON.stringify(f.detail,null,2)),f.detail.status==="failed"?B.RUN_FAILED:B.OK;f.cached?console.error(w.default.yellow(`This target hit its 24h cap \u2014 showing the most recent stored run${f.retryAfterMs?` (fresh run in ${He(f.retryAfterMs)})`:""}.`)):f.allowance.remaining!==void 0&&f.allowance.limit!==void 0&&console.error(w.default.dim(`allowance: ${f.allowance.remaining} of ${f.allowance.limit} target runs left in the 24h window`));let h=(f.detail.result?.trajectory?.steps??[]).map(Wt);if(h.length){console.log();for(let m of Dt(h,a,!0))console.log(m)}for(let m of ho(f,t))console.log(m);return f.detail.status==="failed"?B.RUN_FAILED:B.OK}var S=U(D(),1);var ve=()=>q(60,120);function fo(e){if(e.type==="tool_call"){let t=e.input_display??e.summary??"";if(X(e))return t?`searching ${Y(t,40)}`:"searching\u2026";let{host:n}=Ge(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 yo=e=>e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e);function bo(e){return e<.01?`$${e.toFixed(4)}`:e<1?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function wo(e,t){let n=e.outcome==="success",o=[];return e.num_turns!=null&&o.push(`${e.num_turns} turns`),e.duration_ms!=null&&o.push(`${(e.duration_ms/1e3).toFixed(1)}s`),t?.totalTokens!=null&&o.push(`${yo(t.totalTokens)} tokens`),t?.costUsd!=null&&o.push(bo(t.costUsd)),["",` ${S.default.dim("\u2500".repeat(Math.min(ve()-4,52)))}`,` ${n?S.default.green("\u2713"):S.default.red("\u2717")} ${S.default.bold(n?"completed":e.outcome)}${o.length?` ${S.default.dim(o.join(" \xB7 "))}`:""}`]}function vo(e,t=22){let n=Math.min(100,Math.max(0,e)),o=Math.round(n/100*t);return(n>=70?S.default.green:n>=50?S.default.yellow:S.default.red)("\u2588".repeat(o))+S.default.dim("\u2591".repeat(t-o))}function So(e){return e==="high"?S.default.red("\u25CF high "):e==="medium"?S.default.yellow("\u25CF medium"):e==="low"?S.default.dim("\u25CF low "):S.default.dim("\u25CF ")}function xo(e){let t=[""];if(e.visibility_score!=null){let n=e.visibility_score,o=n>=70?S.default.green:n>=50?S.default.yellow:S.default.red,r=e.intent_satisfied?S.default.green("\u2713 intent satisfied"):S.default.yellow("\u2717 intent not satisfied");t.push(` ${S.default.bold("Visibility")} ${vo(n)} ${o(S.default.bold(`${n}/100`))} ${r}`)}if(e.summary){t.push("");for(let n of P(e.summary,ve()-4))t.push(` ${S.default.dim(n)}`)}if(e.friction_points?.length){t.push("",` ${S.default.bold("Friction")}`);for(let n of e.friction_points){let[o,...r]=P(n,ve()-6);t.push(` ${S.default.yellow("\xB7")} ${o}`);for(let i of r)t.push(` ${i}`)}}if(e.recommendations?.length){t.push("",` ${S.default.bold("Recommendations")}`);for(let n of e.recommendations){t.push(` ${So(n.priority)} ${S.default.bold(n.title)}`);for(let o of P(n.detail,ve()-8))t.push(` ${S.default.dim(o)}`)}}return t.push(""),t}function Ao(e){let t=e.insight??{};return JSON.stringify({runId:e.runId,intent:e.intent,domain:e.domain,harness:e.harness,model:e.result?.effective_model??e.result?.model,outcome:e.result?.outcome,durationMs:e.result?.duration_ms,numTurns:e.result?.num_turns,totalTokens:e.usage?.totalTokens,inputTokens:e.usage?.inputTokens,outputTokens:e.usage?.outputTokens,costUsd:e.usage?.costUsd,visibilityScore:t.visibility_score,intentSatisfied:t.intent_satisfied,taskSatisfied:t.task_satisfied,summary:t.summary,keyObservations:t.key_observations,frictionPoints:t.friction_points,recommendations:t.recommendations,journeyLayers:t.journey_layers,intentCategory:t.intent_category,steps:e.trajectory},null,2)}async function Ut(e){let t={intent:e.intent,domain:e.domain,harness:e.harness,model:e.model};if(e.json)try{let s=await Ue(t);return process.stdout.write(`${Ao(s)}
|
|
38
|
+
`),s.result?.outcome==="success"?0:1}catch(s){return console.error(`Journey failed: ${s instanceof Error?s.message:String(s)}`),2}let n=new ee,o=[],r=!1,i=()=>[` ${ye(o)}`,"",...be(fe(o,e.intent,r)).map(s=>` ${s}`)];console.log(),console.log(` ${S.default.cyan("\u25B6")} ${e.domain?S.default.bold(e.domain):S.default.dim("(no domain)")} ${S.default.dim("\xB7")} ${S.default.dim(e.harness)}`),console.log(),n.open(),n.draw(i(),"waking the agent");try{let s=await Ue(t,{snapshot:a=>{o=a;let c=a[a.length-1];n.draw(i(),c?fo(c):"working")},finished:()=>{r=!0,n.draw(i(),"scoring the journey")}});n.close(),r=!0,s.trajectory.length&&(o=s.trajectory);for(let a of i())console.log(a);if(s.result)for(let a of wo(s.result,s.usage))console.log(a);if(s.insight)for(let a of xo(s.insight))console.log(a);else s.result&&(console.log(S.default.dim(" (insight not available for this run)")),console.log());return s.result?.outcome==="success"?0:1}catch(s){return n.close(),console.error(`Journey failed: ${s instanceof Error?s.message:String(s)}`),2}}var Se=require("fs"),Xe=require("path"),te=U(D(),1);var Ft=require("crypto"),ko="https://ora.ai",L=class extends Error{};function Ht(e){return(e??process.env.ORA_API_URL??ko).replace(/\/+$/,"")}async function Ye(e){let t=Ht(e),n;try{n=await fetch(`${t}/.well-known/agent-skills/index.json`,{headers:{accept:"application/json"},signal:AbortSignal.timeout(15e3)})}catch(r){throw new L(`could not reach the skill registry at ${t}: ${r instanceof Error?r.message:String(r)}`)}if(!n.ok)throw new L(`skill registry answered HTTP ${n.status}`);let o=await n.json();if(!Array.isArray(o.skills))throw new L("skill registry index has no skills[]");return o.skills}function Jt(e){return`sha256:${(0,Ft.createHash)("sha256").update(e).digest("hex")}`}async function Gt(e,t){let n=Ht(t),o=await Ye(n),r=o.find(c=>c.name===e);if(!r){let c=o.map(l=>l.name).join(", ");throw new L(`unknown skill ${JSON.stringify(e)} - the registry has: ${c}`)}let i=r.url.startsWith("http")?r.url:`${n}${r.url}`,s;try{s=await fetch(i,{signal:AbortSignal.timeout(15e3)})}catch(c){throw new L(`could not fetch ${i}: ${c instanceof Error?c.message:String(c)}`)}if(!s.ok)throw new L(`skill fetch answered HTTP ${s.status} for ${i}`);let a=new Uint8Array(await s.arrayBuffer());if(r.digest&&Jt(a)!==r.digest)throw new L(`digest mismatch for ${e}: index says ${r.digest}, served bytes hash to ${Jt(a)} - refusing to use them`);return{entry:r,bytes:a}}var $o=".claude/skills";function Ro(e,t,n){let o=[],r="";for(let i of e.split(/\s+/))r&&`${r} ${i}`.length>t?(o.push(n+r),r=i):r=r?`${r} ${i}`:i;return r&&o.push(n+r),o}async function qt(e){try{if(!e.name){let o=await Ye();if(e.json)return process.stdout.write(`${JSON.stringify(o,null,2)}
|
|
39
|
+
`),E.OK;console.log("");for(let r of o){let i=r.digest?te.default.dim(` ${r.digest.slice(0,19)}\u2026`):"";if(console.log(` ${te.default.bold(r.name)}${i}`),r.description)for(let s of Ro(r.description,76," "))console.log(te.default.dim(s));console.log("")}return console.log(te.default.dim(" Install one with: ax skill <name> --install")),console.log(""),E.OK}let{entry:t,bytes:n}=await Gt(e.name);if(e.install){let o=(0,Xe.join)(e.dir??$o,t.name);(0,Se.mkdirSync)(o,{recursive:!0});let r=(0,Xe.join)(o,"SKILL.md");return(0,Se.writeFileSync)(r,n),console.log(`Installed ${t.name} to ${r}`),t.digest&&console.log(te.default.dim(`verified ${t.digest}`)),E.OK}return process.stdout.write(n),E.OK}catch(t){let n=t instanceof Error?t.message:String(t);return console.error(`Skill command failed: ${n}`),t instanceof L&&n.includes("unknown skill")?E.USAGE:E.API}}var k=class extends Error{constructor(t,n){super(t,n),this.name="CdpError"}},Kt=1e4,Vt=5e3,Qe=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((o,r)=>{let i=setTimeout(()=>{r(new k(`timed out connecting to ${t}`))},Vt);n.addEventListener("open",()=>{clearTimeout(i),o()},{once:!0}),n.addEventListener("error",()=>{clearTimeout(i),r(new k(`could not connect to ${t}`))},{once:!0})}),new e(n)}dispatch(t){let n;try{n=JSON.parse(t)}catch{return}let o=n.id;if(typeof o=="number"){let a=this.pending.get(o);if(!a)return;this.pending.delete(o),clearTimeout(a.timer);let c=n.error;c?a.reject(new k(c.message??"CDP call failed")):a.resolve(n.result??{});return}let r=n.method;if(typeof r!="string")return;let i=typeof n.sessionId=="string"?n.sessionId:"",s=n.params??{};for(let a of this.handlers.get(`${i}\0${r}`)??[])try{a(s)}catch{}}fail(t){if(!this.closed){this.closed=!0,this.closeReason=t;for(let[,n]of this.pending)clearTimeout(n.timer),n.reject(new k(t));this.pending.clear()}}send(t,n={},o={}){if(this.closed)return Promise.reject(new k(this.closeReason??"the connection is closed"));let r=this.nextId++,i=o.timeoutMs??Kt;return new Promise((s,a)=>{let c=setTimeout(()=>{this.pending.delete(r),a(new k(`${t} timed out after ${i}ms`))},i);this.pending.set(r,{resolve:s,reject:a,timer:c});let l={id:r,method:t,params:n};o.sessionId&&(l.sessionId=o.sessionId);try{this.socket.send(JSON.stringify(l))}catch(u){this.pending.delete(r),clearTimeout(c),a(new k(`could not send ${t}`,{cause:u}))}})}on(t,n,o){let r=`${t}\0${n}`,i=this.handlers.get(r)??new Set;return i.add(o),this.handlers.set(r,i),()=>{i.delete(o)}}close(){this.closed=!0;try{this.socket.close()}catch{}}};async function et(e,t=Vt){if(e.startsWith("ws://")||e.startsWith("wss://"))return{webSocketDebuggerUrl:e,product:""};let n=e.startsWith("http://")||e.startsWith("https://")?e.replace(/\/+$/,""):`http://${e.replace(/\/+$/,"")}`,o;try{o=await fetch(`${n}/json/version`,{signal:AbortSignal.timeout(t)})}catch(i){throw new k(`no debuggable Chrome answered at ${n}`,{cause:i})}if(!o.ok)throw new k(`${n}/json/version returned HTTP ${o.status}`);let r=await o.json().catch(()=>null);if(!r?.webSocketDebuggerUrl)throw new k(`${n}/json/version carried no webSocketDebuggerUrl`);return{webSocketDebuggerUrl:r.webSocketDebuggerUrl,product:r.Browser??""}}var xe=class e{connection;product;constructor(t,n){this.connection=t,this.product=n}static async connect(t){let n=await Qe.open(t.webSocketDebuggerUrl),o=t.product;if(!o){let r=await n.send("Browser.getVersion").catch(()=>({}));o=typeof r.product=="string"?r.product:""}return new e(n,o.replace(/^(?:Headless)?Chrome\//i,""))}async newContext(t){let{browserContextId:n}=await this.connection.send("Target.createBrowserContext",{disposeOnDetach:!0}),{targetId:o}=await this.connection.send("Target.createTarget",{url:"about:blank",browserContextId:n}),{sessionId:r}=await this.connection.send("Target.attachToTarget",{targetId:o,flatten:!0}),i=new Ze(this.connection,r,n,t.entryUrl);return await i.prepare(t.initScripts??[],t.viewport),i}close(){this.connection.close()}},Co=8,_o=1024*1024,Eo=new Set(["Image","Media","Font"]),Ze=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,o,r){this.connection=t,this.sessionId=n,this.browserContextId=o,this.entryHost=ze(r)}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",o=>{this.onRequestPaused(o)}),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",o=>{let r=o.frame;!r||r.parentId||typeof r.url=="string"&&(this.currentUrl=r.url)}),this.connection.on(this.sessionId,"Network.responseReceived",o=>{this.onResponse(o)}),this.connection.on(this.sessionId,"Network.loadingFinished",o=>{this.onLoadingFinished(o)});for(let o of t)await this.send("Page.addScriptToEvaluateOnNewDocument",{source:o})}send(t,n={},o){return this.connection.send(t,n,{sessionId:this.sessionId,timeoutMs:o})}onRequestPaused(t){let n=t.requestId;if(typeof n!="string")return;(Eo.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,o=t.requestId,r=t.response;if(typeof o!="string"||!r)return;if(n==="Document"){let a=typeof t.frameId=="string"?t.frameId:"";this.documentResponses.set(a,{status:typeof r.status=="number"?r.status:0,headers:To(r.headers??{})});return}if(n!=="Script"||this.scriptsStarted>=Co)return;let i=typeof r.url=="string"?r.url:"",s=ze(i);s&&(s!==this.entryHost&&s!==ze(this.currentUrl)||(this.scriptsStarted++,this.pendingScriptRequests.set(o,i)))}onLoadingFinished(t){let n=t.requestId;if(typeof n!="string")return;let o=this.pendingScriptRequests.get(n);o!==void 0&&(this.pendingScriptRequests.delete(n),this.send("Network.getResponseBody",{requestId:n}).then(r=>{let i=typeof r.body=="string"?r.body:"",s=r.base64Encoded===!0?Buffer.from(i,"base64").toString("utf8"):i;this.scripts.push({url:o,body:s.slice(0,_o)})}).catch(()=>{}))}async goto(t,n){this.domContentFired=!1,this.loadFired=!1;let o=await this.send("Page.navigate",{url:t},n),r=o.errorText;if(typeof r=="string"&&r.length>0)throw new k(`navigating to ${t} failed: ${r}`);let i=typeof o.frameId=="string"?o.frameId:"";return await this.waitFor(()=>this.domContentFired,n,`${t} never reached DOMContentLoaded`),this.currentUrl=await this.readLocation(t),this.documentResponses.get(i)??this.documentResponses.get("")??null}async waitForLoad(t){await this.waitFor(()=>this.loadFired,t,"load").catch(()=>{})}async waitFor(t,n,o){let r=Date.now()+n;for(;!t();){if(Date.now()>=r)throw new k(`timed out waiting for ${o}`);await new Promise(i=>setTimeout(i,25))}}async readLocation(t){let n=await this.evaluate("location.href",2e3).catch(()=>null);return typeof n=="string"&&n.length>0?n:t}async evaluate(t,n=Kt){let o=await this.send("Runtime.evaluate",{expression:t,awaitPromise:!0,returnByValue:!0},n),r=o.exceptionDetails;if(r)throw new k(r.exception?.description??r.text??"evaluation threw");return o.result?.value}async content(){return await this.evaluate("document.documentElement ? document.documentElement.outerHTML : ''").catch(()=>"")??""}async inlineScripts(){return await this.evaluate('Array.from(document.querySelectorAll("script:not([src])")).map(function (s) { return s.textContent || ""; }).join("\\n")').catch(()=>"")??""}url(){return this.currentUrl}collectedScripts(){return this.scripts.slice()}viewportSize(){return this.viewport}async screenshot(t,n){try{let r=(await this.send("Page.captureScreenshot",{format:"jpeg",quality:t,captureBeyondViewport:!1},n)).data;return typeof r!="string"||r.length===0?null:Buffer.from(r,"base64")}catch{return null}}async close(){await this.connection.send("Target.disposeBrowserContext",{browserContextId:this.browserContextId}).catch(()=>{})}};function To(e){let t={};for(let[n,o]of Object.entries(e)){let r=n.toLowerCase(),i=o.split(`
|
|
40
|
+
`).map(s=>s.trim()).filter(s=>s.length>0).join(", ");t[r]=t[r]===void 0?i:`${t[r]}, ${i}`}return t}function ze(e){try{return new URL(e).host}catch{return""}}var Po=new Set([2,3]),Io=8192,Oo=864e10;function Mo(e){if(typeof e!="string")return null;let t=e.trim();if(t.length===0||t.length>Io)return null;let n;try{n=Buffer.from(t,"base64")}catch{return null}if(n.length<=69||!Po.has(n[0])||n.readUInt32BE(65)!==n.length-69)return null;let r;try{r=JSON.parse(n.subarray(69).toString("utf8"))}catch{return null}if(!r||typeof r!="object")return null;let i=r,s=i.origin,a=i.feature,c=i.expiry;return typeof s!="string"||typeof a!="string"||typeof c!="number"||!Number.isFinite(c)||c<0||c>Oo?null:{origin:s,feature:a,expiry:c,isSubdomain:i.isSubdomain===!0,isThirdParty:i.isThirdParty===!0}}function No(e){return e.toLowerCase().replace(/[^a-z]/g,"").includes("modelcontext")}function jo(e,t,n){let o,r;try{o=new URL(e),r=new URL(t)}catch{return!1}if(o.protocol!==r.protocol)return!1;let i=o.hostname.toLowerCase(),s=r.hostname.toLowerCase();return i===s?!0:n&&s.endsWith(`.${i}`)}function Yt(e,t,n){let o=e.map(i=>i.trim()).filter(i=>i.length>0);if(o.length===0)return null;let r=null;for(let i of o){let s=Mo(i);if(!s)continue;let a=No(s.feature),c=s.expiry*1e3>n.getTime(),l=jo(s.origin,t,s.isSubdomain),u=a&&c&&l,p=u?3:a?2:1;(!r||p>r.rank)&&(r={parsed:s,valid:u,rank:p})}return r?{present:!0,valid:r.valid,origin:r.parsed.origin,feature:r.parsed.feature,expiresAt:new Date(r.parsed.expiry*1e3).toISOString()}:{present:!0,valid:!1}}function Xt(e){return e?e.split(",").map(t=>t.trim()).filter(t=>t.length>0):[]}var tt="capture-incomplete:";function Lo(e){return e.imperative!==null||e.polyfillPackages.length>0}function zt(e){return e.blocked?"blocked":e.loadError?"load-error":e.toolCount>0?e.nativeApi||e.originTrialValid||e.declarativeToolCount>0?"active":"testing-only":e.nativeApi?"api-empty":e.shimTakenOver||Lo(e.staticSignals)?"declared-inactive":"absent"}function Qt(e,t){switch(e){case"blocked":return"waf-blocked";case"load-error":return"unreachable";case"active":case"testing-only":{let n=t.filter(o=>o.via==="imperative");return n.length>0&&n.every(o=>!o.hasExecute)?"stub-only":"ok"}case"api-empty":case"declared-inactive":case"absent":return"no-tools";default:return e}}var Zt={"shared-experience":30,"task-completion":25,"tool-quality":25,trust:20},nt={"page-experience":{title:"Page experience",category:"shared-experience",weight:20,docSlug:"page-experience"},"human-parity":{title:"Human parity",category:"shared-experience",weight:10,docSlug:"human-parity"},"tool-selection":{title:"Tool selection",category:"task-completion",weight:15,docSlug:"tool-selection"},"coverage-vs-site-type":{title:"Coverage vs. site type",category:"task-completion",weight:10,docSlug:"coverage-vs-site-type"},"schema-validity":{title:"Schema validity",category:"tool-quality",weight:4,docSlug:"schema-validity"},"schema-quality":{title:"Schema quality",category:"tool-quality",weight:4,docSlug:"schema-quality"},"description-quality":{title:"Description quality",category:"tool-quality",weight:5,docSlug:"description-quality"},"stub-detection":{title:"Stub detection",category:"tool-quality",weight:4,docSlug:"stub-detection"},"canonical-entry-point":{title:"Canonical entry point",category:"tool-quality",weight:3,docSlug:"canonical-entry-point"},"naming-quality":{title:"Naming quality",category:"tool-quality",weight:2,docSlug:"naming-quality"},"registration-errors":{title:"Registration errors",category:"tool-quality",weight:2,docSlug:"registration-errors"},"registration-timing":{title:"Registration timing",category:"tool-quality",weight:1,docSlug:"registration-timing"},"annotations-present":{title:"Annotations present",category:"trust",weight:6,docSlug:"annotations-present"},"annotation-mismatch":{title:"Annotation mismatch",category:"trust",weight:6,docSlug:"annotation-mismatch"},"injection-surface":{title:"Injection surface",category:"trust",weight:4,docSlug:"injection-surface"},"untrusted-content-hint":{title:"Untrusted content hint",category:"trust",weight:4,docSlug:"untrusted-content-hint"}},z="1";function Wo(e,t,n){return!!(t["cf-mitigated"]==="challenge"||e===403&&n.includes("cf-browser-verification")||e===503&&n.includes("challenge-platform"))}function en(e,t,n){return!!(Wo(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 Do=100,nn=4096,Bo=32768,Uo=50,Jo=200,tn="__oraWebmcpCapture",rn=`(function () {
|
|
41
|
+
"use strict";
|
|
42
|
+
try {
|
|
43
|
+
var W = typeof globalThis !== "undefined" ? globalThis : window;
|
|
44
|
+
if (W.${tn}) return;
|
|
45
|
+
|
|
46
|
+
var SHIM_VERSION = ${JSON.stringify(z)};
|
|
47
|
+
var MAX_TOOLS = ${Do};
|
|
48
|
+
var MAX_DESCRIPTION_CHARS = ${nn};
|
|
49
|
+
var MAX_SCHEMA_CHARS = ${Bo};
|
|
50
|
+
var MAX_ERRORS = ${Uo};
|
|
51
|
+
// Internal bound only: a page looping on addEventListener must not grow
|
|
52
|
+
// the shim's retained set without limit.
|
|
53
|
+
var MAX_LISTENERS = 50;
|
|
54
|
+
|
|
55
|
+
// Natives are pinned at install time, while they are still pristine: this
|
|
56
|
+
// script runs before any page script, so everything captured here is the
|
|
57
|
+
// real implementation. Resolving them at call time instead would let a page
|
|
58
|
+
// swap performance.now (forging registrationMs, which feeds the
|
|
59
|
+
// registration-timing check), JSON (forging schemas), Array.isArray
|
|
60
|
+
// (steering provideContext), or Object.getOwnPropertyDescriptor (hiding a
|
|
61
|
+
// takeover) after the fact.
|
|
62
|
+
var nativeDefineProperty = Object.defineProperty;
|
|
63
|
+
var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
|
|
64
|
+
var nativeObjectCreate = Object.create;
|
|
65
|
+
var nativeIsArray = Array.isArray;
|
|
66
|
+
var nativeStringify = JSON.stringify;
|
|
67
|
+
var nativeParse = JSON.parse;
|
|
68
|
+
var nativeString = String;
|
|
69
|
+
var nativeTypeError = TypeError;
|
|
70
|
+
var nativeDateNow = Date.now;
|
|
71
|
+
var nativePromise = typeof Promise === "function" ? Promise : null;
|
|
72
|
+
var nativePerformanceNow = null;
|
|
73
|
+
try {
|
|
74
|
+
if (W.performance && typeof W.performance.now === "function") {
|
|
75
|
+
nativePerformanceNow = W.performance.now.bind(W.performance);
|
|
76
|
+
}
|
|
77
|
+
} catch (e) {
|
|
78
|
+
// A hostile performance getter cannot be pinned; the Date fallback holds.
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
var entries = [];
|
|
82
|
+
var byKey = nativeObjectCreate(null);
|
|
83
|
+
var listenersByType = nativeObjectCreate(null);
|
|
84
|
+
var errors = [];
|
|
85
|
+
var provideContextCalls = 0;
|
|
86
|
+
var toolchangeEvents = 0;
|
|
87
|
+
var extraToolCount = 0;
|
|
88
|
+
var nextRegId = 1;
|
|
89
|
+
|
|
90
|
+
function now() {
|
|
91
|
+
if (nativePerformanceNow) return nativePerformanceNow();
|
|
92
|
+
return nativeDateNow();
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Never throws, whatever the page put in the value: a description, an
|
|
96
|
+
// error message, or an event type can all carry a throwing toString.
|
|
97
|
+
function safeText(value, fallback) {
|
|
98
|
+
try {
|
|
99
|
+
return nativeString(value);
|
|
100
|
+
} catch (e) {
|
|
101
|
+
return fallback;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function describeError(value) {
|
|
106
|
+
var message;
|
|
107
|
+
try {
|
|
108
|
+
message = value ? value.message : undefined;
|
|
109
|
+
} catch (e) {
|
|
110
|
+
// A thrown object with a throwing message getter.
|
|
111
|
+
message = undefined;
|
|
112
|
+
}
|
|
113
|
+
if (message !== undefined && message !== null) {
|
|
114
|
+
return safeText(message, "unreadable error message");
|
|
115
|
+
}
|
|
116
|
+
return safeText(value, "unreadable error");
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function recordError(message) {
|
|
120
|
+
if (errors.length >= MAX_ERRORS) return;
|
|
121
|
+
errors.push(
|
|
122
|
+
safeText(message, "unstringifiable registration error").slice(0, 500)
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Cycle-safe: tracks the ANCESTOR chain (via the replacer's holder), not
|
|
127
|
+
// every object seen, so a schema that reuses one sub-schema in two places
|
|
128
|
+
// still serializes both copies instead of reporting a false cycle.
|
|
129
|
+
function cycleSafeStringify(value) {
|
|
130
|
+
var stack = [];
|
|
131
|
+
return nativeStringify(value, function (key, val) {
|
|
132
|
+
if (typeof val === "function") return undefined;
|
|
133
|
+
if (val && typeof val === "object") {
|
|
134
|
+
while (stack.length > 0 && stack[stack.length - 1] !== this) stack.pop();
|
|
135
|
+
if (stack.indexOf(val) !== -1) return "[Circular]";
|
|
136
|
+
stack.push(val);
|
|
137
|
+
}
|
|
138
|
+
return val;
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function safeCopy(value, maxChars) {
|
|
143
|
+
if (value === undefined || value === null) return null;
|
|
144
|
+
var json;
|
|
145
|
+
try {
|
|
146
|
+
json = cycleSafeStringify(value);
|
|
147
|
+
} catch (e) {
|
|
148
|
+
// Throwing getters, BigInt, or a structure too deep for JSON.stringify.
|
|
149
|
+
return { __unserializable: true };
|
|
150
|
+
}
|
|
151
|
+
if (typeof json !== "string") return null;
|
|
152
|
+
if (json.length > maxChars) return { __truncated: true };
|
|
153
|
+
try {
|
|
154
|
+
return nativeParse(json);
|
|
155
|
+
} catch (e) {
|
|
156
|
+
// Should not happen: nativeParse is the pinned native, and its input is
|
|
157
|
+
// this shim's own output. Kept so a copy failure never breaks a page.
|
|
158
|
+
return { __unserializable: true };
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function readProp(source, key) {
|
|
163
|
+
try {
|
|
164
|
+
return source[key];
|
|
165
|
+
} catch (e) {
|
|
166
|
+
// Property access on a page object can throw from a getter.
|
|
167
|
+
return undefined;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function hasExecute(tool) {
|
|
172
|
+
return (
|
|
173
|
+
typeof readProp(tool, "execute") === "function" ||
|
|
174
|
+
typeof readProp(tool, "callback") === "function"
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function markUnregistered(record, regId) {
|
|
179
|
+
if (!record || record.regId !== regId || record.unregistered) return;
|
|
180
|
+
record.unregistered = true;
|
|
181
|
+
record.unregisteredMs = now();
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Registers or refreshes ONE tool. Entries are keyed by source + name, so
|
|
185
|
+
// a re-registration updates in place and keeps its first registrationMs -
|
|
186
|
+
// the timing checks want when the tool first appeared, and a page that
|
|
187
|
+
// re-provides its set on every state change must not exhaust MAX_TOOLS.
|
|
188
|
+
function upsert(tool, source, entryPoint) {
|
|
189
|
+
var name = readProp(tool, "name");
|
|
190
|
+
if (typeof name !== "string" || name.trim() === "") {
|
|
191
|
+
var error = new nativeTypeError(
|
|
192
|
+
"WebMCP registration rejected: tool name must be a non-empty string"
|
|
193
|
+
);
|
|
194
|
+
recordError(error.message);
|
|
195
|
+
throw error;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// A name collision is a name collision whatever registered it: two live
|
|
199
|
+
// tools called "search" are ambiguous to an agent even when one came
|
|
200
|
+
// from registerTool and the other from provideContext. Both entries are
|
|
201
|
+
// kept; the warning is the evidence.
|
|
202
|
+
for (var d = 0; d < entries.length; d++) {
|
|
203
|
+
if (entries[d].name === name && !entries[d].unregistered) {
|
|
204
|
+
recordError("duplicate tool name registered: " + name);
|
|
205
|
+
break;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// A throwing toString must not drop the tool: record the defect and keep
|
|
210
|
+
// the registration, since an unreadable description is exactly what the
|
|
211
|
+
// description-quality check exists to see.
|
|
212
|
+
var description = "";
|
|
213
|
+
var rawDescription = readProp(tool, "description");
|
|
214
|
+
if (rawDescription !== undefined && rawDescription !== null) {
|
|
215
|
+
if (typeof rawDescription === "string") {
|
|
216
|
+
description = rawDescription;
|
|
217
|
+
} else {
|
|
218
|
+
try {
|
|
219
|
+
description = nativeString(rawDescription);
|
|
220
|
+
} catch (e) {
|
|
221
|
+
recordError(
|
|
222
|
+
"tool " + name + " has a description that could not be read as text"
|
|
223
|
+
);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
var descriptionTruncated = description.length > MAX_DESCRIPTION_CHARS;
|
|
228
|
+
if (descriptionTruncated) description = description.slice(0, MAX_DESCRIPTION_CHARS);
|
|
229
|
+
|
|
230
|
+
var record = byKey[source + ":" + name];
|
|
231
|
+
if (!record) {
|
|
232
|
+
if (entries.length >= MAX_TOOLS) {
|
|
233
|
+
extraToolCount++;
|
|
234
|
+
return null;
|
|
235
|
+
}
|
|
236
|
+
record = { name: name, registrationMs: now() };
|
|
237
|
+
entries.push(record);
|
|
238
|
+
byKey[source + ":" + name] = record;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
record.description = description;
|
|
242
|
+
record.descriptionTruncated = descriptionTruncated;
|
|
243
|
+
record.inputSchema = safeCopy(readProp(tool, "inputSchema"), MAX_SCHEMA_CHARS);
|
|
244
|
+
record.annotations = safeCopy(readProp(tool, "annotations"), MAX_SCHEMA_CHARS);
|
|
245
|
+
record.hasExecute = hasExecute(tool);
|
|
246
|
+
record.entryPoint = entryPoint;
|
|
247
|
+
record.source = source;
|
|
248
|
+
record.unregistered = false;
|
|
249
|
+
record.unregisteredMs = null;
|
|
250
|
+
record.regId = nextRegId++;
|
|
251
|
+
return record;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// The spec's unregistration path is the AbortSignal in options; the
|
|
255
|
+
// tool-carried fallback observes pages that put the signal on the tool
|
|
256
|
+
// object instead.
|
|
257
|
+
function resolveSignal(tool, options) {
|
|
258
|
+
var signal = readProp(options, "signal");
|
|
259
|
+
if (!signal) signal = readProp(tool, "signal");
|
|
260
|
+
return signal || null;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// Callers with an already-aborted signal never reach here: registerTool
|
|
264
|
+
// rejects those before any record exists.
|
|
265
|
+
function wireAbort(signal, record, regId) {
|
|
266
|
+
if (!signal || typeof readProp(signal, "addEventListener") !== "function") return;
|
|
267
|
+
try {
|
|
268
|
+
signal.addEventListener("abort", function () {
|
|
269
|
+
markUnregistered(record, regId);
|
|
270
|
+
});
|
|
271
|
+
} catch (e) {
|
|
272
|
+
// A signal-like object that is not a real AbortSignal: capture is
|
|
273
|
+
// best-effort here and must never break the page's registration.
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// The draft's registerTool returns a Promise, and legacy pages hold the
|
|
278
|
+
// return value for its unregister method - so the shim returns a settled
|
|
279
|
+
// promise CARRYING unregister, serving both shapes at once (the agent
|
|
280
|
+
// invoke shim does the same). The internal catch marks the rejected path
|
|
281
|
+
// handled, so a page that ignores the return value produces no unhandled
|
|
282
|
+
// rejection from our shim.
|
|
283
|
+
function registration(settledPromise, unregister) {
|
|
284
|
+
settledPromise.catch(function () {});
|
|
285
|
+
settledPromise.unregister = unregister;
|
|
286
|
+
return settledPromise;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function noop() {}
|
|
290
|
+
|
|
291
|
+
function registerTool(tool, options, entryPoint) {
|
|
292
|
+
var signal = resolveSignal(tool, options);
|
|
293
|
+
if (signal && readProp(signal, "aborted") === true) {
|
|
294
|
+
// Already aborted at register time: the registration never lands, and
|
|
295
|
+
// per the draft the promise rejects with the abort reason.
|
|
296
|
+
var reason = readProp(signal, "reason");
|
|
297
|
+
if (!nativePromise) return { unregister: noop };
|
|
298
|
+
return registration(
|
|
299
|
+
nativePromise.reject(
|
|
300
|
+
reason === undefined
|
|
301
|
+
? new nativeTypeError("registration signal already aborted")
|
|
302
|
+
: reason
|
|
303
|
+
),
|
|
304
|
+
noop
|
|
305
|
+
);
|
|
306
|
+
}
|
|
307
|
+
var record = upsert(tool, "registerTool", entryPoint);
|
|
308
|
+
var regId = record ? record.regId : -1;
|
|
309
|
+
wireAbort(signal, record, regId);
|
|
310
|
+
// A capped registration (record null) still resolves: the page did
|
|
311
|
+
// nothing wrong, the shim just stopped recording past MAX_TOOLS.
|
|
312
|
+
var unregister = record
|
|
313
|
+
? function () { markUnregistered(record, regId); }
|
|
314
|
+
: noop;
|
|
315
|
+
if (!nativePromise) return { unregister: unregister };
|
|
316
|
+
return registration(nativePromise.resolve(undefined), unregister);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function provideContext(context, entryPoint) {
|
|
320
|
+
provideContextCalls++;
|
|
321
|
+
var tools = readProp(context, "tools");
|
|
322
|
+
if (tools === undefined || tools === null) tools = [];
|
|
323
|
+
if (!nativeIsArray(tools)) {
|
|
324
|
+
recordError("provideContext called with a non-array tools value");
|
|
325
|
+
tools = [];
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// Replacement semantics apply to the provideContext-sourced set only:
|
|
329
|
+
// mark it superseded BEFORE the new set lands, so re-providing a tool
|
|
330
|
+
// reactivates its entry instead of reading as a duplicate registration,
|
|
331
|
+
// and registerTool-sourced tools are left alone.
|
|
332
|
+
for (var i = 0; i < entries.length; i++) {
|
|
333
|
+
if (entries[i].source === "provideContext") {
|
|
334
|
+
markUnregistered(entries[i], entries[i].regId);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
for (var j = 0; j < tools.length; j++) {
|
|
339
|
+
var errorsBefore = errors.length;
|
|
340
|
+
try {
|
|
341
|
+
upsert(tools[j], "provideContext", entryPoint);
|
|
342
|
+
} catch (e) {
|
|
343
|
+
// One invalid tool must not drop the rest of the provided set, but
|
|
344
|
+
// it must never vanish silently either: upsert records the reason
|
|
345
|
+
// for the failures it raises itself, and anything else that escaped
|
|
346
|
+
// (a throwing getter on the tool object) is recorded here.
|
|
347
|
+
if (errors.length === errorsBefore) {
|
|
348
|
+
recordError(
|
|
349
|
+
"provideContext tool at index " + j + " failed to register: " +
|
|
350
|
+
describeError(e)
|
|
351
|
+
);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
return nativePromise ? nativePromise.resolve() : undefined;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
function addEventListener(type, listener) {
|
|
359
|
+
if (typeof listener !== "function") return;
|
|
360
|
+
var key = safeText(type, "");
|
|
361
|
+
var list = listenersByType[key];
|
|
362
|
+
if (!list) {
|
|
363
|
+
list = [];
|
|
364
|
+
listenersByType[key] = list;
|
|
365
|
+
}
|
|
366
|
+
if (list.length < MAX_LISTENERS) list.push(listener);
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function removeEventListener(type, listener) {
|
|
370
|
+
var list = listenersByType[safeText(type, "")];
|
|
371
|
+
if (!list) return;
|
|
372
|
+
var index = list.indexOf(listener);
|
|
373
|
+
if (index !== -1) list.splice(index, 1);
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
function dispatchEvent(event) {
|
|
377
|
+
var rawType = readProp(event, "type");
|
|
378
|
+
var type = safeText(
|
|
379
|
+
rawType === undefined || rawType === null ? event : rawType,
|
|
380
|
+
""
|
|
381
|
+
);
|
|
382
|
+
if (type === "toolchange") toolchangeEvents++;
|
|
383
|
+
|
|
384
|
+
var list = listenersByType[type];
|
|
385
|
+
if (list) {
|
|
386
|
+
for (var i = 0; i < list.length; i++) {
|
|
387
|
+
try {
|
|
388
|
+
list[i](event);
|
|
389
|
+
} catch (e) {
|
|
390
|
+
recordError("listener for " + type + " threw: " + describeError(e));
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
return true;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
// Two distinct delegate objects over one registry, so we can tell which
|
|
398
|
+
// global the page reached for.
|
|
399
|
+
function createDelegate(entryPoint) {
|
|
400
|
+
return {
|
|
401
|
+
registerTool: function (tool, options) {
|
|
402
|
+
return registerTool(tool, options, entryPoint);
|
|
403
|
+
},
|
|
404
|
+
provideContext: function (context) {
|
|
405
|
+
return provideContext(context, entryPoint);
|
|
406
|
+
},
|
|
407
|
+
addEventListener: addEventListener,
|
|
408
|
+
removeEventListener: removeEventListener,
|
|
409
|
+
dispatchEvent: dispatchEvent
|
|
410
|
+
};
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
// Every entry point we installed on, so snapshot() can prove the shim is
|
|
414
|
+
// still the one answering. The getter is null when the install itself failed.
|
|
415
|
+
var installs = [];
|
|
416
|
+
|
|
417
|
+
function install(target, delegate, label) {
|
|
418
|
+
if (!target) return;
|
|
419
|
+
var getter = function () {
|
|
420
|
+
return delegate;
|
|
421
|
+
};
|
|
422
|
+
try {
|
|
423
|
+
nativeDefineProperty(target, "modelContext", {
|
|
424
|
+
// Deliberately configurable: making it non-configurable would give a
|
|
425
|
+
// legitimate polyfill a page-visible TypeError. A page CAN therefore
|
|
426
|
+
// redefine the property and take the entry point away from us, which
|
|
427
|
+
// is what detectTakeovers reports.
|
|
428
|
+
configurable: true,
|
|
429
|
+
enumerable: true,
|
|
430
|
+
get: getter,
|
|
431
|
+
set: function () {
|
|
432
|
+
// A page polyfill assigning its own implementation over the shim
|
|
433
|
+
// would blind the capture and produce a false "absent" verdict.
|
|
434
|
+
// The assignment is accepted silently and ignored: feature
|
|
435
|
+
// detection still passes and registrations through the global
|
|
436
|
+
// still land here.
|
|
437
|
+
}
|
|
438
|
+
});
|
|
439
|
+
installs.push({ target: target, getter: getter, label: label });
|
|
440
|
+
} catch (e) {
|
|
441
|
+
recordError("could not install shim on " + label + ": " + describeError(e));
|
|
442
|
+
installs.push({ target: target, getter: null, label: label });
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
// Rechecked at snapshot time, not at install time: a page script can
|
|
447
|
+
// redefine the property at any point after we run, and an empty tools list
|
|
448
|
+
// must not be reported as absence when that happened.
|
|
449
|
+
function detectTakeovers() {
|
|
450
|
+
var taken = [];
|
|
451
|
+
for (var i = 0; i < installs.length; i++) {
|
|
452
|
+
var descriptor;
|
|
453
|
+
try {
|
|
454
|
+
descriptor = nativeGetOwnPropertyDescriptor(
|
|
455
|
+
installs[i].target,
|
|
456
|
+
"modelContext"
|
|
457
|
+
);
|
|
458
|
+
} catch (e) {
|
|
459
|
+
// An exotic target that refuses introspection counts as taken over.
|
|
460
|
+
descriptor = undefined;
|
|
461
|
+
}
|
|
462
|
+
if (!descriptor || descriptor.get !== installs[i].getter) {
|
|
463
|
+
taken.push(installs[i].label);
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
return taken;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
install(W.navigator, createDelegate("navigator"), "navigator");
|
|
470
|
+
install(W.document, createDelegate("document"), "document");
|
|
471
|
+
|
|
472
|
+
function snapshot() {
|
|
473
|
+
var tools = [];
|
|
474
|
+
for (var i = 0; i < entries.length; i++) {
|
|
475
|
+
var e = entries[i];
|
|
476
|
+
tools.push({
|
|
477
|
+
name: e.name,
|
|
478
|
+
description: e.description,
|
|
479
|
+
descriptionTruncated: e.descriptionTruncated,
|
|
480
|
+
inputSchema: e.inputSchema,
|
|
481
|
+
annotations: e.annotations,
|
|
482
|
+
hasExecute: e.hasExecute,
|
|
483
|
+
entryPoint: e.entryPoint,
|
|
484
|
+
source: e.source,
|
|
485
|
+
registrationMs: e.registrationMs,
|
|
486
|
+
unregistered: e.unregistered,
|
|
487
|
+
unregisteredMs: e.unregisteredMs
|
|
488
|
+
});
|
|
489
|
+
}
|
|
490
|
+
return {
|
|
491
|
+
shimVersion: SHIM_VERSION,
|
|
492
|
+
tools: tools,
|
|
493
|
+
provideContextCalls: provideContextCalls,
|
|
494
|
+
toolchangeEvents: toolchangeEvents,
|
|
495
|
+
registrationErrors: errors.slice(),
|
|
496
|
+
extraToolCount: extraToolCount,
|
|
497
|
+
takenOver: detectTakeovers()
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
// Non-writable and non-configurable: the capture payload is the audit's
|
|
502
|
+
// evidence, so a page must not be able to replace snapshot() and report
|
|
503
|
+
// whatever tools it wishes it had.
|
|
504
|
+
nativeDefineProperty(W, ${JSON.stringify(tn)}, {
|
|
505
|
+
value: {
|
|
506
|
+
shimVersion: SHIM_VERSION,
|
|
507
|
+
installedAt: now(),
|
|
508
|
+
snapshot: snapshot
|
|
509
|
+
},
|
|
510
|
+
writable: false,
|
|
511
|
+
configurable: false,
|
|
512
|
+
enumerable: false
|
|
513
|
+
});
|
|
514
|
+
} catch (installError) {
|
|
515
|
+
try {
|
|
516
|
+
console.warn("[ora-webmcp-shim] install failed", installError);
|
|
517
|
+
} catch (loggingError) {
|
|
518
|
+
// Nothing left to report to; never let the shim break the page.
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
})();`,on=`(function () {
|
|
522
|
+
var MAX_FORMS = ${Jo};
|
|
523
|
+
var MAX_DESCRIPTION_CHARS = ${nn};
|
|
524
|
+
var forms = [];
|
|
525
|
+
var nodes = document.querySelectorAll("form[toolname], [toolname]");
|
|
526
|
+
for (var i = 0; i < nodes.length && forms.length < MAX_FORMS; i++) {
|
|
527
|
+
var node = nodes[i];
|
|
528
|
+
var isForm = node.tagName === "FORM";
|
|
529
|
+
var description = node.getAttribute("tooldescription") || "";
|
|
530
|
+
forms.push({
|
|
531
|
+
toolName: node.getAttribute("toolname") || "",
|
|
532
|
+
toolDescription: description.slice(0, MAX_DESCRIPTION_CHARS),
|
|
533
|
+
action: isForm ? node.getAttribute("action") || "" : "",
|
|
534
|
+
method: isForm ? (node.getAttribute("method") || "get").toLowerCase() : "",
|
|
535
|
+
fieldCount: node.querySelectorAll("input, select, textarea").length
|
|
536
|
+
});
|
|
537
|
+
}
|
|
538
|
+
return { forms: forms };
|
|
539
|
+
})()`;var an=["@mcp-b/global","@mcp-b/react-webmcp","usewebmcp"];function Fo(e){let t=e.toLowerCase(),n=/document\.modelcontext/.test(t),o=/navigator\.modelcontext/.test(t),r=/modelcontext\??\.(registertool|providecontext)/.test(t),i=an.find(a=>t.includes(a));return!n&&!o&&!r&&!i?null:{marker:n?"document.modelContext":o?"navigator.modelContext":r?"modelContext.registerTool/provideContext":`${i} package`,deprecatedAliasOnly:o&&!n}}var Ho=["webmcp","web model context protocol"];function sn(e){let t=e.toLowerCase();return Ho.some(n=>t.includes(n))}function cn(e,t,n){let o=[t,...n.map(a=>a.body)],r=Fo(o.join(`
|
|
540
|
+
`)),i=new Set;for(let a of o){let c=a.toLowerCase();for(let l of an)c.includes(l)&&i.add(l)}let s=sn(e)||o.some(sn);return{imperative:r,polyfillPackages:[...i],keywordMention:s}}var dn=15e3,Go=3e4,qo=2e3,Ko=250,Vo={fast:12e3,deep:2e4},Yo=2*1024*1024,pn=512,Xo=512,zo=60,Qo=15e5,mn={width:1280,height:720},ln={imperative:null,polyfillPackages:[],keywordMention:!1},Zo=`(function () {
|
|
541
|
+
var tokens = [];
|
|
542
|
+
try {
|
|
543
|
+
var metas = document.querySelectorAll('meta[http-equiv="origin-trial" i]');
|
|
544
|
+
for (var i = 0; i < metas.length && tokens.length < 20; i++) {
|
|
545
|
+
var content = metas[i].getAttribute("content");
|
|
546
|
+
if (content) tokens.push(content);
|
|
547
|
+
}
|
|
548
|
+
} catch (e) {
|
|
549
|
+
// A document without a queryable DOM still answers the native probe.
|
|
550
|
+
}
|
|
551
|
+
var nativeApi = false;
|
|
552
|
+
try {
|
|
553
|
+
nativeApi = ("modelContext" in navigator) || ("modelContext" in document);
|
|
554
|
+
} catch (e) {
|
|
555
|
+
// A hostile getter on either global; absence is the honest answer.
|
|
556
|
+
}
|
|
557
|
+
return { nativeApi: nativeApi, metaTokens: tokens };
|
|
558
|
+
})()`,gn=`(function () {
|
|
559
|
+
try {
|
|
560
|
+
var g = window.__oraWebmcpCapture;
|
|
561
|
+
return g ? g.snapshot() : null;
|
|
562
|
+
} catch (e) {
|
|
563
|
+
return null;
|
|
564
|
+
}
|
|
565
|
+
})()`,ei=`(function () {
|
|
566
|
+
try {
|
|
567
|
+
var g = window.__oraWebmcpCapture;
|
|
568
|
+
if (!g) return "none";
|
|
569
|
+
var s = g.snapshot();
|
|
570
|
+
return s.tools.length + ":" + s.provideContextCalls + ":" + s.toolchangeEvents + ":" +
|
|
571
|
+
s.registrationErrors.length + ":" + s.extraToolCount + ":" + s.takenOver.length;
|
|
572
|
+
} catch (e) {
|
|
573
|
+
return "error";
|
|
574
|
+
}
|
|
575
|
+
})()`;function hn(e,t){return e.filter(n=>!n.unregistered).map(n=>({name:n.name.slice(0,pn),description:n.description,via:"imperative",entryPoint:n.source==="provideContext"?"provideContext":n.entryPoint,pageUrl:t,inputSchema:n.inputSchema,annotations:ni(n.annotations),hasExecute:n.hasExecute,registrationMs:n.registrationMs}))}function ti(e,t){return e.map(n=>({name:n.toolName.slice(0,pn),description:n.toolDescription,via:"declarative",entryPoint:"form",pageUrl:t,inputSchema:null,annotations:{},hasExecute:!0,registrationMs:null}))}function ni(e){if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e,n={};for(let o of["readOnlyHint","destructiveHint","idempotentHint","openWorldHint","untrustedContentHint"])typeof t[o]=="boolean"&&(n[o]=t[o]);return typeof t.title=="string"&&(n.title=t.title.slice(0,Xo)),n}function ri(e){if(!e)return[];let t=[...e.registrationErrors];return e.takenOver.length>0&&t.push(`${tt} the page replaced modelContext on ${e.takenOver.join(", ")}, so imperative tools may be under-reported`),e.extraToolCount>0&&t.push(`${tt} the capture's tool cap was reached and ${e.extraToolCount} further registration attempts were not stored`),t}function oi(e){if(!e)return null;for(let t of e.split(",")){let n=/^\s*([a-z0-9-]+)\s*=\s*(.*)$/i.exec(t);if(!n||!n[1].toLowerCase().replace(/-/g,"").includes("modelcontext"))continue;let o=n[2].trim().replace(/^\(|\)$/g,"").trim();return o==="*"?!0:o===""||o.toLowerCase()==="self"?!1:o.split(/\s+/).some(r=>r.toLowerCase()!=="self"&&r.length>0)}return null}async function ii(e,t,n,o){let r=Date.now(),i={finalUrl:t,navMs:0,blocked:!1,nativeApi:!1,originTrialTokens:[],permissionsPolicy:null,html:"",inlineJs:"",scripts:[],screenshot:null,loadError:null},s=null;try{s=await e.newContext({entryUrl:t,viewport:mn});let a;try{a=await s.goto(t,ke(n,dn))}catch(h){return{...i,navMs:Date.now()-r,loadError:Ae(h)}}let c=Date.now()-r;await s.waitForLoad(ke(n,5e3));let l=a?.headers??{},u=a?.status??0,p=(await s.content()).slice(0,Yo),g=await s.inlineScripts(),d=await s.evaluate(Zo).catch(()=>null)??{},f=o?await ui(s,n):null;return{finalUrl:s.url(),navMs:c,blocked:en(u,l,p),nativeApi:d.nativeApi===!0,originTrialTokens:[...Xt(l["origin-trial"]),...Array.isArray(d.metaTokens)?d.metaTokens:[]],permissionsPolicy:l["permissions-policy"]??null,html:p,inlineJs:g,scripts:s.collectedScripts(),screenshot:f,loadError:null}}catch(a){return{...i,navMs:Date.now()-r,loadError:Ae(a)}}finally{await s?.close()}}async function si(e,t,n,o,r){let i=null;try{i=await e.newContext({initScripts:[rn],entryUrl:t,viewport:mn});try{await i.goto(t,ke(o,dn))}catch(l){return{snapshot:null,declarative:null,quietMs:0,loadError:Ae(l)}}let s=await ai(i,n,o,r),a=await i.evaluate(gn).catch(()=>null),c=await i.evaluate(on).catch(()=>null);return{snapshot:a,declarative:c,quietMs:s,loadError:null}}catch(s){return{snapshot:null,declarative:null,quietMs:0,loadError:Ae(s)}}finally{await i?.close()}}async function ai(e,t,n,o){let r=Date.now(),i=Math.min(Vo[t],Math.max(0,n-r)),s=null,a=r;for(;Date.now()-r<i;){let c=await e.evaluate(ei).catch(()=>null);if(c!==s)s=typeof c=="string"?c:null,a=Date.now(),o&&await ci(e,o);else if(Date.now()-a>=qo)break;if(await pi(Math.min(Ko,Math.max(0,n-Date.now()))),Date.now()>=n)break}return Date.now()-r}async function ci(e,t){let n=await e.evaluate(gn).catch(()=>null);n&&t(hn(n.tools,e.url()))}async function li(e,t,n,o,r){let i=Date.now(),s=i+Go,a=await ii(e,t,s,o),l=a.loadError!==null||a.blocked?{snapshot:null,declarative:null,quietMs:0,loadError:null}:await si(e,t,n,s,r),u=a.loadError??l.loadError,p=l.snapshot,g=(l.declarative?.forms??[]).filter(F=>F.toolName.trim()!==""),d=a.finalUrl||t,f=p?hn(p.tools,d):[],h=ti(g,d),m=[...f,...h],y=di(a.html,a.inlineJs,a.scripts),x=Yt(a.originTrialTokens,un(d)??un(t)??"",new Date),T={loadError:u,blocked:a.blocked,nativeApi:a.nativeApi,originTrialValid:x?.valid===!0,declarativeToolCount:h.length,toolCount:m.length,shimTakenOver:(p?.takenOver.length??0)>0,staticSignals:y},N=zt(T);return{page:{url:t,finalUrl:d,verdict:N,status:Qt(N,m),tools:m,declarativeFormCount:h.length,consumer:{nativeApi:a.nativeApi,originTrial:x,permissionsPolicy:a.permissionsPolicy,iframeAllow:oi(a.permissionsPolicy)},staticSignals:y,apiSurface:{toolchangeEvents:p?.toolchangeEvents??0,provideContextCalls:p?.provideContextCalls??0,registrationErrors:ri(p)},timing:{navMs:a.navMs,quietMs:l.quietMs,totalMs:Date.now()-i},error:u},screenshot:a.blocked?null:a.screenshot}}async function fn(e){let{url:t,endpoint:n,mode:o="fast",screenshot:r=!0,onTools:i}=e,s=Date.now(),a=new Date().toISOString(),c=await xe.connect(n);try{let l=await li(c,t,o,r,i);return{url:t,pages:[l.page],chromeVersion:c.product,shimVersion:z,capturedAt:a,durationMs:Date.now()-s,screenshot:l.screenshot}}finally{c.close()}}async function ui(e,t){let n=await e.screenshot(zo,ke(t,5e3));if(!n||n.byteLength===0||n.byteLength>Qo)return null;let o=e.viewportSize();return{data:n.toString("base64"),mimeType:"image/jpeg",width:o?.width??0,height:o?.height??0}}function di(e,t,n){if(!e)return ln;try{return cn(e,t,n)}catch{return ln}}function un(e){try{return new URL(e).origin}catch{return null}}function Ae(e){return(e instanceof Error?e.message:String(e)).split(`
|
|
576
|
+
`)[0].slice(0,300)}function ke(e,t){return Math.max(250,Math.min(t,e-Date.now()))}function pi(e){return new Promise(t=>setTimeout(t,e))}var bn=require("child_process"),W=require("fs"),wn=require("os"),ot=require("path");var vn=9222;async function Sn(e){if(e)try{return{ok:!0,endpoint:await et(e),close:async()=>{},launched:!1}}catch(t){let n=rt(t);return{ok:!1,message:[`No debuggable Chrome answered at ${e}.`,...n.startsWith("no debuggable Chrome answered")?[]:[n],"",...mi(vn)].join(`
|
|
577
|
+
`)}}try{let t=await xi();return{ok:!0,endpoint:t.endpoint,close:t.close,launched:!0}}catch(t){return{ok:!1,message:rt(t)}}}function xn(e){return e.pages.some(t=>t.consumer.nativeApi)?["This Chrome provides WebMCP itself. ora captures with a browser that does not,","so anything that depended on the browser rather than on your page can read","differently there.","","Where that actually changed a result, ora says so in the availability reason","above - read that rather than this. This notice only reports what the browser","did, because deciding whether it changed the outcome is ora's job, not the","CLI's.","","If you started Chrome with --enable-features=WebMCPTesting, drop the flag (or","omit --chrome-endpoint and let this command start its own).","","Keep a flag-enabled Chrome for `npx @ora-ai/webmcp-verify`, which needs the API","present in order to call your tools."].join(`
|
|
578
|
+
`):null}function mi(e){return["The audit drives a Chrome you already have; it never downloads one.","Start one with a debugging port and a scratch profile:","",` ${An(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 An(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 rt(e){return e instanceof k||e instanceof Error?e.message:String(e)}function gi(){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 hi(){for(let e of gi())try{if((0,W.statSync)(e).isFile())return e}catch{}return null}var fi=["--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 yi(){return process.env.AX_WEBMCP_NO_SANDBOX==="1"}var yn=2e4,bi=3e3,wi=4,vi=150;function Si(e,t){return e.exitCode!==null||e.signalCode!==null?Promise.resolve():new Promise(n=>{let o=()=>{clearTimeout(r),e.off("exit",o),n()},r=setTimeout(o,t);e.once("exit",o)})}async function xi(){let e=hi();if(!e)throw new k($i());let t=(0,W.mkdtempSync)((0,ot.join)((0,wn.tmpdir)(),"ax-webmcp-")),n=(0,bn.spawn)(e,[...fi,...yi()?["--no-sandbox"]:[],"--remote-debugging-port=0",`--user-data-dir=${t}`,"about:blank"],{stdio:"ignore",detached:!0}),o=i=>{r().finally(()=>{process.removeListener("SIGINT",o),process.removeListener("SIGTERM",o),process.kill(process.pid,i)})},r=async()=>{process.removeListener("SIGINT",o),process.removeListener("SIGTERM",o);let i=n.pid;try{i!==void 0?process.kill(-i,"SIGTERM"):n.kill("SIGTERM")}catch{try{n.kill("SIGTERM")}catch{}}await Si(n,bi),await ki(t)};process.once("SIGINT",o),process.once("SIGTERM",o);try{let i=await Ai(t,n);return{endpoint:await et(`127.0.0.1:${i}`),close:r}}catch(i){throw await r(),i instanceof k?i:new k(rt(i))}}async function Ai(e,t){let n=(0,ot.join)(e,"DevToolsActivePort"),o=Date.now()+yn;for(;Date.now()<o;){if(t.exitCode!==null)throw new k(`Chrome exited with code ${t.exitCode} before it was ready.`);try{let r=(0,W.readFileSync)(n,"utf8").split(`
|
|
579
|
+
`)[0]?.trim(),i=Number(r);if(Number.isInteger(i)&&i>0)return i}catch{}await new Promise(r=>setTimeout(r,100))}throw new k(`Chrome did not publish a debugging port within ${yn/1e3}s.`)}async function ki(e){for(let t=0;t<wi;t++){try{if((0,W.rmSync)(e,{recursive:!0,force:!0}),!(0,W.existsSync)(e))return}catch{}await new Promise(n=>setTimeout(n,vi))}try{(0,W.rmSync)(e,{recursive:!0,force:!0})}catch{}}function $i(){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:","",` ${An(vn)}`].join(`
|
|
580
|
+
`)}var Ri="https://ora.ai",Ci=12e4,I=class extends Error{code;retryAfterMs;constructor(t,n={}){super(t),this.name="WebmcpIngestError",this.code=n.code??null,this.retryAfterMs=n.retryAfterMs??null}},kn=4*1024*1024,$n=10,Rn=100,Cn=32768,_n=4096,En=512;function Tn(e){if(e.shimVersion!==z)return`this build captures with shim version ${e.shimVersion}, which is not the version it was built against (${z})`;if(e.pages.length>$n)return`capture covers ${e.pages.length} pages; the limit is ${$n}`;for(let t of e.pages){if(t.tools.length>Rn)return`${t.url} registered ${t.tools.length} tools; the limit is ${Rn} per page`;for(let n of t.tools){if(n.name.length>En)return`tool name on ${t.url} is ${n.name.length} characters; the limit is ${En}`;if(n.description.length>_n)return`description for "${n.name}" is ${n.description.length} characters; the limit is ${_n}`;for(let[o,r]of[["inputSchema",n.inputSchema],["annotations",n.annotations]]){let i=_i(r);if(i===null)return`${o} for "${n.name}" could not be serialized (a cycle, or a value JSON cannot carry)`;if(i.length>Cn)return`${o} for "${n.name}" serializes to ${i.length} characters; the limit is ${Cn}`}}}return null}function Pn(e){let t=e.screenshot;if(!t)return{capture:e,droppedScreenshot:!1};let n=t.data.length>2*1024*1024,o=t.mimeType!=="image/jpeg";return!n&&!o?{capture:e,droppedScreenshot:!1}:{capture:{...e,screenshot:null},droppedScreenshot:!0}}function _i(e){try{return JSON.stringify(e)??"null"}catch{return null}}async function In(e,t,n={}){let o=(n.baseUrl??process.env.ORA_API_URL??Ri).replace(/\/+$/,""),r=n.idleMs??Ci,i=H(r),s=()=>new I(`ora scoring timed out \u2014 no progress for ${Math.round(r/1e3)}s`),a=JSON.stringify({url:e,capture:t});if(Buffer.byteLength(a,"utf8")>kn)throw i.disarm(),new I(`this capture serializes to ${Math.round(Buffer.byteLength(a,"utf8")/1024)} KB; the ingest limit is ${kn/1024/1024} MB`,{code:"BODY_TOO_LARGE"});let c;try{c=await fetch(`${o}/api/webmcp/audit/ingest`,{method:"POST",headers:{accept:"text/event-stream","content-type":"application/json",...n.apiKey?{authorization:`Bearer ${n.apiKey}`}:{}},body:a,signal:i.signal})}catch(l){throw i.disarm(),i.tripped()?s():new I(`ora ingest request failed: ${l instanceof Error?l.message:String(l)}`)}if(!c.ok||!c.body)throw i.disarm(),await Ei(c);return Ti(c,i,n,s)}async function Ei(e){let t=await e.clone().json().catch(()=>null),n=t?.code??null;if(e.status===429){let o=Number(e.headers.get("retry-after")),r=t?.retry_after_ms??(Number.isFinite(o)&&o>0?o*1e3:null),i=r?` \u2014 retry in ${Math.ceil(r/1e3)}s`:"";return new I(`ora rate limit exceeded${i} (10/min and 20 per 24h per IP). An ora API key lifts these limits: set ORA_API_KEY or pass --api-key.`,{code:n??"RATE_LIMITED",retryAfterMs:r})}return n==="SHIM_VERSION_MISMATCH"?new I(`This ax build captures with a shim ora no longer scores, so the audit was refused.
|
|
581
|
+
Upgrade with \`npm i -g ax@latest\` (or \`npx ax@latest webmcp-audit \u2026\`) and run it again.
|
|
582
|
+
|
|
583
|
+
ora said: ${t?.error??"shim version mismatch"}`,{code:n}):e.status===503?new I(`ora cannot score right now: ${Pi(t?.error??"scoring is unavailable")} Nothing was spent against your rate limit; try again shortly.`,{code:n??"SCORING_UNAVAILABLE"}):new I(`ora ingest failed: ${t?.error??await G(e)}`,{code:n})}async function Ti(e,t,n,o){let r=new TextDecoder,i="",s;try{e:for await(let a of e.body){t.poke(),i=`${i}${r.decode(a,{stream:!0})}`.replace(/\r\n?/g,`
|
|
584
|
+
`);let c=i.indexOf(`
|
|
585
|
+
|
|
586
|
+
`);for(;c!==-1;){let l=Ii(i.slice(0,c));if(i=i.slice(c+2),c=i.indexOf(`
|
|
587
|
+
|
|
588
|
+
`),!l)continue;let u;try{u=JSON.parse(l)}catch{continue}if(n.onEvent?.(u),u.type==="error")throw new I(`ora audit failed: ${u.message}`,{code:u.status});if(u.type==="done"){s=u.audit;break e}}}}catch(a){throw t.tripped()?o():a instanceof I?a:new I(`ora ingest stream failed: ${a instanceof Error?a.message:String(a)}`)}finally{t.disarm()}if(!s)throw new I("ora ingest stream ended before the audit completed");return s}function Pi(e){let t=e.trim();return/[.!?]$/.test(t)?t:`${t}.`}function Ii(e){let t=[];for(let n of e.split(`
|
|
589
|
+
`))n.startsWith("data:")&&t.push(n.slice(5).replace(/^ /,""));return t.join(`
|
|
590
|
+
`)}var b=U(D(),1);var it=12,Oi=["fail","warning","unmeasured","na","pass"],st={fail:["\u2716",b.default.red],warning:["\u25B2",b.default.yellow],unmeasured:["?",b.default.magenta],na:["\u2013",b.default.dim],pass:["\u2714",b.default.green]},Mi={fail:"Failing",warning:"Warnings",unmeasured:"Not measured",na:"Not applicable",pass:"Passing"},Ni=["shared-experience","task-completion","tool-quality","trust"],ji={"shared-experience":"Shared experience","task-completion":"Task completion","tool-quality":"Tool quality",trust:"Trust"};function On(e,t={}){let n=q(80,120),o=e.availability.status==="ready";return["",...Li(e,n),"",...Di(e.availability,n),...o?["",...Bi(e,n),"",...Ji(e)]:[],"",...Hi(e.findings,n,t.showPassing===!0),...Ki(e.simulation,n),"",...Vi(e,n)]}function Li(e,t){let n=[` ${b.default.bold(R(e.url))}`],o=`${e.toolCount} tool${e.toolCount===1?"":"s"}`,r=[Wi(e.verdict),o,`Chrome ${R(e.chromeVersion)}`];return e.error&&r.push(b.default.red(R(e.error))),n.push(` ${b.default.dim(r.join(" \xB7 "))}`),n.map(i=>Mn(i,t))}function Wi(e){switch(e){case"active":return b.default.green("active");case"testing-only":case"declared-inactive":case"api-empty":return b.default.yellow(e);case"blocked":case"load-error":return b.default.red(e);default:return b.default.dim(e)}}function Di(e,t){let[n,o]=e.status==="ready"?["agent-ready",b.default.green]:e.status==="not-ready"?["not agent-ready",b.default.red]:["availability unknown",b.default.yellow],r=[` ${o(b.default.bold(n))}`];for(let i of e.reasons)r.push(...P(R(i.detail),t-4).map(s=>` ${b.default.dim(s)}`));return e.status==="not-ready"&&r.push(...P("No score is reported for a page an agent cannot use yet: the reasons above are what to fix first.",t-4).map(i=>` ${b.default.dim(i)}`)),r}function Bi(e,t){let n=e.score===null?"\u2014":String(e.score),o=[` ${b.default.bold(`${n}/100`)} ${Ui(e)}`];return e.grade===null&&e.score!==null&&o.push(...P(`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(r=>` ${b.default.dim(r)}`)),o}function Ui(e){return e.grade!==null?b.default.bold(b.default.green(`grade ${e.grade}`)):b.default.dim("grade withheld")}function Ji(e){let t=[` ${b.default.bold("Pillars")}`];for(let n of Ni){let o=e.categoryScores[n]??0,r=Zt[n],i=e.findings.some(c=>nt[c.checkId]?.category===n&&c.status!=="na"&&c.status!=="unmeasured"),s=i?Fi(o):b.default.dim("\u2591".repeat(it)),a=i?`weight ${r}`:`weight ${r} \xB7 nothing measured`;t.push(` ${ji[n].padEnd(18)} ${s} ${String(o).padStart(3)}% ${b.default.dim(a)}`)}return t}function Fi(e){let t=Math.round(Math.min(100,Math.max(0,e))/100*it);return`${(e>=75?b.default.green:e>=40?b.default.yellow:b.default.red)("\u2588".repeat(t))}${b.default.dim("\u2591".repeat(it-t))}`}function Hi(e,t,n){let o=[` ${b.default.bold("Checks")}`];for(let r of Oi){let i=e.filter(s=>s.status===r);if(i.length!==0){if(r==="pass"&&!n){o.push(` ${b.default.dim(`${i.length} passing (--show-passing to list)`)}`);continue}o.push("",` ${b.default.bold(Mi[r])} (${i.length})`);for(let s of i)o.push(...Gi(s,t))}}return e.length===0&&o.push(` ${b.default.dim("no checks reported")}`),o}function Gi(e,t){let[n,o]=st[e.status],r=qi(e.checkId),s=[` ${o(n)} ${r}${e.toolName?b.default.dim(` ${R(e.toolName)}`):""}`];return e.details&&s.push(...P(R(e.details),t-10).map(a=>` ${b.default.dim(a)}`)),e.evidence&&s.push(...P(R(e.evidence),t-10).map(a=>` ${b.default.dim(a)}`)),s}function qi(e){return nt[e]?.title??e}function Ki(e,t){if(!e)return[];let n=["",` ${b.default.bold("Tool selection")}`];if(e.skipped)return n.push(...P(R(e.skipReason??"The selection simulation did not run."),t-4).map(r=>` ${b.default.dim(r)}`)),n;let o=Math.round(e.accuracy*100);n.push(` ${o}% of ${e.steps.length} intent${e.steps.length===1?"":"s"} picked the right tool ${b.default.dim(R(e.model))}`);for(let r of e.steps){let[i,s]=r.ok?st.pass:st.fail,a=r.chosenTool?R(r.chosenTool):b.default.dim("nothing");n.push(` ${s(i)} ${Mn(R(r.intent),t-30)} ${b.default.dim("\u2192")} ${a}`)}return n}function Vi(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?P(n,t-4).map(o=>` ${b.default.dim(o)}`):[]}function Mn(e,t){return e.length>t?`${e.slice(0,t-1)}\u2026`:e}var M={OK:0,BELOW_MIN_SCORE:1,USAGE:2,API:3};function Yi(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 Xi(e){if(e===void 0)return{};let t=Number(e);return e.trim()===""||!Number.isInteger(t)||t<0||t>100?{error:`--min-score must be an integer between 0 and 100, got ${JSON.stringify(e)}`}:{value:t}}async function Nn(e){let t=Yi(e.url);if(!t)return console.error(`Not an auditable URL: ${JSON.stringify(e.url)}`),console.error("Pass the page you want audited, e.g. http://localhost:3000"),M.USAGE;let n=Xi(e.minScore);if(n.error)return console.error(n.error),M.USAGE;let o=await Sn(e.chromeEndpoint);if(!o.ok)return console.error(o.message),M.USAGE;e.json||A.start(o.launched?`Starting Chrome and capturing ${t}`:`Capturing ${t}`);let r;try{r=await fn({url:t,endpoint:o.endpoint,onTools:p=>{e.json||A.update(`Capturing ${t} \u2014 ${p.length} tools`)}})}catch(p){return A.stop(),console.error(`Capture failed: ${p instanceof Error?p.message:String(p)}`),M.API}finally{await o.close()}let i=r.pages[0];if(i?.error)return A.stop(),console.error(`Could not capture ${t}: ${i.error}`),console.error("Is the dev server running?"),M.USAGE;let s=Tn(r);if(s)return A.stop(),console.error(`ora would refuse this capture: ${s}`),M.USAGE;let{capture:a,droppedScreenshot:c}=Pn(r);e.json||A.update("Scoring with ora");let l;try{l=await In(t,a,{apiKey:e.apiKey??process.env.ORA_API_KEY,onEvent:p=>{e.json||A.update(zi(p))}})}catch(p){return A.stop(),p instanceof I?(console.error(p.message),M.API):(console.error(`Scoring failed: ${p instanceof Error?p.message:String(p)}`),M.API)}if(A.stop(),e.json)console.log(JSON.stringify(l,null,2));else for(let p of On(l,{showPassing:e.showPassing}))console.log(p);c&&console.error("Note: the screenshot exceeded ora's 2 MB limit and was not sent, so page-experience could not be graded.");let u=xn(r);if(u&&console.error(`
|
|
591
|
+
${u}`),n.value!==void 0){if(l.availability.status!=="ready")return e.json||console.log(`
|
|
592
|
+
Not agent-ready, so there is no score to compare against --min-score ${n.value}
|
|
593
|
+
`),M.BELOW_MIN_SCORE;if(l.score===null)return e.json||console.error(`
|
|
594
|
+
ora returned no score, so --min-score cannot be evaluated.`),M.API;if(l.score<n.value)return e.json||console.log(`
|
|
595
|
+
Score ${l.score} is below the required minimum ${n.value}
|
|
596
|
+
`),M.BELOW_MIN_SCORE}return M.OK}function zi(e){switch(e.type){case"phase":return`Scoring with ora \u2014 ${e.phase}`;case"tool-discovered":return`Scoring with ora \u2014 found ${R(e.tool.name)}`;case"finding":return`Scoring with ora \u2014 ${e.finding.checkId}`;case"simulation-step":return`Scoring with ora \u2014 simulating "${R(e.step.intent)}"`;default:return"Scoring with ora"}}function jn(){if(typeof process.loadEnvFile!="function")return!1;try{return process.loadEnvFile(),!0}catch{return!1}}var K="ax",Qi={meta:{name:"audit",description:"Score a site's agent readiness (exit codes: 0 ok, 1 below --min-score, 2 usage, 3 API error)"},args:{url:{type:"positional",description:"URL or domain to audit (e.g. https://docs.example.com)",required:!0},json:{type:"boolean",description:"Print the raw ora audit payload as JSON",default:!1},"min-score":{type:"string",description:"Exit 1 when the score is below this threshold (0-100); the CI gate"},"max-age":{type:"string",description:"Accept a cached result up to this many seconds old (server default 6h)"},force:{type:"boolean",description:"Bypass the cache and rescan (spends the stricter 6/day force budget)",default:!1},"tunnel-cmd":{type:"string",description:"Command that exposes a local target and prints its public https URL (e.g. 'ngrok http 3000 --log stdout'); also read from ORA_TUNNEL_CMD. The result is stored as ephemeral"},"api-key":{type:"string",description:"ora-issued scan API key that lifts the scan rate limits; also read from ORA_SCAN_API_KEY"},"show-passing":{type:"boolean",description:"List each passing check individually",default:!1},"show-skipped":{type:"boolean",description:"List not-applicable / pending checks too",default:!1}},async run({args:e}){process.exitCode=await Tt({url:e.url,json:!!e.json,showSkipped:!!e["show-skipped"],showPassing:!!e["show-passing"],minScore:e["min-score"],maxAge:e["max-age"],force:!!e.force,tunnelCmd:e["tunnel-cmd"],apiKey:e["api-key"]})}},Zi={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 Ut({intent:e.intent,domain:e.domain,harness:e.harness,model:e.model,json:!!e.json})}},es={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 from the public roster (see GET /api/journey/agents)"},json:{type:"boolean",description:"Print the terminal run detail as JSON",default:!1},task:{type:"string",description:"Free-text task for the agent (needs a partner API key; mutually exclusive with --intent)"},"api-key":{type:"string",description:"ora-issued partner API key: unlocks --task and the 1000/24h keyed allowance; also read from ORA_PARTNER_API_KEY"},"no-stream":{type:"boolean",description:"Skip the live trajectory stream and poll for the result instead",default:!1}},async run({args:e}){process.exitCode=await Bt({url:e.url,intent:e.intent,task:e.task,apiKey:e["api-key"],agent:e.agent,json:!!e.json,noStream:!!e["no-stream"]})}},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 qt({name:e.name,install:!!e.install,dir:e.dir,json:!!e.json})}},ns={meta:{name:"webmcp-audit",description:"Audit a page's WebMCP tools in a real browser - localhost included, so you can check before you publish (exit codes: 0 ok, 1 below --min-score, 2 usage, 3 API error)"},args:{url:{type:"positional",description:"Page to audit, scheme included (e.g. http://localhost:3000)",required:!0},"chrome-endpoint":{type:"string",description:"Drive a Chrome you started instead of launching one: ws:// URL, http origin, or host:port"},"min-score":{type:"string",description:"Exit 1 when the score is below this threshold (0-100); the CI gate"},"api-key":{type:"string",description:"ora API key that lifts the ingest rate limits; also read from ORA_API_KEY"},json:{type:"boolean",description:"Print the raw ora audit payload as JSON",default:!1},"show-passing":{type:"boolean",description:"List each passing check individually",default:!1}},async run({args:e}){process.exitCode=await Nn({url:e.url,json:!!e.json,showPassing:!!e["show-passing"],minScore:e["min-score"],chromeEndpoint:e["chrome-endpoint"],apiKey:e["api-key"]})}};function rs(){let e=$e.default.green("$"),t=$e.default.dim;return["",` ${$e.default.bold(K)} ${t(`v${Ie.version}`)}`,` ${t("Score any site's agent readiness \u2014 and watch real AI agents navigate it")}`,"",` ${t("Commands:")}`,` audit ${t("<url>")} ${t("Score a site's agent readiness")}`,` webmcp-audit ${t("<url>")} ${t("Audit a WebMCP surface in a real browser, localhost included")}`,` deep-journey ${t("<url>")} ${t("Run a real agent at a site on a curated or free-text task")}`,` journey ${t("<intent>")} ${t("Send a real agent at a site and watch it live (workspace)")}`,` skill ${t("[name]")} ${t("List, print, or install ora's agent skills")}`,"",` ${t("Examples:")}`,` ${e} ${K} audit https://docs.example.com`,` ${e} ${K} audit https://docs.example.com --min-score 70 ${t("# CI gate")}`,` ${e} ${K} audit https://docs.example.com --json`,` ${e} ${K} webmcp-audit http://localhost:3000`,` ${e} ${K} deep-journey stripe.com --intent pricing`,` ${e} ${K} journey "Find the API docs and how to authenticate" --domain stripe.com`,"",` ${t("audit options:")}`,` --min-score <n> ${t("Exit 1 when the score is below n (0-100); the CI gate")}`,` --max-age <s> ${t("Accept a cached result up to s seconds old (default 6h)")}`,` --force ${t("Bypass the cache and rescan (6/day budget)")}`,` --tunnel-cmd <c> ${t("Expose a local target via your own tunnel command (e.g. 'ngrok http 3000 --log stdout')")}`,` --api-key <k> ${t("ora-issued scan API key that lifts the rate limits; also read from ORA_SCAN_API_KEY")}`,` --json ${t("Print the raw ora audit payload as JSON")}`,` --show-passing ${t("List each passing check (hidden by default)")}`,` --show-skipped ${t("List skipped checks (hidden by default)")}`,"",` ${t("audit exit codes:")}`,` ${t("0 success \xB7 1 below --min-score \xB7 2 usage error \xB7 3 API unreachable/rate-limited")}`,"",` ${t("webmcp-audit options:")}`,` --chrome-endpoint ${t("<e> Drive a Chrome you started: ws:// URL, http origin, or host:port")}`,` --min-score <n> ${t("Exit 1 when the score is below n (0-100); the CI gate")}`,` --api-key <k> ${t("ora API key that lifts the ingest rate limits; also read from ORA_API_KEY")}`,` --json ${t("Print the raw ora audit payload as JSON")}`,` --show-passing ${t("List each passing check (hidden by default)")}`,` ${t("starts a headless Chrome you already have installed; never downloads one")}`,` ${t("scored by ora, stored nowhere: the result is never published or ranked")}`,"",` ${t("deep-journey options:")}`,` --intent <id> ${t("Curated task id, e.g. pricing, signup, api-docs (server default when omitted)")}`,` --task <text> ${t("Free-text task (needs a partner API key; replaces --intent)")}`,` --api-key <k> ${t("ora partner API key: unlocks --task + 1000 runs/24h; also read from ORA_PARTNER_API_KEY")}`,` --agent <id> ${t("Agent from the public roster (default: ora's pick)")}`,` --no-stream ${t("Poll for the result instead of streaming the trajectory")}`,` --json ${t("Print the terminal run detail as JSON")}`,` ${t("no key needed \xB7 public caps: 100 runs/24h per target, 200 runs/24h per IP")}`,"",` ${t("journey options:")}`,` --domain <d> ${t("Site the agent targets (e.g. stripe.com)")}`,` --harness <h> ${t("Agent harness: claude-code (default), codex, openclaw, hermess, claude-agent, eve, \u2026")}`,` --model <m> ${t("Model override (harness default when omitted)")}`,` --json ${t("Output as JSON")}`,` ${t("requires ORA_API_KEY (see .env.example)")}`,""].join(`
|
|
597
|
+
`)}var os={meta:{name:K,version:Ie.version,description:"Score any site's agent readiness \u2014 and watch real AI agents navigate it"},subCommands:{audit:Qi,"webmcp-audit":ns,"deep-journey":es,journey:Zi,skill:ts},setup(){let e=process.argv[2];(!e||e==="--help"||e==="-h")&&(console.log(rs()),process.exit(0))}};jn();ht(os);
|