ax 0.10.0 → 0.10.2
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 +6 -6
- package/README.md +35 -28
- package/dist/contract/types.gen.d.ts +221 -4
- package/dist/contract/version.d.ts +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/main.cjs +183 -70
- package/package.json +1 -1
package/dist/main.cjs
CHANGED
|
@@ -1,60 +1,60 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var
|
|
3
|
-
`)}function I(e){return typeof e=="function"?e():e}var X=class extends Error{code;constructor(e,t){super(e),this.name="CLIError",this.code=t}};function
|
|
4
|
-
`)}catch(n){console.error(n)}}var
|
|
5
|
-
`)}function Ze(e){let t=e.valueHint?`=<${e.valueHint}>`:"",n=t||`=<${Bt(e.name)}>`;return!e.type||e.type==="positional"||e.type==="boolean"?t:e.type==="enum"&&e.options?.length?`=<${e.options.join("|")}>`:n}function Jt(e,t){let n=t?Pe("(Required)"):"",r=e.default===void 0?"":Pe(`(Default: ${e.default})`);return[e.description,n,r].filter(Boolean).join(" ")}async function Yt(e,t={}){let n=t.rawArgs||process.argv.slice(2),r=t.showUsage||
|
|
6
|
-
`),process.exit(1)}}async function
|
|
7
|
-
`))}function z(e){let t=new AbortController,n=!1,r,o=()=>{clearTimeout(r),r=setTimeout(()=>{n=!0,t.abort()},e)};return o(),{signal:t.signal,poke:o,disarm:()=>clearTimeout(r),tripped:()=>n}}async function ve(e){let t=null;try{t=await e.clone().json()}catch{}return e.body?.cancel().catch(()=>{}),{message:t?.message||t?.error||`HTTP ${e.status}`,code:t?.code??null,payload:t}}async function ce(e){return(await ve(e)).message}var Q=e=>new Promise(t=>setTimeout(t,e));var
|
|
2
|
+
"use strict";var Qr=Object.create;var Dt=Object.defineProperty;var Zr=Object.getOwnPropertyDescriptor;var eo=Object.getOwnPropertyNames;var to=Object.getPrototypeOf,no=Object.prototype.hasOwnProperty;var ro=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var oo=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of eo(t))!no.call(e,o)&&o!==n&&Dt(e,o,{get:()=>t[o],enumerable:!(r=Zr(t,o))||r.enumerable});return e};var B=(e,t,n)=>(n=e!=null?Qr(to(e)):{},oo(t||!e||!e.__esModule?Dt(n,"default",{value:e,enumerable:!0}):n,e));var D=ro((ic,ot)=>{"use strict";var Me=process||{},Vt=Me.argv||[],Ie=Me.env||{},vo=!(Ie.NO_COLOR||Vt.includes("--no-color"))&&(!!Ie.FORCE_COLOR||Vt.includes("--color")||Me.platform==="win32"||(Me.stdout||{}).isTTY&&Ie.TERM!=="dumb"||!!Ie.CI),So=(e,t,n=e)=>r=>{let o=""+r,s=o.indexOf(t,e.length);return~s?e+xo(o,t,n,s)+t:e+o+t},xo=(e,t,n,r)=>{let o="",s=0;do o+=e.substring(s,r)+n,s=r+t.length,r=e.indexOf(t,s);while(~r);return o+e.substring(s)},Xt=(e=vo)=>{let t=e?So:()=>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")}};ot.exports=Xt();ot.exports.createColors=Xt});var so=/\d/,io=["-","_","/","."];function ao(e=""){if(!so.test(e))return e!==e.toLowerCase()}function Ft(e,t){let n=t??io,r=[];if(!e||typeof e!="string")return r;let o="",s,i;for(let a of e){let c=n.includes(a);if(c===!0){r.push(o),o="",s=void 0;continue}let l=ao(a);if(i===!1){if(s===!1&&l===!0){r.push(o),o=a,s=l;continue}if(s===!0&&l===!1&&o.length>1){let u=o.at(-1);r.push(o.slice(0,Math.max(0,o.length-1))),o=u+a,s=l;continue}}o+=a,s=l,i=c}return r.push(o),r}function co(e){return e?e[0].toUpperCase()+e.slice(1):""}function lo(e){return e?e[0].toLowerCase()+e.slice(1):""}function uo(e,t){return e?(Array.isArray(e)?e:Ft(e)).map(n=>co(t?.normalize?n.toLowerCase():n)).join(""):""}function fe(e,t){return lo(uo(e||"",t))}function Te(e,t){return e?(Array.isArray(e)?e:Ft(e)).map(n=>n.toLowerCase()).join(t??"-"):""}function Bt(e){return Te(e||"","_")}var Gt=require("util");function ye(e){return Array.isArray(e)?e:e===void 0?[]:[e]}function Qe(e,t=""){let n=[];for(let r of e)for(let[o,s]of r.entries())n[o]=Math.max(n[o]||0,s.length);return e.map(r=>r.map((o,s)=>t+o[s===0?"padStart":"padEnd"](n[s])).join(" ")).join(`
|
|
3
|
+
`)}function I(e){return typeof e=="function"?e():e}var X=class extends Error{code;constructor(e,t){super(e),this.name="CLIError",this.code=t}};function po(e=[],t={}){let n=new Set(t.boolean||[]),r=new Set(t.string||[]),o=t.alias||{},s=t.default||{},i=new Map,a=new Map;for(let[p,y]of Object.entries(o)){let x=y;for(let C of x)i.set(p,C),a.has(C)||a.set(C,[]),a.get(C).push(p),i.set(C,p),a.has(p)||a.set(p,[]),a.get(p).push(C)}let c={};function l(p){if(n.has(p))return"boolean";let y=a.get(p)||[];for(let x of y)if(n.has(x))return"boolean";return"string"}function u(p){if(r.has(p))return!0;let y=a.get(p)||[];for(let x of y)if(r.has(x))return!0;return!1}let d=new Set([...n,...r,...Object.keys(o),...Object.values(o).flat(),...Object.keys(s)]);for(let p of d)c[p]||(c[p]={type:l(p),default:s[p]});for(let[p,y]of i.entries())p.length===1&&c[y]&&!c[y].short&&(c[y].short=p);let m=[],g={};for(let p=0;p<e.length;p++){let y=e[p];if(y==="--"){m.push(...e.slice(p));break}if(y.startsWith("--no-")){let x=y.slice(5);g[x]=!0;continue}m.push(y)}let f;try{f=(0,Gt.parseArgs)({args:m,options:Object.keys(c).length>0?c:void 0,allowPositionals:!0,strict:!1})}catch{f={values:{},positionals:m}}let h={_:[]};h._=f.positionals;for(let[p,y]of Object.entries(f.values)){let x=y;l(p)==="boolean"&&typeof y=="string"?x=y!=="false":u(p)&&typeof y=="boolean"&&(x=""),h[p]=x}for(let[p]of Object.entries(g)){h[p]=!1;let y=i.get(p);y&&(h[y]=!1);let x=a.get(p);if(x)for(let C of x)h[C]=!1}for(let[p,y]of i.entries())h[p]!==void 0&&h[y]===void 0&&(h[y]=h[p]),h[y]!==void 0&&h[p]===void 0&&(h[p]=h[y]),h[p]!==h[y]&&s[y]===h[y]&&(h[y]=h[p]);return h}var mo=(()=>{let e=globalThis.process?.env??{};return e.NO_COLOR==="1"||e.TERM==="dumb"||e.TEST||e.CI})(),Oe=(e,t=39)=>n=>mo?n:`\x1B[${e}m${n}\x1B[${t}m`,_e=Oe(1,22),J=Oe(36),Pe=Oe(90),Ce=Oe(4,24);function ho(e,t){let n={boolean:[],string:[],alias:{},default:{}},r=Kt(t);for(let a of r){if(a.type==="positional")continue;a.type==="string"||a.type==="enum"?n.string.push(a.name):a.type==="boolean"&&n.boolean.push(a.name),a.default!==void 0&&(n.default[a.name]=a.default),a.alias&&(n.alias[a.name]=a.alias);let c=fe(a.name),l=Te(a.name);if(c!==a.name||l!==a.name){let u=ye(n.alias[a.name]||[]);c!==a.name&&!u.includes(c)&&u.push(c),l!==a.name&&!u.includes(l)&&u.push(l),u.length>0&&(n.alias[a.name]=u)}}let o=po(e,n),[...s]=o._,i=new Proxy(o,{get(a,c){return a[c]??a[fe(c)]??a[Te(c)]}});for(let[,a]of r.entries())if(a.type==="positional"){let c=s.shift();if(c!==void 0)i[a.name]=c;else{if(a.default===void 0&&a.required!==!1)throw new X(`Missing required positional argument: ${a.name.toUpperCase()}`,"EARG");i[a.name]=a.default}}else if(a.type==="enum"){let c=i[a.name],l=a.options||[];if(c!==void 0&&l.length>0&&!l.includes(c))throw new X(`Invalid value for argument: ${J(`--${a.name}`)} (${J(c)}). Expected one of: ${l.map(u=>J(u)).join(", ")}.`,"EARG")}else if(a.required&&i[a.name]===void 0)throw new X(`Missing required argument: --${a.name}`,"EARG");return i}function Kt(e){let t=[];for(let[n,r]of Object.entries(e||{}))t.push({...r,name:n,alias:ye(r.alias)});return t}async function go(e){return Promise.all(e.map(t=>I(t)))}async function et(e,t){let n=await I(e.args||{}),r=ho(t.rawArgs,n),o={rawArgs:t.rawArgs,args:r,data:t.data,cmd:e},s=await go(e.plugins??[]),i,a;try{for(let u of s)await u.setup?.(o);typeof e.setup=="function"&&await e.setup(o);let l=await I(e.subCommands);if(l&&Object.keys(l).length>0){let u=qt(t.rawArgs,n),d=t.rawArgs[u];if(d){let m=await nt(l,d);if(!m)throw new X(`Unknown command ${J(d)}`,"E_UNKNOWN_COMMAND");await et(m,{rawArgs:t.rawArgs.slice(u+1)})}else{let m=await I(e.default);if(m){if(e.run)throw new X("Cannot specify both 'run' and 'default' on the same command.","E_DEFAULT_CONFLICT");let g=await nt(l,m);if(!g)throw new X(`Default sub command ${J(m)} not found in subCommands.`,"E_UNKNOWN_COMMAND");await et(g,{rawArgs:t.rawArgs})}else if(!e.run)throw new X("No command specified.","E_NO_COMMAND")}}typeof e.run=="function"&&(i=await e.run(o))}catch(l){a=l}let c=[];if(typeof e.cleanup=="function")try{await e.cleanup(o)}catch(l){c.push(l)}for(let l of[...s].reverse())try{await l.cleanup?.(o)}catch(u){c.push(u)}if(a)throw a;if(c.length===1)throw c[0];if(c.length>1)throw new Error("Multiple cleanup errors",{cause:c});return{result:i}}async function tt(e,t,n){let r=await I(e.subCommands);if(r&&Object.keys(r).length>0){let o=qt(t,await I(e.args||{})),s=t[o],i=await nt(r,s);if(i)return tt(i,t.slice(o+1),e)}return[e,n]}async function nt(e,t){if(t in e)return I(e[t]);for(let n of Object.values(e)){let r=await I(n),o=await I(r?.meta);if(o?.alias&&ye(o.alias).includes(t))return r}}function qt(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(r==="--")return-1;if(r.startsWith("-")){!r.includes("=")&&fo(r,t)&&n++;continue}return n}return-1}function fo(e,t){let n=e.replace(/^-{1,2}/,""),r=fe(n);for(let[o,s]of Object.entries(t))if(!(s.type!=="string"&&s.type!=="enum")&&(r===fe(o)||(Array.isArray(s.alias)?s.alias:s.alias?[s.alias]:[]).includes(n)))return!0;return!1}async function rt(e,t){try{console.log(await wo(e,t)+`
|
|
4
|
+
`)}catch(n){console.error(n)}}var yo=/^no[-A-Z]/;async function wo(e,t){let n=await I(e.meta||{}),r=Kt(await I(e.args||{})),o=await I(t?.meta||{}),s=`${o.name?`${o.name} `:""}`+(n.name||process.argv[1]),i=[],a=[],c=[],l=[];for(let g of r)if(g.type==="positional"){let f=g.name.toUpperCase(),h=g.required!==!1&&g.default===void 0;a.push([J(f+Ze(g)),Jt(g,h)]),l.push(h?`<${f}>`:`[${f}]`)}else{let f=g.required===!0&&g.default===void 0,h=[...(g.alias||[]).map(p=>`-${p}`),`--${g.name}`].join(", ")+Ze(g);if(i.push([J(h),Jt(g,f)]),g.type==="boolean"&&(g.default===!0||g.negativeDescription)&&!yo.test(g.name)){let p=[...(g.alias||[]).map(y=>`--no-${y}`),`--no-${g.name}`].join(", ");i.push([J(p),[g.negativeDescription,f?Pe("(Required)"):""].filter(Boolean).join(" ")])}f&&l.push(`--${g.name}`+Ze(g))}if(e.subCommands){let g=[],f=await I(e.subCommands);for(let[h,p]of Object.entries(f)){let y=await I((await I(p))?.meta);if(y?.hidden)continue;let x=ye(y?.alias),C=[h,...x].join(", ");c.push([J(C),y?.description||""]),g.push(h,...x)}l.push(g.join("|"))}let u=[],d=n.version||o.version;u.push(Pe(`${n.description} (${s+(d?` v${d}`:"")})`),"");let m=i.length>0||a.length>0;return u.push(`${Ce(_e("USAGE"))} ${J(`${s}${m?" [OPTIONS]":""} ${l.join(" ")}`)}`,""),a.length>0&&(u.push(Ce(_e("ARGUMENTS")),""),u.push(Qe(a," ")),u.push("")),i.length>0&&(u.push(Ce(_e("OPTIONS")),""),u.push(Qe(i," ")),u.push("")),c.length>0&&(u.push(Ce(_e("COMMANDS")),""),u.push(Qe(c," ")),u.push("",`Use ${J(`${s} <command> --help`)} for more information about a command.`)),u.filter(g=>typeof g=="string").join(`
|
|
5
|
+
`)}function Ze(e){let t=e.valueHint?`=<${e.valueHint}>`:"",n=t||`=<${Bt(e.name)}>`;return!e.type||e.type==="positional"||e.type==="boolean"?t:e.type==="enum"&&e.options?.length?`=<${e.options.join("|")}>`:n}function Jt(e,t){let n=t?Pe("(Required)"):"",r=e.default===void 0?"":Pe(`(Default: ${e.default})`);return[e.description,n,r].filter(Boolean).join(" ")}async function Yt(e,t={}){let n=t.rawArgs||process.argv.slice(2),r=t.showUsage||rt;try{let o=await bo(e);if(o.help.length>0&&n.some(s=>o.help.includes(s)))await r(...await tt(e,n)),process.exit(0);else if(n.length===1&&o.version.includes(n[0])){let s=typeof e.meta=="function"?await e.meta():await e.meta;if(!s?.version)throw new X("No version specified","E_NO_VERSION");console.log(s.version)}else await et(e,{rawArgs:n})}catch(o){o instanceof X?(await r(...await tt(e,n)),console.error(o.message)):console.error(o,`
|
|
6
|
+
`),process.exit(1)}}async function bo(e){let t=await I(e.args||{}),n=new Set,r=new Set;for(let[o,s]of Object.entries(t)){n.add(o);for(let i of ye(s.alias))r.add(i)}return{help:Ht("help","h",n,r),version:Ht("version","v",n,r)}}function Ht(e,t,n,r){return n.has(e)||r.has(e)?[]:n.has(t)||r.has(t)?[`--${e}`]:[`--${e}`,`-${t}`]}var ze=B(D(),1);var we={name:"ax",version:"0.10.2",description:"Score any site's agent readiness and watch real AI agents navigate it \u2014 powered by ora",type:"module",packageManager:"pnpm@10.34.5",bin:{ax:"./dist/main.cjs"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"}},main:"./dist/index.cjs",types:"./dist/index.d.ts",files:["dist",".env.example"],engines:{node:">=22.4.0"},scripts:{build:"rm -rf dist && tsup && tsc -p tsconfig.lib.json","contract:gen":"node scripts/contract-gen.mjs",smoke:"node scripts/smoke.mjs","smoke:webmcp":"node scripts/smoke-webmcp.mjs","verify:pack":"node scripts/verify-pack.mjs",test:"vitest","test:ci":"vitest run --coverage","test:capture":"vitest run src/webmcp/capture.live.test.ts",lint:"biome check .","lint:fix":"biome check --write .",typecheck:"tsc --noEmit",prepublishOnly:"npm run build"},devDependencies:{"@biomejs/biome":"^2.5.7","@commitlint/cli":"^21.2.2","@commitlint/config-conventional":"^21.2.2","@ora-ai/tunnel-protocol":"^0.4.1","@types/node":"^26.2.0","@vitest/coverage-v8":"^3",citty:"^0.2.2","openapi-typescript":"^6.7.6",picocolors:"^1",tsup:"^8",typescript:"^7.0.2",vitest:"^3"},publishConfig:{access:"public"},pnpm:{onlyBuiltDependencies:["@biomejs/biome","esbuild"],overrides:{"undici@<6.28.0":"^6.28.0"}},license:"MIT",author:{name:"Era AI Labs",url:"https://ora.ai"},homepage:"https://ora.ai/docs#cli",bugs:"https://github.com/ora/ax/issues",repository:{type:"git",url:"git+https://github.com/ora/ax.git"},keywords:["ai","agents","agent-readiness","agent-experience","llms.txt","ora","cli","scan"]};var bt=B(D(),1);var st="1.32.0";function zt(e){let[t=0,n=0]=e.split(".").map(r=>Number.parseInt(r,10));return[t,n]}function ko(e){if(!e||!/^\d+\.\d+\.\d+$/.test(e))return!1;let[t,n]=zt(e),[r,o]=zt(st);return t>r||t===r&&n>o}var Qt=!1;function be(e){Qt||!ko(e)||(Qt=!0,process.stderr.write(`ora reports contract ${e}; this CLI was built against ${st}. Newer fields may be missing from the output - upgrade with: npm i -g ax@latest
|
|
7
|
+
`))}function z(e){let t=new AbortController,n=!1,r,o=()=>{clearTimeout(r),r=setTimeout(()=>{n=!0,t.abort()},e)};return o(),{signal:t.signal,poke:o,disarm:()=>clearTimeout(r),tripped:()=>n}}async function ve(e){let t=null;try{t=await e.clone().json()}catch{}return e.body?.cancel().catch(()=>{}),{message:t?.message||t?.error||`HTTP ${e.status}`,code:t?.code??null,payload:t}}async function ce(e){return(await ve(e)).message}var Q=e=>new Promise(t=>setTimeout(t,e));var Eo="https://ora.ai",Ro=6e4,$o=2e3,To=45,it=14,j=class extends Error{code;payload;constructor(t,n={}){super(t),this.name="AuditApiError",this.code=n.code??null,this.payload=n.payload}},_o="MCP_AUTH_REQUIRED";function Zt(e){return e instanceof j&&e.code===_o}function en(e){return e?{authorization:`Bearer ${e}`}:{}}async function tn(e,t={}){let n=(t.baseUrl??process.env.ORA_API_URL??Eo).replace(/\/+$/,"");t={...t,apiKey:t.apiKey||process.env.ORA_SCAN_API_KEY||void 0},t.progress?.(`Auditing ${e} with ora`);let r=await Po(n,e,t);be(r.result.contractVersion);let o=r.result;return nn(o)&&(o=await Mo(n,o,t)),{result:o,verdict:r.verdict}}function Co(e,t,n){let r=new URLSearchParams({domain:t,format:"audit"});return n.force&&r.set("force","1"),n.ephemeral&&r.set("ephemeral","1"),n.maxAgeSeconds!==void 0&&r.set("maxAgeSeconds",String(n.maxAgeSeconds)),`${e}/api/scan/stream?${r}`}async function Po(e,t,n){let r=n.idleMs??Ro,o=z(r),s=()=>new j(`ora audit timed out \u2014 no progress for ${Math.round(r/1e3)}s`),i;try{i=await fetch(Co(e,t,n),{headers:{accept:"text/event-stream",...en(n.apiKey)},signal:o.signal})}catch(m){if(o.disarm(),o.tripped())throw s();let g=m instanceof Error?m.message:String(m);throw new j(`ora audit request failed: ${g}`)}if(i.status===429){o.disarm();let m=i.headers.get("retry-after");throw new j(`ora rate limit exceeded${m?` \u2014 retry after ${m}s`:""} (burst: 10 scans/min/IP; daily: 30 scans + 6 force per 24h). An ora-issued scan API key lifts these limits: set ORA_SCAN_API_KEY or pass --api-key.`)}if(!i.ok||!i.body){o.disarm();let m=await ve(i);throw new j(`ora audit failed: ${m.message}`,{code:m.code,payload:m.payload})}let a=Io(),c=new TextDecoder,l="",u,d;try{e:for await(let m of i.body){o.poke(),l=`${l}${c.decode(m,{stream:!0})}`.replace(/\r\n?/g,`
|
|
8
8
|
`);let g=l.indexOf(`
|
|
9
9
|
|
|
10
|
-
`);for(;g!==-1;){let f=
|
|
10
|
+
`);for(;g!==-1;){let f=Oo(l.slice(0,g));if(l=l.slice(g+2),g=l.indexOf(`
|
|
11
11
|
|
|
12
|
-
`),!f)continue;let h;try{h=JSON.parse(f)}catch{continue}let p=a(h);if(p&&n.progress?.(p),h.type==="error")throw new j(`ora audit failed: ${typeof h.message=="string"?h.message:"scan error"}`,{code:typeof h.code=="string"?h.code:null,payload:h});if(h.type==="scan_complete"&&h.result?u=h.result:h.type==="summary_ready"&&typeof h.agenticSummary=="string"&&(d=h.agenticSummary),u&&d)break e}}}catch(m){if(o.tripped())throw s();if(m instanceof j)throw m;let g=m instanceof Error?m.message:String(m);throw new j(`ora audit stream error: ${g}`)}finally{o.disarm(),i.body.cancel().catch(()=>{})}if(!u)throw new j("ora audit stream ended before completing");return{result:u,verdict:d}}function
|
|
12
|
+
`),!f)continue;let h;try{h=JSON.parse(f)}catch{continue}let p=a(h);if(p&&n.progress?.(p),h.type==="error")throw new j(`ora audit failed: ${typeof h.message=="string"?h.message:"scan error"}`,{code:typeof h.code=="string"?h.code:null,payload:h});if(h.type==="scan_complete"&&h.result?u=h.result:h.type==="summary_ready"&&typeof h.agenticSummary=="string"&&(d=h.agenticSummary),u&&d)break e}}}catch(m){if(o.tripped())throw s();if(m instanceof j)throw m;let g=m instanceof Error?m.message:String(m);throw new j(`ora audit stream error: ${g}`)}finally{o.disarm(),i.body.cancel().catch(()=>{})}if(!u)throw new j("ora audit stream ended before completing");return{result:u,verdict:d}}function Oo(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: ${a.trim().slice(-300)}`:"";l(new
|
|
14
|
+
`)}function Io(){let e=0,t=0,n="";return r=>{switch(r.type){case"kind_detecting":return"Detecting URL kind\u2026";case"kind_detected":return typeof r.kind=="string"?`Detected ${r.kind}, scanning\u2026`:void 0;case"scan_init":Array.isArray(r.checkRoster)&&(e=r.checkRoster.length);return;case"discovery_phase":return typeof r.label=="string"?r.label:void 0;case"check_complete":{if(t+=1,typeof r.checkName=="string"&&(n=r.checkName),e<=0)return`Running checks\u2026 (${t})`;let o=Math.min(t,e),s=Math.min(it,Math.max(0,Math.round(o/e*it)));return`${`${"\u2588".repeat(s)}${"\u2591".repeat(it-s)}`} ${o}/${e}${n?` \xB7 ${n}`:""}`}case"scan_complete":return"Finishing up\u2026";default:return}}}function nn(e){return e.analysisStatus==="complete"||e.analysisStatus==="stuck"?!1:e.analysisStatus==="partial"?!0:(e.pendingChecks?.length??0)>0}async function Mo(e,t,n){let r=`${e}/api/score/${encodeURIComponent(t.domain)}?format=audit`,o=n.pollEveryMs??$o,s=n.pollLimit??To,i=t;for(let a=0;a<s&&nn(i);a++){let c=i.pendingChecks?.length??0;n.progress?.(c?`Analyzing\u2026 ${c} check${c===1?"":"s"} pending`:"Analyzing\u2026"),await Q(o);try{let l=await fetch(r,{headers:{accept:"application/json",...en(n.apiKey)},signal:AbortSignal.timeout(15e3)});l.ok&&(i=await l.json())}catch{}}return i}function No(e,t){let n=t.filter(r=>!r.skipped);return{name:e,checks:t,passed:n.filter(r=>r.passed).length,total:n.length,skipped:t.length-n.length}}function Lo(e){let t=e.status==="pass",n=e.status==="na"||e.status==="pending",r={id:e.id,name:e.name,passed:t,status:e.status};return n&&(r.skipped=!0),n&&e.naReason?r.detail=e.naReason:e.details&&(r.detail=e.details),typeof e.estScoreGain=="number"&&(r.estScoreGain=e.estScoreGain),e.specUrl&&(r.specUrl=e.specUrl),!t&&!n&&e.recommendation&&(r.hint=e.recommendation),r}function rn(e,t){let{result:n}=e,r=(n.layers??[]).map(i=>No(i.name,(i.checks??[]).map(Lo))),o={target:n.domain||t,score:n.score,grade:n.grade,summary:e.verdict,sections:r,topFixes:n.topFixes??[],reportUrl:n.url,analysisStatus:n.analysisStatus},s=n;return s.servedFromCache&&typeof s.resultAgeSeconds=="number"&&(o.cacheAgeSeconds=s.resultAgeSeconds),n.mcpAuthRequired&&(o.mcpAuthRequired=!0),o}var v=B(D(),1),ct="\u26A0 MCP handshake requires credentials \u2014 target is unscored",jo=" (0/F means could not evaluate, not failed everything)",Uo=80,Wo=120,Ne=10;function Do(){return Math.min(Wo,Math.max(Uo,process.stdout.columns??100))}function lt(e,t){return e.length<t?e+" ".repeat(t-e.length):e}function sn(e,t){if(t<=0||e.length<=t)return[e];let n=[],r="";for(let o of e.split(/\s+/))for(r=r?`${r} ${o}`:o;r.length>t;){let s=r.lastIndexOf(" ");s>0&&r.length-s-1<=t?(n.push(r.slice(0,s)),r=r.slice(s+1)):(n.push(r.slice(0,t)),r=r.slice(t))}return r&&n.push(r),n.length?n:[""]}function at(e,t){let n=(i,a,c)=>v.default.dim(i+e.map(l=>"\u2500".repeat(l.width+2)).join(a)+c),r=v.default.dim("\u2502"),o=(i,a)=>{let c=i.map((d,m)=>sn(typeof d=="string"?d:d[0],e[m].width)),l=Math.max(1,...c.map(d=>d.length)),u=[];for(let d=0;d<l;d++){let m=c.map((g,f)=>{let h=lt(g[d]??"",e[f].width),p=a??(typeof i[f]=="string"?e[f].paint:i[f][1]);return` ${p?p(h):h} `});u.push(r+m.join(r)+r)}return u},s=[n("\u250C","\u252C","\u2510")];return s.push(...o(e.map(i=>i.title),v.default.bold)),s.push(n("\u251C","\u253C","\u2524")),t.forEach((i,a)=>{s.push(...o(i)),a<t.length-1&&s.push(n("\u251C","\u253C","\u2524"))}),s.push(n("\u2514","\u2534","\u2518")),s}function Fo(e,t){let r=Math.max(46,e-4-13),o=14,s=Math.min(26,Math.max(5,...t.map(l=>l.length))),i=r-1-s;i<o*2&&(s=Math.max(12,s-(o*2-i)),i=r-1-s);let a=Math.max(o,Math.ceil(i/2)),c=Math.max(o,i-a);return[{title:"",width:1},{title:"Check",width:s,paint:v.default.bold},{title:"What's wrong",width:a},{title:"How to fix",width:c,paint:v.default.cyan}]}function on(e,t,n,r){let s=Math.max(40,e-4-7),i=Math.min(30,Math.max(n[0].length,...t.map(a=>a.length)));return[{title:n[0],width:i,paint:r},{title:n[1],width:Math.max(20,s-i),paint:r}]}function Bo(e,t){if(t<=0)return v.default.dim("\u2500".repeat(Ne));let n=Math.min(Ne,Math.max(0,Math.round(e/t*Ne)));return v.default.green("\u2588".repeat(n))+v.default.dim("\u2591".repeat(Ne-n))}function Jo(e,t,n,r){let o=[""],s=e.total>0?`${e.passed}/${e.total} passed`:"no applicable checks",i=e.skipped>0?` \xB7 ${e.skipped} skipped`:"";o.push(` ${v.default.bold(lt(e.name,n))} ${Bo(e.passed,e.total)} ${v.default.dim(s+i)}`);let a=e.checks.filter(c=>!c.passed&&!c.skipped);if(a.length){o.push(` ${v.default.red("\u2717")} ${v.default.bold(`Issues (${a.length})`)}`);let c=at(Fo(t,a.map(u=>u.name)),a.map(u=>[u.status==="warning"?["\u26A0",v.default.yellow]:["\u2717",v.default.red],u.name,[u.detail??"",d=>d],u.hint??""]));o.push(...c.map(u=>` ${u}`));let l=a.filter(u=>u.specUrl);for(let u of l)o.push(v.default.dim(` \u21B3 ${u.id} spec: ${u.specUrl}`))}if(r.showPassing){let c=e.checks.filter(l=>l.passed&&!l.skipped);if(c.length){o.push(` ${v.default.green("\u2713")} ${v.default.bold(`Passed (${c.length})`)}`);let l=at(on(t,c.map(u=>u.name),["Check","Details"]),c.map(u=>[u.name,u.detail??""]));o.push(...l.map(u=>` ${u}`))}}if(r.showSkipped){let c=e.checks.filter(l=>l.skipped);if(c.length){o.push(` ${v.default.dim(`\u25CB Skipped (${c.length})`)}`);let l=at(on(t,c.map(u=>u.name),["Check","Reason"],v.default.dim),c.map(u=>[u.name,u.detail??""]));o.push(...l.map(u=>` ${u}`))}}return o}function Ho(e){if(!e.topFixes.length)return[];let t=["",` ${v.default.bold("Top fixes")} ${v.default.dim("(ranked by ora)")}`],n=e.topFixes.reduce((r,o)=>Math.max(r,o.id.length),0);return e.topFixes.forEach((r,o)=>{let s=typeof r.estScoreGain=="number"?v.default.green(`\u2248 +${r.estScoreGain} pts`):v.default.dim("\u2014"),i=r.bonus?v.default.dim(" (bonus)"):"";t.push(` ${o+1}. ${v.default.bold(lt(r.id,n))} ${s}${i}`)}),t}function Go(e){return e<90?`${e}s`:e<5400?`${Math.round(e/60)} min`:`${Math.round(e/3600)}h`}function an(e,t={}){let n=Do(),r=e.sections.reduce((l,u)=>Math.max(l,u.name.length),0),o=[""],s=e.score>=70?v.default.green:e.score>=50?v.default.yellow:v.default.red;if(o.push(` ${v.default.bold(e.target)} ${s(v.default.bold(`${e.score}/100 ${e.grade}`))}`),t.tunnel&&o.push(v.default.dim(" tunnel audit \u2014 disposable result, excluded from rankings; off-site checks (registry listings, brand search) usually fail for a throwaway hostname")),e.mcpAuthRequired&&o.push(v.default.yellow(` ${ct}${jo}`)),e.summary)for(let l of sn(e.summary,n-4))o.push(` ${v.default.dim(l)}`);for(let l of e.sections)o.push(...Jo(l,n,r,t));o.push(...Ho(e));let i=e.sections.reduce((l,u)=>l+u.passed,0),a=e.sections.reduce((l,u)=>l+u.skipped,0),c=[];if(!t.showPassing&&i>0&&c.push(` Run with --show-passing to list all ${i} passing checks`),!t.showSkipped&&a>0&&c.push(` ${a} check${a===1?"":"s"} skipped \u2014 run with --show-skipped to see them`),e.analysisStatus==="partial"?c.push(" Analysis still finishing \u2014 re-run shortly for the final score"):e.analysisStatus==="stuck"&&c.push(" Scan did not fully resolve \u2014 re-run with --force to complete it"),typeof e.cacheAgeSeconds=="number"&&c.push(` cached result (${Go(e.cacheAgeSeconds)} old) \xB7 pass --force for a fresh scan`),e.reportUrl&&c.push(` Full report: ${e.reportUrl}`),c.length){o.push("");for(let l of c)o.push(v.default.dim(l))}return o.push(""),o}var cn=require("child_process"),T=class extends Error{},Ko=3e4,ln=9e4,qo=1e4;function ut(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 Yo(e){for(let t of e.matchAll(/https:\/\/[^\s"'|]+/g))try{let n=new URL(t[0]);if(n.pathname==="/"&&!n.search&&!ut(n.hostname))return n.origin}catch{}}async function un(e,t=Ko){let n=await Vo(e,t);try{await dt(n.url,ln)}catch(r){throw n.close(),r}return n}async function dt(e,t=ln,n=5e3,r){let o=Date.now()+t;for(;Date.now()<o;){if(r?.aborted)throw new T("interrupted while waiting for the tunnel");try{if((await fetch(e,{redirect:"manual",signal:AbortSignal.timeout(qo)})).status<500)return}catch{}await new Promise(s=>setTimeout(s,n))}throw new T([`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 Vo(e,t){return new Promise((n,r)=>{let o=process.platform!=="win32",s=(0,cn.spawn)(e,{shell:!0,detached:o,stdio:["ignore","pipe","pipe"]}),i=!1,a="",c=()=>{try{o&&s.pid?process.kill(-s.pid,"SIGTERM"):s.kill("SIGTERM")}catch{}},l=d=>{i||(i=!0,clearTimeout(u),c(),r(d))},u=setTimeout(()=>l(new T(`tunnel command did not print a public https URL within ${Math.round(t/1e3)}s: ${e}`)),t);s.on("error",d=>l(new T(d.message))),s.on("exit",d=>{let m=a.trim()?`
|
|
16
|
+
output: ${a.trim().slice(-300)}`:"";l(new T(`tunnel command exited before printing a public https URL (code ${d??"unknown"}): ${e}${m}`))});for(let d of[s.stdout,s.stderr])d?.setEncoding("utf8"),d?.on("data",m=>{a=(a+m).slice(-2e3);let g=Yo(a);g&&!i&&(i=!0,clearTimeout(u),s.removeAllListeners("exit"),n({url:g,close:c}))})})}var Cn=require("crypto"),Pn=require("events"),On=require("http");var dn="https://api.agentfront.sh";function pn(e){return(e??process.env.ORA_PLATFORM_URL??dn).replace(/\/+$/,"")}var Xo=12e4;async function Le(e,t){let n=await fetch(`${e}/auth/token`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:"{}"});if(n.status===401)throw new Error("ora rejected the API key (401). Check ORA_API_KEY.");let r=await n.json().catch(()=>({}));if(!n.ok||!r.token)throw new Error(`ora auth failed (${n.status})${r.error?`: ${r.error}`:""}`);return r.token}async function zo(e,t,n){let r={intent:n.intent};n.domain&&(r.domain=n.domain),n.harness&&(r.harness=n.harness),n.model&&(r.model=n.model),n.executionKind&&(r.execution_kind=n.executionKind);let o=await fetch(`${e}/experiment/v1/runs`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify(r)});if(o.status===429)throw new Error("ora rate limit hit (429). Wait a moment and retry.");let s=await o.text(),i;try{i=JSON.parse(s)}catch{throw new Error(`ora returned a non-JSON response (${o.status})`)}if(!o.ok||!i.runId)throw new Error(`ora run failed (${o.status}): ${i.message??i.error??s}`);return i}function pt(e){let t="message",n=[];for(let r of e.split(`
|
|
17
17
|
`))r.startsWith(":")||(r.startsWith("event:")?t=r.slice(6).trim():r.startsWith("data:")&&n.push(r.slice(5).replace(/^ /,"")));return n.length?{event:t,data:n.join(`
|
|
18
|
-
`)}:null}async function
|
|
18
|
+
`)}:null}async function Qo(e,t,n,r,o){let s=n.startsWith("http")?n:`${e}${n}`,i=z(o),a=await fetch(s,{headers:{authorization:`Bearer ${t}`,accept:"text/event-stream"},signal:i.signal});if(!a.ok||!a.body)throw i.disarm(),new Error(`ora run stream failed (${a.status})`);let c=new TextDecoder,l={steps:[],trajectory:[]},u="";try{e:for await(let d of a.body){i.poke(),u=`${u}${c.decode(d,{stream:!0})}`.replace(/\r\n?/g,`
|
|
19
19
|
`);let m=u.indexOf(`
|
|
20
20
|
|
|
21
|
-
`);for(;m!==-1;){let g=
|
|
22
|
-
|
|
23
|
-
`),!g)continue;let f;try{f=JSON.parse(g.data)}catch{continue}if(Yo(l,g.event,f,r),l.summary&&l.insight)break e}}}catch(d){throw i.tripped()?new Error(`ora run stream timed out after ${o}ms of silence`):d}finally{i.disarm(),a.body.cancel().catch(()=>{})}return l}function Yo(e,t,n,r){switch(t){case"trajectory":{let o=n.steps;Array.isArray(o)&&(e.trajectory=o,r.snapshot?.(e.trajectory));return}case"step":{let o=n.step;o&&(e.steps.push(o),r.step?.(o,Number(n.seq??e.steps.length)));return}case"result":{let o=n.result;o&&(e.summary=o,r.finished?.(o));return}case"insight":{let o=n.insight;o&&(e.insight=o,r.scored?.(o));return}default:return}}async function Vo(e,t,n){for(let r=0;;r++){let o;try{let s=await fetch(`${e}/experiment/v1/runs?pageSize=50`,{headers:{authorization:`Bearer ${t}`}});if(!s.ok)return;o=(await s.json()).results?.find(a=>a.id===n)}catch{return}if(!o)return;if(o.total_tokens!=null||o.cost_usd!=null)return{totalTokens:o.total_tokens??void 0,inputTokens:o.input_tokens??void 0,outputTokens:o.output_tokens??void 0,cacheReadTokens:o.cache_read_tokens??void 0,cacheCreationTokens:o.cache_creation_tokens??void 0,costUsd:o.cost_usd??void 0};if(r>0)return;await Q(1200)}}async function pt(e,t={}){let n=(e.baseUrl??process.env.ORA_PLATFORM_URL??dn).replace(/\/+$/,""),r=e.apiKey??process.env.ORA_API_KEY;if(!r)throw new Error("Missing ORA_API_KEY. Set it in your environment or a local .env file (see .env.example).");let o=await Ne(n,r),s=await Ko(n,o,e),i={runId:s.runId,intent:e.intent,domain:e.domain,harness:e.harness};if(s.status==="succeeded"&&!s.streamUrl)return{...i,steps:[],trajectory:[]};t.opened?.(s.runId);let a=await qo(n,o,s.streamUrl??`/experiment/v1/runs/${s.runId}/stream`,t,e.idleMs??Go),c=a.summary?await Vo(n,o,s.runId):void 0;return{...i,result:a.summary,insight:a.insight,usage:c,steps:a.steps,trajectory:a.trajectory}}var k=class extends Error{constructor(n,r){super(r);this.code=n;this.name="ProtocolError"}code},S={frameTooShort:"FRAME_TOO_SHORT",frameTooLarge:"FRAME_TOO_LARGE",frameLengthMismatch:"FRAME_LENGTH_MISMATCH",unknownFrameType:"UNKNOWN_FRAME_TYPE",badJson:"BAD_JSON",badPayload:"BAD_PAYLOAD",handshakeTimeout:"HANDSHAKE_TIMEOUT",handshakeProtocol:"HANDSHAKE_PROTOCOL",maxStreams:"MAX_STREAMS",streamClosed:"STREAM_CLOSED",streamReset:"STREAM_RESET",forwardError:"FORWARD_ERROR",connectionClosed:"CONNECTION_CLOSED",superseded:"SUPERSEDED",timeout:"TIMEOUT"};function mn(e,t){return e.safeParse(t)}var U=class extends Error{};function te(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new U(`${t}: expected object`);return e}function ee(e,t,n=0,r=Number.POSITIVE_INFINITY){if(typeof e!="string")throw new U(`${t}: expected string`);if(e.length<n)throw new U(`${t}: expected at least ${n} characters`);if(e.length>r)throw new U(`${t}: expected at most ${r} characters`);return e}function le(e,t,n,r=Number.POSITIVE_INFINITY){if(typeof e!="number"||!Number.isInteger(e))throw new U(`${t}: expected integer`);if(e<n||e>r)throw new U(`${t}: expected ${n}..${r}`);return e}function hn(e,t){if(e===void 0)return{};let n={};for(let[r,o]of Object.entries(te(e,t)))if(typeof o=="string")n[r]=o;else if(Array.isArray(o)&&o.every(s=>typeof s=="string"))n[r]=o;else throw new U(`${t}.${r}: expected string or string[]`);return n}function ue(e){return{safeParse(t){try{return{success:!0,data:e(t)}}catch(n){if(n instanceof U)return{success:!1,error:{message:n.message}};throw n}}}}function gn(e,t){let n=te(e,t);if(n.protocol!=="http")throw new U(`${t}.protocol: expected "http"`);return{protocol:"http",host:ee(n.host,`${t}.host`,1),port:le(n.port,`${t}.port`,1,65535)}}var yc=ue(e=>gn(e,"target")),wc=ue(e=>{let t=te(e,"hello");return{agentVersion:ee(t.agentVersion,"hello.agentVersion",1,64),target:gn(t.target,"hello.target"),maxStreams:t.maxStreams===void 0?32:le(t.maxStreams,"hello.maxStreams",1,256)}}),fn=ue(e=>{let t=te(e,"helloAck");return{tunnelId:ee(t.tunnelId,"helloAck.tunnelId",1),heartbeatMs:le(t.heartbeatMs,"helloAck.heartbeatMs",1),maxStreams:le(t.maxStreams,"helloAck.maxStreams",1),maxFrame:le(t.maxFrame,"helloAck.maxFrame",1)}}),yn=ue(e=>{let t=te(e,"open"),n=ee(t.path,"open.path");if(!n.startsWith("/"))throw new U('open.path: expected a path starting with "/"');let r={method:ee(t.method,"open.method",1,16),path:n,headers:hn(t.headers,"open.headers")};if(t.hasBody!==void 0){if(typeof t.hasBody!="boolean")throw new U("open.hasBody: expected boolean");r.hasBody=t.hasBody}return r}),wn=ue(e=>{let t=te(e,"responseHeaders");return{status:le(t.status,"responseHeaders.status",100,599),headers:hn(t.headers,"responseHeaders.headers")}});function bn(e){return ue(t=>{let n=te(t,e);return{code:ee(n.code,`${e}.code`,1,64),message:n.message===void 0?"":ee(n.message,`${e}.message`,0,1024)}})}var vn=bn("reset"),Sn=bn("goaway");var ne=9,Se=64*1024,re=0,de=(c=>(c[c.Hello=1]="Hello",c[c.HelloAck=2]="HelloAck",c[c.Open=16]="Open",c[c.Headers=17]="Headers",c[c.Data=18]="Data",c[c.End=19]="End",c[c.Reset=20]="Reset",c[c.Goaway=32]="Goaway",c))(de||{}),Xo=new Set(Object.values(de).filter(e=>typeof e=="number"));function xn(e,t=Se){if(e.payload.byteLength>t)throw new k(S.frameTooLarge,`frame payload ${e.payload.byteLength} exceeds max ${t}`);let n=new Uint8Array(ne+e.payload.byteLength),r=new DataView(n.buffer);return r.setUint8(0,e.type),r.setUint32(1,e.streamId,!1),r.setUint32(5,e.payload.byteLength,!1),n.set(e.payload,ne),n}function An(e,t=Se){if(e.byteLength<ne)throw new k(S.frameTooShort,`frame is ${e.byteLength} bytes, header alone is ${ne}`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=n.getUint8(0);if(!Xo.has(r))throw new k(S.unknownFrameType,`unknown frame type 0x${r.toString(16)}`);let o=n.getUint32(1,!1),s=n.getUint32(5,!1);if(s>t)throw new k(S.frameTooLarge,`declared payload ${s} exceeds max ${t}`);if(e.byteLength!==ne+s)throw new k(S.frameLengthMismatch,`declared payload ${s} but message carries ${e.byteLength-ne}`);return{type:r,streamId:o,payload:e.subarray(ne)}}var $n="ora-tunnel.v1",kn=Se,zo=new TextEncoder,Qo=new TextDecoder,xe=class{constructor(t=Se){this.maxFrame=t}maxFrame;subprotocol=$n;encode(t){return xn(t,this.capFor(t.type))}decode(t){let n=An(t,Math.max(this.maxFrame,kn)),r=this.capFor(n.type);if(n.payload.byteLength>r)throw new k(S.frameTooLarge,`payload ${n.payload.byteLength} exceeds max ${r} for frame type 0x${n.type.toString(16)}`);return n}encodeJson(t,n,r){return this.encode({type:t,streamId:n,payload:zo.encode(JSON.stringify(r))})}decodeJson(t,n){let r;try{r=JSON.parse(Qo.decode(t.payload))}catch{throw new k(S.badJson,"frame payload is not valid JSON")}let o=mn(n,r);if(!o.success)throw new k(S.badPayload,o.error.message);return o.data}capFor(t){return t===18?this.maxFrame:kn}};var En=1e4;function Rn(e,t,n,r,o){return new Promise((s,i)=>{let a=!1,c=u=>{a||(a=!0,clearTimeout(l),u())},l=setTimeout(()=>{c(()=>{e.close(1002,S.handshakeTimeout),i(new k(S.handshakeTimeout,`no handshake frame within ${o}ms`))})},o);l.unref?.(),e.onError(u=>c(()=>i(u))),e.onClose((u,d)=>c(()=>i(new k(S.connectionClosed,`connection closed during handshake (${u}${d?`: ${d}`:""})`)))),e.onMessage(u=>{c(()=>{try{let d=t.decode(u);if(d.streamId!==re||d.type!==n)throw new k(S.handshakeProtocol,`expected handshake frame 0x${n.toString(16)}, got 0x${d.type.toString(16)} on stream ${d.streamId}`);s(t.decodeJson(d,r))}catch(d){e.close(1002,S.handshakeProtocol),i(d)}})})})}var je=class{constructor(t,n,r,o){this.id=t;this.codec=n;this.writer=r;this.onFinalized=o}id;codec;writer;onFinalized;localEnded=!1;remoteEnded=!1;resetPayload=null;handlers={};cancellation=new AbortController;get signal(){return this.cancellation.signal}get isFinalized(){return this.resetPayload!==null||this.localEnded&&this.remoteEnded}setHandlers(t){Object.assign(this.handlers,t)}sendData(t){this.assertWritable();let n=this.codec.maxFrame;for(let r=0;r<t.byteLength;r+=n)this.writer.writeFrame(this.codec.encode({type:18,streamId:this.id,payload:t.subarray(r,Math.min(r+n,t.byteLength))}))}sendHeaders(t){this.assertWritable(),this.writer.writeFrame(this.codec.encodeJson(17,this.id,t))}sendEnd(){this.localEnded||this.resetPayload||(this.localEnded=!0,this.writer.writeFrame(this.codec.encode({type:19,streamId:this.id,payload:new Uint8Array(0)})),this.maybeFinalize())}sendReset(t,n=""){if(this.resetPayload)return;let r={code:t,message:n};this.resetPayload=r;try{this.writer.writeFrame(this.codec.encodeJson(20,this.id,r))}finally{this.notifyReset(r)}}receive(t){if(!this.resetPayload)switch(t.type){case 17:this.handlers.onHeaders?.(this.codec.decodeJson(t,wn));return;case 18:if(this.remoteEnded)return;this.handlers.onData?.(t.payload);return;case 19:if(this.remoteEnded)return;this.remoteEnded=!0,this.handlers.onEnd?.(),this.maybeFinalize();return;case 20:{let n=this.codec.decodeJson(t,vn);this.resetPayload=n,this.notifyReset(n);return}default:throw new k(S.badPayload,`frame type 0x${t.type.toString(16)} is not valid on an open stream`)}}failLocally(t){this.resetPayload||(this.resetPayload=t,this.notifyReset(t))}notifyReset(t){this.cancellation.abort(new k(S.streamReset,`${t.code}: ${t.message}`)),this.handlers.onReset?.(t),this.onFinalized(this)}assertWritable(){if(this.resetPayload)throw new k(S.streamReset,`stream ${this.id} was reset (${this.resetPayload.code})`);if(this.localEnded)throw new k(S.streamClosed,`stream ${this.id} already ended locally`)}maybeFinalize(){this.localEnded&&this.remoteEnded&&this.onFinalized(this)}};var Ue=class{constructor(t,n){this.socket=t;this.opts=n}socket;opts;streams=new Map;nextStreamId=1;goingAway=!1;closed=!1;start(){this.socket.onMessage(t=>this.handleMessage(t)),this.socket.onClose((t,n)=>this.teardown(new k(S.connectionClosed,`connection closed (${t}${n?`: ${n}`:""})`))),this.socket.onError(t=>this.teardown(new k(S.connectionClosed,t.message)))}get activeStreamCount(){return this.streams.size}openStream(t){if(this.closed||this.goingAway)throw new k(S.connectionClosed,"connection is closed or draining");if(this.streams.size>=this.opts.maxStreams)throw new k(S.maxStreams,`stream cap ${this.opts.maxStreams} reached`);let n=this.createStream(this.nextStreamId);return this.nextStreamId+=2,this.socket.send(this.opts.codec.encodeJson(16,n.id,t)),n}goaway(t,n=""){this.closed||this.goingAway||(this.goingAway=!0,this.socket.send(this.opts.codec.encodeJson(32,re,{code:t,message:n})))}close(t,n){this.socket.close(t,n)}handleMessage(t){let n;try{n=this.opts.codec.decode(t),this.dispatch(n)}catch(r){if(r instanceof k){this.goaway(r.code,r.message),this.close(1002,r.code),this.teardown(r);return}throw r}}dispatch(t){if(t.streamId===re){t.type===32&&(this.goingAway=!0,this.opts.onGoaway?.(this.opts.codec.decodeJson(t,Sn)));return}if(t.type===16){this.handleOpen(t);return}let n=this.streams.get(t.streamId);if(!n){t.type!==19&&t.type!==20&&this.socket.send(this.opts.codec.encodeJson(20,t.streamId,{code:S.streamClosed,message:"unknown stream"}));return}n.receive(t)}handleOpen(t){if(!this.opts.onOpen){this.socket.send(this.opts.codec.encodeJson(20,t.streamId,{code:S.badPayload,message:"this side does not accept streams"}));return}if(this.goingAway)return;let n=this.opts.codec.decodeJson(t,yn);if(this.streams.size>=this.opts.maxStreams){this.socket.send(this.opts.codec.encodeJson(20,t.streamId,{code:S.maxStreams,message:`stream cap ${this.opts.maxStreams} reached`}));return}let r=this.createStream(t.streamId);this.opts.onOpen(r,n)}createStream(t){let n={writeFrame:o=>this.socket.send(o)},r=new je(t,this.opts.codec,n,o=>this.streams.delete(o.id));return this.streams.set(t,r),r}teardown(t){if(!this.closed){this.closed=!0;for(let n of[...this.streams.values()])n.failLocally({code:t.code,message:t.message});this.streams.clear(),this.opts.onConnectionClosed?.(t)}}};var De=class{constructor(t){this.onCancel=t}onCancel;buffered=[];pending=null;ended=!1;error=null;cancelled=!1;push(t){if(!(this.ended||this.error)){if(this.pending){let n=this.pending;this.pending=null,n.resolve({value:t,done:!1});return}this.buffered.push(t)}}end(){if(!(this.ended||this.error)&&(this.ended=!0,this.pending&&this.buffered.length===0)){let t=this.pending;this.pending=null,t.resolve({value:void 0,done:!0})}}fail(t){if(!(this.ended||this.error)&&(this.error=t,this.buffered.length=0,this.pending)){let n=this.pending;this.pending=null,n.reject(t)}}[Symbol.asyncIterator](){let t=!1,n=()=>{t||this.cancelled||(this.cancelled=!0,this.ended=!0,this.error=null,this.buffered.length=0,this.pending?.resolve({value:void 0,done:!0}),this.pending=null,this.onCancel?.())};return{next:()=>this.buffered.length>0?Promise.resolve({value:this.buffered.shift(),done:!1}):this.error?Promise.reject(this.error):this.ended?(t=!0,Promise.resolve({value:void 0,done:!0})):new Promise((r,o)=>{this.pending={resolve:s=>{s.done&&(t=!0),r(s)},reject:o}}),return:async()=>(n(),{value:void 0,done:!0}),throw:async r=>{throw n(),r}}}};function _n(e){let t=new De;return e.setHandlers({onData:n=>t.push(Uint8Array.from(n)),onEnd:()=>t.end(),onReset:n=>t.fail(new k(S.streamReset,`${n.code}: ${n.message}`))}),t}async function Tn(e,t){try{for await(let n of t)e.sendData(n);e.sendEnd()}catch(n){throw e.sendReset(S.forwardError,n instanceof Error?n.message:String(n)),n}}var Ae=class{constructor(t){this.opts=t}opts;mux=null;async start(){if(this.mux)throw new Error("connector already started");let{socket:t,codec:n,hello:r}=this.opts,o=Rn(t,n,2,fn,this.opts.handshakeTimeoutMs??En);t.send(n.encodeJson(1,re,r));let s=await o;return this.mux=new Ue(t,{codec:n,maxStreams:s.maxStreams,onOpen:(i,a)=>{this.serve(i,a)},onGoaway:this.opts.onGoaway,onConnectionClosed:this.opts.onConnectionClosed}),this.mux.start(),s}get activeStreamCount(){return this.mux?.activeStreamCount??0}close(t,n){(this.mux??this.opts.socket).close(t,n)}async serve(t,n){try{let r=await this.opts.forwarder.forward({method:n.method,path:n.path,headers:n.headers,body:_n(t),hasBody:n.hasBody,signal:t.signal});t.sendHeaders({status:r.status,headers:r.headers}),await Tn(t,r.body)}catch(r){try{t.sendReset(S.forwardError,r instanceof Error?r.message:String(r))}catch{}}}};var ht="tunnels:write + tunnels:connect",gt=[`--tunnel ora needs ORA_API_KEY: an ora platform key (ora_sk_...) with the ${ht} scopes.`,"Create one at https://agentfront.sh (API keys), export it or put it in a local .env,","or bring your own tunnel instead: --tunnel-cmd 'ngrok http 3000 --log stdout'"].join(`
|
|
24
|
-
`),
|
|
25
|
-
(--tunnel ora needs a platform key with the ${
|
|
26
|
-
`)))),l=u=>{let{code:d,reason:m}=u;i(()=>o(new
|
|
27
|
-
`;function
|
|
28
|
-
`))
|
|
29
|
-
`)}else{console.log(""),console.log(
|
|
30
|
-
`);else for(let h of an(rn(g,t),{showSkipped:e.showSkipped,showPassing:e.showPassing,tunnel:s}))console.log(h);if(n.value!==void 0){if(f.mcpAuthRequired)return process.stderr.write(Mn)
|
|
31
|
-
`)
|
|
21
|
+
`);for(;m!==-1;){let g=pt(u.slice(0,m));if(u=u.slice(m+2),m=u.indexOf(`
|
|
22
|
+
|
|
23
|
+
`),!g)continue;let f;try{f=JSON.parse(g.data)}catch{continue}if(Zo(l,g.event,f,r),l.summary&&l.insight)break e}}}catch(d){throw i.tripped()?new Error(`ora run stream timed out after ${o}ms of silence`):d}finally{i.disarm(),a.body.cancel().catch(()=>{})}return l}function Zo(e,t,n,r){switch(t){case"trajectory":{let o=n.steps;Array.isArray(o)&&(e.trajectory=o,r.snapshot?.(e.trajectory));return}case"step":{let o=n.step;o&&(e.steps.push(o),r.step?.(o,Number(n.seq??e.steps.length)));return}case"result":{let o=n.result;o&&(e.summary=o,r.finished?.(o));return}case"insight":{let o=n.insight;o&&(e.insight=o,r.scored?.(o));return}default:return}}async function es(e,t,n){for(let r=0;;r++){let o;try{let s=await fetch(`${e}/experiment/v1/runs?pageSize=50`,{headers:{authorization:`Bearer ${t}`}});if(!s.ok)return;o=(await s.json()).results?.find(a=>a.id===n)}catch{return}if(!o)return;if(o.total_tokens!=null||o.cost_usd!=null)return{totalTokens:o.total_tokens??void 0,inputTokens:o.input_tokens??void 0,outputTokens:o.output_tokens??void 0,cacheReadTokens:o.cache_read_tokens??void 0,cacheCreationTokens:o.cache_creation_tokens??void 0,costUsd:o.cost_usd??void 0};if(r>0)return;await Q(1200)}}async function mt(e,t={}){let n=(e.baseUrl??process.env.ORA_PLATFORM_URL??dn).replace(/\/+$/,""),r=e.apiKey??process.env.ORA_API_KEY;if(!r)throw new Error("Missing ORA_API_KEY. Set it in your environment or a local .env file (see .env.example).");let o=await Le(n,r),s=await zo(n,o,e),i={runId:s.runId,intent:e.intent,domain:e.domain,harness:e.harness};if(s.status==="succeeded"&&!s.streamUrl)return{...i,steps:[],trajectory:[]};t.opened?.(s.runId);let a=await Qo(n,o,s.streamUrl??`/experiment/v1/runs/${s.runId}/stream`,t,e.idleMs??Xo),c=a.summary?await es(n,o,s.runId):void 0;return{...i,result:a.summary,insight:a.insight,usage:c,steps:a.steps,trajectory:a.trajectory}}var k=class extends Error{constructor(n,r){super(r);this.code=n;this.name="ProtocolError"}code},S={frameTooShort:"FRAME_TOO_SHORT",frameTooLarge:"FRAME_TOO_LARGE",frameLengthMismatch:"FRAME_LENGTH_MISMATCH",unknownFrameType:"UNKNOWN_FRAME_TYPE",badJson:"BAD_JSON",badPayload:"BAD_PAYLOAD",handshakeTimeout:"HANDSHAKE_TIMEOUT",handshakeProtocol:"HANDSHAKE_PROTOCOL",maxStreams:"MAX_STREAMS",streamClosed:"STREAM_CLOSED",streamReset:"STREAM_RESET",forwardError:"FORWARD_ERROR",connectionClosed:"CONNECTION_CLOSED",superseded:"SUPERSEDED",timeout:"TIMEOUT"};function mn(e,t){return e.safeParse(t)}var U=class extends Error{};function te(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new U(`${t}: expected object`);return e}function ee(e,t,n=0,r=Number.POSITIVE_INFINITY){if(typeof e!="string")throw new U(`${t}: expected string`);if(e.length<n)throw new U(`${t}: expected at least ${n} characters`);if(e.length>r)throw new U(`${t}: expected at most ${r} characters`);return e}function le(e,t,n,r=Number.POSITIVE_INFINITY){if(typeof e!="number"||!Number.isInteger(e))throw new U(`${t}: expected integer`);if(e<n||e>r)throw new U(`${t}: expected ${n}..${r}`);return e}function hn(e,t){if(e===void 0)return{};let n={};for(let[r,o]of Object.entries(te(e,t)))if(typeof o=="string")n[r]=o;else if(Array.isArray(o)&&o.every(s=>typeof s=="string"))n[r]=o;else throw new U(`${t}.${r}: expected string or string[]`);return n}function ue(e){return{safeParse(t){try{return{success:!0,data:e(t)}}catch(n){if(n instanceof U)return{success:!1,error:{message:n.message}};throw n}}}}function gn(e,t){let n=te(e,t);if(n.protocol!=="http")throw new U(`${t}.protocol: expected "http"`);return{protocol:"http",host:ee(n.host,`${t}.host`,1),port:le(n.port,`${t}.port`,1,65535)}}var Sc=ue(e=>gn(e,"target")),xc=ue(e=>{let t=te(e,"hello");return{agentVersion:ee(t.agentVersion,"hello.agentVersion",1,64),target:gn(t.target,"hello.target"),maxStreams:t.maxStreams===void 0?32:le(t.maxStreams,"hello.maxStreams",1,256)}}),fn=ue(e=>{let t=te(e,"helloAck");return{tunnelId:ee(t.tunnelId,"helloAck.tunnelId",1),heartbeatMs:le(t.heartbeatMs,"helloAck.heartbeatMs",1),maxStreams:le(t.maxStreams,"helloAck.maxStreams",1),maxFrame:le(t.maxFrame,"helloAck.maxFrame",1)}}),yn=ue(e=>{let t=te(e,"open"),n=ee(t.path,"open.path");if(!n.startsWith("/"))throw new U('open.path: expected a path starting with "/"');let r={method:ee(t.method,"open.method",1,16),path:n,headers:hn(t.headers,"open.headers")};if(t.hasBody!==void 0){if(typeof t.hasBody!="boolean")throw new U("open.hasBody: expected boolean");r.hasBody=t.hasBody}return r}),wn=ue(e=>{let t=te(e,"responseHeaders");return{status:le(t.status,"responseHeaders.status",100,599),headers:hn(t.headers,"responseHeaders.headers")}});function bn(e){return ue(t=>{let n=te(t,e);return{code:ee(n.code,`${e}.code`,1,64),message:n.message===void 0?"":ee(n.message,`${e}.message`,0,1024)}})}var vn=bn("reset"),Sn=bn("goaway");var ne=9,Se=64*1024,re=0,de=(c=>(c[c.Hello=1]="Hello",c[c.HelloAck=2]="HelloAck",c[c.Open=16]="Open",c[c.Headers=17]="Headers",c[c.Data=18]="Data",c[c.End=19]="End",c[c.Reset=20]="Reset",c[c.Goaway=32]="Goaway",c))(de||{}),ts=new Set(Object.values(de).filter(e=>typeof e=="number"));function xn(e,t=Se){if(e.payload.byteLength>t)throw new k(S.frameTooLarge,`frame payload ${e.payload.byteLength} exceeds max ${t}`);let n=new Uint8Array(ne+e.payload.byteLength),r=new DataView(n.buffer);return r.setUint8(0,e.type),r.setUint32(1,e.streamId,!1),r.setUint32(5,e.payload.byteLength,!1),n.set(e.payload,ne),n}function An(e,t=Se){if(e.byteLength<ne)throw new k(S.frameTooShort,`frame is ${e.byteLength} bytes, header alone is ${ne}`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=n.getUint8(0);if(!ts.has(r))throw new k(S.unknownFrameType,`unknown frame type 0x${r.toString(16)}`);let o=n.getUint32(1,!1),s=n.getUint32(5,!1);if(s>t)throw new k(S.frameTooLarge,`declared payload ${s} exceeds max ${t}`);if(e.byteLength!==ne+s)throw new k(S.frameLengthMismatch,`declared payload ${s} but message carries ${e.byteLength-ne}`);return{type:r,streamId:o,payload:e.subarray(ne)}}var En="ora-tunnel.v1",kn=Se,ns=new TextEncoder,rs=new TextDecoder,xe=class{constructor(t=Se){this.maxFrame=t}maxFrame;subprotocol=En;encode(t){return xn(t,this.capFor(t.type))}decode(t){let n=An(t,Math.max(this.maxFrame,kn)),r=this.capFor(n.type);if(n.payload.byteLength>r)throw new k(S.frameTooLarge,`payload ${n.payload.byteLength} exceeds max ${r} for frame type 0x${n.type.toString(16)}`);return n}encodeJson(t,n,r){return this.encode({type:t,streamId:n,payload:ns.encode(JSON.stringify(r))})}decodeJson(t,n){let r;try{r=JSON.parse(rs.decode(t.payload))}catch{throw new k(S.badJson,"frame payload is not valid JSON")}let o=mn(n,r);if(!o.success)throw new k(S.badPayload,o.error.message);return o.data}capFor(t){return t===18?this.maxFrame:kn}};var Rn=1e4;function $n(e,t,n,r,o){return new Promise((s,i)=>{let a=!1,c=u=>{a||(a=!0,clearTimeout(l),u())},l=setTimeout(()=>{c(()=>{e.close(1002,S.handshakeTimeout),i(new k(S.handshakeTimeout,`no handshake frame within ${o}ms`))})},o);l.unref?.(),e.onError(u=>c(()=>i(u))),e.onClose((u,d)=>c(()=>i(new k(S.connectionClosed,`connection closed during handshake (${u}${d?`: ${d}`:""})`)))),e.onMessage(u=>{c(()=>{try{let d=t.decode(u);if(d.streamId!==re||d.type!==n)throw new k(S.handshakeProtocol,`expected handshake frame 0x${n.toString(16)}, got 0x${d.type.toString(16)} on stream ${d.streamId}`);s(t.decodeJson(d,r))}catch(d){e.close(1002,S.handshakeProtocol),i(d)}})})})}var je=class{constructor(t,n,r,o){this.id=t;this.codec=n;this.writer=r;this.onFinalized=o}id;codec;writer;onFinalized;localEnded=!1;remoteEnded=!1;resetPayload=null;handlers={};cancellation=new AbortController;get signal(){return this.cancellation.signal}get isFinalized(){return this.resetPayload!==null||this.localEnded&&this.remoteEnded}setHandlers(t){Object.assign(this.handlers,t)}sendData(t){this.assertWritable();let n=this.codec.maxFrame;for(let r=0;r<t.byteLength;r+=n)this.writer.writeFrame(this.codec.encode({type:18,streamId:this.id,payload:t.subarray(r,Math.min(r+n,t.byteLength))}))}sendHeaders(t){this.assertWritable(),this.writer.writeFrame(this.codec.encodeJson(17,this.id,t))}sendEnd(){this.localEnded||this.resetPayload||(this.localEnded=!0,this.writer.writeFrame(this.codec.encode({type:19,streamId:this.id,payload:new Uint8Array(0)})),this.maybeFinalize())}sendReset(t,n=""){if(this.resetPayload)return;let r={code:t,message:n};this.resetPayload=r;try{this.writer.writeFrame(this.codec.encodeJson(20,this.id,r))}finally{this.notifyReset(r)}}receive(t){if(!this.resetPayload)switch(t.type){case 17:this.handlers.onHeaders?.(this.codec.decodeJson(t,wn));return;case 18:if(this.remoteEnded)return;this.handlers.onData?.(t.payload);return;case 19:if(this.remoteEnded)return;this.remoteEnded=!0,this.handlers.onEnd?.(),this.maybeFinalize();return;case 20:{let n=this.codec.decodeJson(t,vn);this.resetPayload=n,this.notifyReset(n);return}default:throw new k(S.badPayload,`frame type 0x${t.type.toString(16)} is not valid on an open stream`)}}failLocally(t){this.resetPayload||(this.resetPayload=t,this.notifyReset(t))}notifyReset(t){this.cancellation.abort(new k(S.streamReset,`${t.code}: ${t.message}`)),this.handlers.onReset?.(t),this.onFinalized(this)}assertWritable(){if(this.resetPayload)throw new k(S.streamReset,`stream ${this.id} was reset (${this.resetPayload.code})`);if(this.localEnded)throw new k(S.streamClosed,`stream ${this.id} already ended locally`)}maybeFinalize(){this.localEnded&&this.remoteEnded&&this.onFinalized(this)}};var Ue=class{constructor(t,n){this.socket=t;this.opts=n}socket;opts;streams=new Map;nextStreamId=1;goingAway=!1;closed=!1;start(){this.socket.onMessage(t=>this.handleMessage(t)),this.socket.onClose((t,n)=>this.teardown(new k(S.connectionClosed,`connection closed (${t}${n?`: ${n}`:""})`))),this.socket.onError(t=>this.teardown(new k(S.connectionClosed,t.message)))}get activeStreamCount(){return this.streams.size}openStream(t){if(this.closed||this.goingAway)throw new k(S.connectionClosed,"connection is closed or draining");if(this.streams.size>=this.opts.maxStreams)throw new k(S.maxStreams,`stream cap ${this.opts.maxStreams} reached`);let n=this.createStream(this.nextStreamId);return this.nextStreamId+=2,this.socket.send(this.opts.codec.encodeJson(16,n.id,t)),n}goaway(t,n=""){this.closed||this.goingAway||(this.goingAway=!0,this.socket.send(this.opts.codec.encodeJson(32,re,{code:t,message:n})))}close(t,n){this.socket.close(t,n)}handleMessage(t){let n;try{n=this.opts.codec.decode(t),this.dispatch(n)}catch(r){if(r instanceof k){this.goaway(r.code,r.message),this.close(1002,r.code),this.teardown(r);return}throw r}}dispatch(t){if(t.streamId===re){t.type===32&&(this.goingAway=!0,this.opts.onGoaway?.(this.opts.codec.decodeJson(t,Sn)));return}if(t.type===16){this.handleOpen(t);return}let n=this.streams.get(t.streamId);if(!n){t.type!==19&&t.type!==20&&this.socket.send(this.opts.codec.encodeJson(20,t.streamId,{code:S.streamClosed,message:"unknown stream"}));return}n.receive(t)}handleOpen(t){if(!this.opts.onOpen){this.socket.send(this.opts.codec.encodeJson(20,t.streamId,{code:S.badPayload,message:"this side does not accept streams"}));return}if(this.goingAway)return;let n=this.opts.codec.decodeJson(t,yn);if(this.streams.size>=this.opts.maxStreams){this.socket.send(this.opts.codec.encodeJson(20,t.streamId,{code:S.maxStreams,message:`stream cap ${this.opts.maxStreams} reached`}));return}let r=this.createStream(t.streamId);this.opts.onOpen(r,n)}createStream(t){let n={writeFrame:o=>this.socket.send(o)},r=new je(t,this.opts.codec,n,o=>this.streams.delete(o.id));return this.streams.set(t,r),r}teardown(t){if(!this.closed){this.closed=!0;for(let n of[...this.streams.values()])n.failLocally({code:t.code,message:t.message});this.streams.clear(),this.opts.onConnectionClosed?.(t)}}};var We=class{constructor(t){this.onCancel=t}onCancel;buffered=[];pending=null;ended=!1;error=null;cancelled=!1;push(t){if(!(this.ended||this.error)){if(this.pending){let n=this.pending;this.pending=null,n.resolve({value:t,done:!1});return}this.buffered.push(t)}}end(){if(!(this.ended||this.error)&&(this.ended=!0,this.pending&&this.buffered.length===0)){let t=this.pending;this.pending=null,t.resolve({value:void 0,done:!0})}}fail(t){if(!(this.ended||this.error)&&(this.error=t,this.buffered.length=0,this.pending)){let n=this.pending;this.pending=null,n.reject(t)}}[Symbol.asyncIterator](){let t=!1,n=()=>{t||this.cancelled||(this.cancelled=!0,this.ended=!0,this.error=null,this.buffered.length=0,this.pending?.resolve({value:void 0,done:!0}),this.pending=null,this.onCancel?.())};return{next:()=>this.buffered.length>0?Promise.resolve({value:this.buffered.shift(),done:!1}):this.error?Promise.reject(this.error):this.ended?(t=!0,Promise.resolve({value:void 0,done:!0})):new Promise((r,o)=>{this.pending={resolve:s=>{s.done&&(t=!0),r(s)},reject:o}}),return:async()=>(n(),{value:void 0,done:!0}),throw:async r=>{throw n(),r}}}};function Tn(e){let t=new We;return e.setHandlers({onData:n=>t.push(Uint8Array.from(n)),onEnd:()=>t.end(),onReset:n=>t.fail(new k(S.streamReset,`${n.code}: ${n.message}`))}),t}async function _n(e,t){try{for await(let n of t)e.sendData(n);e.sendEnd()}catch(n){throw e.sendReset(S.forwardError,n instanceof Error?n.message:String(n)),n}}var Ae=class{constructor(t){this.opts=t}opts;mux=null;async start(){if(this.mux)throw new Error("connector already started");let{socket:t,codec:n,hello:r}=this.opts,o=$n(t,n,2,fn,this.opts.handshakeTimeoutMs??Rn);t.send(n.encodeJson(1,re,r));let s=await o;return this.mux=new Ue(t,{codec:n,maxStreams:s.maxStreams,onOpen:(i,a)=>{this.serve(i,a)},onGoaway:this.opts.onGoaway,onConnectionClosed:this.opts.onConnectionClosed}),this.mux.start(),s}get activeStreamCount(){return this.mux?.activeStreamCount??0}close(t,n){(this.mux??this.opts.socket).close(t,n)}async serve(t,n){try{let r=await this.opts.forwarder.forward({method:n.method,path:n.path,headers:n.headers,body:Tn(t),hasBody:n.hasBody,signal:t.signal});t.sendHeaders({status:r.status,headers:r.headers}),await _n(t,r.body)}catch(r){try{t.sendReset(S.forwardError,r instanceof Error?r.message:String(r))}catch{}}}};var gt="tunnels:write + tunnels:connect",ft=[`--tunnel ora needs ORA_API_KEY: an ora platform key (ora_sk_...) with the ${gt} scopes.`,"Create one at https://agentfront.sh (API keys), export it or put it in a local .env,","or bring your own tunnel instead: --tunnel-cmd 'ngrok http 3000 --log stdout'"].join(`
|
|
24
|
+
`),os=1,ss=32,ht=()=>new T("interrupted before the tunnel was ready");function is(e){let t;try{t=new URL(e.includes("://")?e:`http://${e}`)}catch{throw new T(`not a local target: ${JSON.stringify(e)}`)}if(t.protocol!=="http:")throw new T(`--tunnel ora forwards plain http only; ${t.protocol}// targets are not supported`);let n=t.hostname.replace(/^\[(.*)\]$/,"$1"),r=n==="localhost"?"127.0.0.1":n,o=t.port?Number(t.port):80;return{host:r,port:o}}async function In(e,t={}){let n=is(e),r=t.apiKey??process.env.ORA_API_KEY;if(!r)throw new T(ft);let o=pn(t.platformUrl),s;try{s=await Le(o,r)}catch(x){throw new T(`${x instanceof Error?x.message:String(x)}
|
|
25
|
+
(--tunnel ora needs a platform key with the ${gt} scopes)`)}if(t.signal?.aborted)throw ht();let i=await cs(o,s),a=()=>us(o,s,i.id,()=>Le(o,r)),c,l,u=!1,d=()=>{},m=new Promise(x=>{d=x}),g=new Promise((x,C)=>{t.signal?.aborted&&C(ht()),t.signal?.addEventListener("abort",()=>C(ht()),{once:!0})}),f;try{f=as(i),c=await Promise.race([ds(f,s),g]),l=new Ae({socket:ps(c),codec:new xe,hello:{agentVersion:`ax/${we.version}`,target:{protocol:"http",host:n.host,port:n.port},maxStreams:ss},forwarder:hs(n.host,n.port),onConnectionClosed:x=>{u||d(new T(`ora tunnel connection dropped: ${x.message}`))}}),await Promise.race([l.start(),g]),await dt(f.publicUrl,t.routableMs,t.probeEveryMs,t.signal)}catch(x){u=!0;try{l?l.close(1e3,"ax setup failed"):c?.close()}catch{}throw await a(),x}let h=l,p,y=()=>(p||(u=!0,p=(async()=>{try{h.close(1e3,"ax exit")}catch{}await a()})()),p);return{url:f.publicUrl,close:y,dropped:m}}function as(e){if(!e.publicUrl||!e.connection?.url||!e.connection.subprotocol)throw new T("ora created a tunnel but returned no public URL to connect to");if(e.connection.kind!=="ora-ws")throw new T(`ora returned a "${e.connection.kind}" tunnel, which this version of ax cannot connect; upgrade ax`);return e}async function cs(e,t){let n=await fetch(`${e}/tunnels/v1`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({name:`ax-${(0,Cn.randomBytes)(4).toString("hex")}`,access:"public"})}),r=await n.text(),o={};try{o=JSON.parse(r)}catch{}if(!n.ok){let s=o.error??o.message??r.trim().slice(0,200);throw new T(`${ls(n.status)}${s?`: ${s}`:""}`)}if(!o.id)throw new T("ora created a tunnel but returned no id");return o}function ls(e){switch(e){case 401:return"ora rejected the platform key (401). Check ORA_API_KEY";case 403:return`the platform key lacks the ${gt} scopes (403). Issue one with both and retry`;case 429:return"ora rate-limited the tunnel request (429). Wait a moment and retry";default:return`ora could not create a tunnel (${e})`}}async function us(e,t,n,r){let o=s=>fetch(`${e}/tunnels/v1/${n}`,{method:"DELETE",headers:{authorization:`Bearer ${s}`},signal:AbortSignal.timeout(1e4)});try{let s=await o(t);s.status===401&&(s=await o(await r())),!s.ok&&s.status!==404&&console.error(`could not delete ora tunnel ${n} (${s.status}); remove it with: ora tunnels delete ${n}`)}catch(s){console.error(`could not delete ora tunnel ${n} (${s instanceof Error?s.message:String(s)}); remove it with: ora tunnels delete ${n}`)}}function ds(e,t){let n=new URL(e.connection.url);return n.searchParams.set("tunnelId",e.id),n.searchParams.set("token",t),new Promise((r,o)=>{let s=new WebSocket(n,[e.connection.subprotocol]);s.binaryType="arraybuffer";let i=u=>{s.removeEventListener("open",a),s.removeEventListener("error",c),s.removeEventListener("close",l),u()},a=()=>i(()=>r(s)),c=()=>i(()=>o(new T(["ora refused the tunnel connection.","Either the platform key lacks the tunnels:connect scope, the bearer expired (401/403),","or the account's active-tunnel limit is reached (429): check `ora tunnels list`."].join(`
|
|
26
|
+
`)))),l=u=>{let{code:d,reason:m}=u;i(()=>o(new T(`ora closed the tunnel connection (${d??"?"} ${m??""})`)))};s.addEventListener("open",a),s.addEventListener("error",c),s.addEventListener("close",l)})}function ps(e){let t,n,r;return e.addEventListener("message",o=>{let s=o.data;s instanceof ArrayBuffer?t?.(new Uint8Array(s)):ArrayBuffer.isView(s)&&t?.(new Uint8Array(s.buffer,s.byteOffset,s.byteLength))}),e.addEventListener("close",o=>{let{code:s,reason:i}=o;n?.(s??1006,i??"")}),e.addEventListener("error",()=>r?.(new Error("tunnel socket error"))),{get bufferedAmount(){return e.bufferedAmount},send(o){e.readyState===os&&e.send(o)},close(o,s){try{e.close(o,s)}catch{}},onMessage:o=>{t=o},onClose:o=>{n=o},onError:o=>{r=o}}}var ms=new Set(["host","connection","keep-alive","transfer-encoding","upgrade","te"]);function hs(e,t){return{forward:n=>new Promise((r,o)=>{let s=(0,On.request)({host:e,port:t,path:n.path,method:n.method,headers:fs(n.headers)},i=>r({status:i.statusCode??502,headers:ys(i),body:i}));s.on("error",o),gs(n.body,s).catch(i=>{s.destroy(i instanceof Error?i:new Error(String(i))),o(i)})})}}async function gs(e,t){try{for await(let n of e)t.write(n)||await(0,Pn.once)(t,"drain")}finally{t.end()}}function fs(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!ms.has(t.toLowerCase())))}function ys(e){let t={};for(let[n,r]of Object.entries(e.headers))r!==void 0&&(t[n]=r);return t}var yt=B(D(),1);function Z(e,t){let n=process.stdout.columns??100;return Math.min(t,Math.max(e,n))}function oe(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function M(e,t){let n=[],r="";for(let o of e.replace(/\s+/g," ").trim().split(" "))r&&r.length+1+o.length>t?(n.push(r),r=o):r=r?`${r} ${o}`:o;return r&&n.push(r),n}var pe=["\u25C7","\u25C7","\u25C8","\u25C8","\u25C6","\u25C6","\u25C8","\u25C8"];function O(e){return e.replace(/[\u0000-\u001f\u007f-\u009f]/g," ")}var ws=80,De,wt=0,ke="";function bs(){let e=yt.default.cyan(pe[wt%pe.length]),t=Math.max(10,(process.stderr.columns??80)-2),n=ke.length>t?`${ke.slice(0,t-1)}\u2026`:ke;process.stderr.write(`\r\x1B[K${e} ${yt.default.dim(n)}`),wt++}var R={start(e){R.stop(),wt=0,ke=e,process.stderr.isTTY&&(De=setInterval(bs,ws))},update(e){ke=e},stop(){De&&(clearInterval(De),De=void 0,process.stderr.write("\r\x1B[K"))}};var E={OK:0,BELOW_MIN_SCORE:1,USAGE:2,API:3},Mn=`--min-score skipped: the MCP handshake requires credentials, so the target is unscored
|
|
27
|
+
`;function Nn(e,t,n,r){if(e===void 0)return{};let o=Number(e);return e.trim()===""||!Number.isInteger(o)||o<n||o>r?{error:`${t} must be an integer between ${n} and ${r}, got ${JSON.stringify(e)}`}:{value:o}}function vs(e){let t=e.trim().replace(/\/+$/,"");if(!(!t||/\s/.test(t)))try{let n=new URL(t.includes("://")?t:`https://${t}`);return!n.hostname.includes(".")&&n.hostname!=="localhost"?void 0:t}catch{return}}function Ss(e){let t=e.tunnelCmd?.trim();if(t)return{kind:"cmd",command:t};let n=e.tunnel?.trim();if(n!==void 0)return n!=="ora"?{error:`--tunnel must be "ora" (ora's own tunnel), got ${JSON.stringify(e.tunnel)}`}:{kind:"ora"};let r=process.env.ORA_TUNNEL_CMD?.trim();if(r)return{kind:"cmd",command:r};let o=process.env.ORA_TUNNEL?.trim();return o?o!=="ora"?{error:`ORA_TUNNEL must be "ora" (ora's own tunnel), got ${JSON.stringify(o)}`}:{kind:"ora"}:{kind:"none"}}function xs(e){let t=e?.mcpUrl;return typeof t=="string"&&t?t:void 0}async function Ln(e){let t=vs(e.url);if(!t)return console.error(`Not a scannable URL or domain: ${JSON.stringify(e.url)}`),E.USAGE;let n=Nn(e.minScore,"--min-score",0,100),r=Nn(e.maxAge,"--max-age",0,86400);for(let h of[n,r])if(h.error)return console.error(h.error),E.USAGE;let o=Ss(e);if("error"in o)return console.error(o.error),E.USAGE;let s=o.kind!=="none";if(!s&&ut(t))return console.error([`${t} only exists on this machine, and ora audits public URLs.`,"Either audit a publicly reachable deployment of this site (e.g. a preview URL),","or run it through a tunnel:"," ax audit localhost:3000 --tunnel ora # ora's own tunnel; needs ORA_API_KEY"," ax audit localhost:3000 --tunnel-cmd 'ora tunnel 3000 --access public'"," ax audit localhost:3000 --tunnel-cmd 'ngrok http 3000 --log stdout'","Any command that prints a public https URL works; the result is stored as","ephemeral (excluded from rankings, deleted after 7 days)."].join(`
|
|
28
|
+
`)),E.USAGE;if(o.kind==="ora"&&!process.env.ORA_API_KEY)return console.error(ft),E.USAGE;let i=!e.json;i&&R.start(`Auditing ${t} with ora`);let a,c,l=new AbortController,u=async()=>{await a?.close()},d=h=>{process.removeListener("SIGINT",d),process.removeListener("SIGTERM",d),l.abort(),(async()=>{await c?.catch(()=>{}),await u()})().finally(()=>process.exit(h==="SIGINT"?130:143))},m=t;if(o.kind!=="none"){i&&R.update(`Opening a tunnel to ${t}`),process.on("SIGINT",d),process.on("SIGTERM",d);try{c=o.kind==="ora"?In(t,{signal:l.signal}):un(o.command),a=await c}catch(h){return R.stop(),process.removeListener("SIGINT",d),process.removeListener("SIGTERM",d),console.error(h instanceof Error?h.message:String(h)),E.USAGE}m=a.url}let g;try{let h=tn(m,{progress:i?p=>R.update(p):void 0,maxAgeSeconds:r.value,force:e.force,ephemeral:s||void 0,apiKey:e.apiKey?.trim()||void 0});g=a?.dropped?await Promise.race([h,a.dropped.then(p=>Promise.reject(p))]):await h}catch(h){if(R.stop(),Zt(h)){if(e.json){let p=h.payload===void 0?{code:h.code,message:h.message}:h.payload;process.stdout.write(`${JSON.stringify(p,null,2)}
|
|
29
|
+
`)}else{console.log(""),console.log(bt.default.yellow(` ${ct}`));let p=xs(h.payload);p&&console.log(bt.default.dim(` MCP endpoint: ${p}`)),console.log("")}return n.value!==void 0&&process.stderr.write(Mn),E.OK}return console.error(`Audit failed: ${h instanceof Error?h.message:String(h)}`),h instanceof j?E.API:E.USAGE}finally{await u(),process.removeListener("SIGINT",d),process.removeListener("SIGTERM",d)}R.stop();let{result:f}=g;if(e.json)process.stdout.write(`${JSON.stringify(f,null,2)}
|
|
30
|
+
`);else for(let h of an(rn(g,t),{showSkipped:e.showSkipped,showPassing:e.showPassing,tunnel:s}))console.log(h);if(n.value!==void 0){if(f.mcpAuthRequired)return process.stderr.write(Mn),E.OK;if(f.score<n.value)return e.json||console.log(` Score ${f.score} is below the required minimum ${n.value}
|
|
31
|
+
`),E.BELOW_MIN_SCORE}return E.OK}var b=B(D(),1);var As="https://ora.ai",ks=12e4,Es=5e3,Rs=180,$s=15*6e4,Ts=6e4,_s=5,Cs=2e3,_=class extends Error{},Ee=class extends _{constructor(n,r,o){super(n);this.status=r;this.retryAfterMs=o}status;retryAfterMs};function vt(e){return(e??process.env.ORA_API_URL??As).replace(/\/+$/,"")}async function St(e){let t;try{t=await fetch(e,{headers:{accept:"application/json"},signal:AbortSignal.timeout(15e3)})}catch(n){let r=n instanceof Error?n.message:String(n);throw new _(`ora request failed: ${r}`)}if(!t.ok)throw new _(`ora request failed: ${await ce(t)}`);return await t.json()}function Un(e){return St(`${vt(e)}/api/journey/intents`)}function Wn(e){return St(`${vt(e)}/api/journey/agents`)}function Ps(e){let t=r=>{let o=e.headers.get(r);if(o===null)return;let s=Number.parseInt(o,10);return Number.isFinite(s)?s:void 0},n=t("x-ratelimit-reset");return{limit:t("x-ratelimit-limit"),remaining:t("x-ratelimit-remaining"),resetAtMs:n!==void 0?n*1e3:void 0}}async function Os(e,t,n){let r={intent:n.task?{custom:n.task,domain:t}:{...n.intentId?{intent_id:n.intentId}:{},domain:t},harness:n.harness,model:n.model},o;try{o=await fetch(`${e}/api/journey/runs`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json",...n.apiKey?{authorization:`Bearer ${n.apiKey}`}:{}},body:JSON.stringify(r),signal:AbortSignal.timeout(3e4)})}catch(i){let a=i instanceof Error?i.message:String(i);throw new _(`ora journey request failed: ${a}`)}if(o.status===401)throw new _("free-text tasks need an ora partner API key \u2014 set ORA_PARTNER_API_KEY or pass --api-key (keys are issued by ora on request)");if(o.status===429){let i=o.headers.get("retry-after"),a=n.apiKey?"keyed allowance: 1000 runs per 24h per key":"burst: 20/min/IP; daily: 20 runs per 24h per IP \u2014 an ora partner API key raises this to 1000/24h per key: set ORA_PARTNER_API_KEY or pass --api-key";throw new _(`ora journey caller limit exceeded${i?` \u2014 retry after ${xt(Number(i)*1e3)}`:""} (${a})`)}if(o.status===503)throw new _("ora's run engine is unavailable right now \u2014 try again shortly");if(!o.ok)throw new _(`ora journey request failed: ${await ce(o)}`);let s=await o.json();return be(s.contractVersion),{record:s,cached:s.rate_limited===!0,allowance:Ps(o)}}function xt(e){if(!Number.isFinite(e)||e<=0)return"soon";let t=e/36e5;if(t>=1)return`${Math.ceil(t)}h`;let n=e/6e4;return n>=1?`${Math.ceil(n)}m`:`${Math.ceil(e/1e3)}s`}function Is(e){if(!e)return"starting\u2026";if(e.type==="text")return"thinking\u2026";if(e.action==="search")return e.search_query?`searching \u201C${jn(e.search_query,40)}\u201D`:"searching\u2026";let t=e.label??`${e.url_host??""}${e.url_path??""}`,n=e.completed===!1?"fetching":"fetched";return t?`${n} ${jn(t,48)}`:`${n}\u2026`}function jn(e,t){return e.length>t?`${e.slice(0,t-1)}\u2026`:e}async function Ms(e,t,n){let r=t.startsWith("http")?t:`${e}${t}`,o=n.idleMs??ks,s=z(o),i=()=>new _(`ora journey stream timed out \u2014 no frames for ${Math.round(o/1e3)}s`),a;try{a=await fetch(r,{headers:{accept:"text/event-stream",...n.apiKey?{authorization:`Bearer ${n.apiKey}`}:{}},signal:s.signal})}catch(d){if(s.disarm(),s.tripped())throw i();let m=d instanceof Error?d.message:String(d);throw new _(`ora journey stream failed: ${m}`)}if(!a.ok||!a.body){s.disarm();let d=Number(a.headers.get("retry-after"));throw new Ee(`ora journey stream failed (${a.status}): ${await ce(a)}`,a.status,Number.isFinite(d)&&d>0?d*1e3:void 0)}let c=new TextDecoder,l={},u="";try{e:for await(let d of a.body){s.poke(),u=`${u}${c.decode(d,{stream:!0})}`.replace(/\r\n?/g,`
|
|
32
32
|
`);let m=u.indexOf(`
|
|
33
33
|
|
|
34
|
-
`);for(;m!==-1;){let g=
|
|
34
|
+
`);for(;m!==-1;){let g=pt(u.slice(0,m));if(u=u.slice(m+2),m=u.indexOf(`
|
|
35
35
|
|
|
36
|
-
`),!g)continue;let f;try{f=JSON.parse(g.data)}catch{continue}if(g.event==="trajectory"){let h=f.steps??[],p=h.filter(y=>y.type==="tool_call").at(-1);n.progress?.(`step ${h.length} \xB7 ${
|
|
37
|
-
`;t.length<this.rows&&(n+="\x1B[0J"),this.rows=t.length,process.stdout.write(n)}pulse(){!this.live||this.rows===0||(this.beat++,process.stdout.write(`\x1B[${this.rows}A\r\x1B[2K${this.banner()}\x1B[${this.rows}B\r`))}};var q={OK:0,RUN_FAILED:1,USAGE:2,API:3},
|
|
36
|
+
`),!g)continue;let f;try{f=JSON.parse(g.data)}catch{continue}if(g.event==="trajectory"){let h=f.steps??[],p=h.filter(y=>y.type==="tool_call").at(-1);n.progress?.(`step ${h.length} \xB7 ${Is(p??h.at(-1))}`),n.onTrajectory?.(h)}else if(g.event==="processing")n.progress?.(typeof f.message=="string"?f.message:"generating insights\u2026");else if(g.event==="result"){l.result=f;break e}else if(g.event==="error"){l.errorMessage=typeof f.message=="string"?f.message:"unknown engine error";break e}}}}catch(d){if(s.tripped())throw i();if(d instanceof _)throw d;let m=d instanceof Error?d.message:String(d);throw new _(`ora journey stream error: ${m}`)}finally{s.disarm(),a.body.cancel().catch(()=>{})}return l}async function Ns(e,t,n,r){let o=n.reopenPauseMs??Cs,s,i=0;for(let a=0;a<=_s&&Date.now()<r;a++){a>0&&(n.progress?.("stream dropped \u2014 reopening"),await Q(i)),i=o;try{let c=await Ms(e,t,n);if(c.result||c.errorMessage)return c.errorMessage;s=new _("ora journey stream closed before the run ended")}catch(c){if(s=c,c instanceof Ee){if(c.status!==429)throw c;i=Math.min(c.retryAfterMs??o,Ts)}}}throw s??new _("ora journey stream was never opened")}function Fe(e,t){return St(`${e}/api/journey/runs/${encodeURIComponent(t)}`)}async function Ls(e,t,n,r){let o=n.pollEveryMs??Es,s=n.pollLimit??Rs,i=await Fe(e,t);for(let a=0;a<s&&i.status==="running"&&Date.now()<r;a++){n.progress?.("agent working\u2026 (polling)"),await Q(o);try{i=await Fe(e,t)}catch{}}return i}async function Dn(e,t){let n=vt(t.baseUrl);t={...t,apiKey:t.apiKey||process.env.ORA_PARTNER_API_KEY||process.env.ORA_SCAN_API_KEY||void 0};let r=await Os(n,e,t),{record:o}=r;r.cached&&t.progress?.("target at its 24h cap \u2014 fetching the most recent stored run");let s,i;if(o.status==="running"){let c=Date.now()+(t.followBudgetMs??$s),l=t.noStream?{...t,onTrajectory:void 0}:t;try{s=await Ns(n,o.stream_url,l,c)}catch(u){if(u instanceof Ee&&u.status!==429)throw u;i=u instanceof Error?u.message:String(u),t.progress?.(`stream unavailable (${i}) \u2014 polling`),await Ls(n,o.id,t,c)}}let a=await js(n,o.id,t);if(a.status==="running")throw s?new _(`ora journey run failed: ${s}`):new _(`run ${o.id} is still executing \u2014 ${i?`the stream could not be followed (${i}) and polling ran out of time`:"the stream ended"} before a terminal result. Check ${n}/api/journey/runs/${o.id} shortly`);return be(a.contractVersion),{record:o,cached:r.cached,retryAfterMs:r.record.retry_after_ms,allowance:r.allowance,detail:a,engineError:s}}async function js(e,t,n){let r=await Fe(e,t);for(let o=0;o<3&&r.status==="running";o++)n.progress?.("finalizing\u2026"),await Q(1500),r=await Fe(e,t);return r}var P=B(D(),1);function At(e){if(!e)return{};let t=e.match(/https?:\/\/([^/\s]+)(\/\S*)?/i);return t?{host:t[1],path:t[2]??"/"}:{}}function se(e){return/search/i.test(`${e.tool??""} ${e.action??""}`)}function Us(e){if(se(e))return"\u{1F50D}";let t=`${e.tool??""} ${e.action??""}`.toLowerCase();return/fetch|http|get/.test(t)?"\u{1F310}":/read|open|view/.test(t)?"\u{1F4C4}":"\u{1F310}"}function Ws(e,t){if(se(e)){let c=e.input_display??String(e.input?.query??"search"),l=e.output_structured?.links?.length;return{id:e.id,kind:"search",icon:"\u{1F50D}",label:oe(`"${c}"`,t),meta:l?`${l} results`:void 0,tone:"ok",notes:[],children:[]}}let{host:n,path:r}=At(e.input_display??String(e.input?.url??"")),o=e.status,s=o!=null&&o>=300&&o<400,i=!!e.is_error||o!=null&&o>=400,a;if(s)a=`\u21B3 ${o}`;else if(i)a=`\u2717 ${o??"error"}`;else{let c=["\u2713"];o&&c.push(String(o)),e.duration_ms&&c.push(`${(e.duration_ms/1e3).toFixed(1)}s`),a=c.join(" ")}return{id:e.id,kind:"fetch",icon:Us(e),label:oe(`${n??"?"}${r??""}`,t),meta:a,tone:s?"redirect":i?"error":"ok",notes:[],children:[]}}function Be(e,t,n){let r=Z(60,120),o=Math.min(52,Math.max(24,r-40)),s=Math.max(30,r-24),i={id:-1,kind:"intent",icon:"\u25C6",label:oe(t,s),tone:"root",notes:[],children:[]},a=new Map,c=[],l,u,d;for(let m of e){if(m.type==="text"&&m.kind==="reasoning"){let h=(m.thinking??m.text??"").trim();h&&c.push(oe(h,s));continue}if(m.type!=="tool_call")continue;let g=Ws(m,o);g.notes=c,c=[],a.set(m.id,g);let f=i;if(!se(m)){let h=m.attribution?.referrer?.step_id,p=m.attribution?.kind,y=h!=null?a.get(h):void 0;y&&y!==g?f=y:p==="web_search"&&l?f=l:p==="previous_artifact"&&u&&(f=u)}f.children.push(g),se(m)?l=g:u=g,d=g}return d&&!n&&(d.tone="active",d.meta="\u2026"),{root:i,looseNotes:c}}function Je(e){let t=e.filter(o=>o.kind==="reasoning").length,n=e.filter(o=>o.type==="tool_call"&&se(o)).length,r=[`${P.default.bold(String(e.length))} steps`];return t&&r.push(`${P.default.bold(String(t))} reasoning`),n&&r.push(`${P.default.bold(String(n))} search${n===1?"":"es"}`),r.join(P.default.dim(" \xB7 "))}function Ds(e){switch(e){case"root":return{frame:P.default.dim,ink:t=>P.default.bold(t)};case"active":return{frame:P.default.cyan,ink:t=>P.default.cyan(P.default.bold(t))};case"redirect":return{frame:P.default.yellow,ink:P.default.yellow};case"error":return{frame:P.default.red,ink:P.default.red};default:return{frame:P.default.green,ink:P.default.green}}}var Fn=e=>P.default.dim(`(\u2026) ${e}`);function Bn(e,t){let{frame:n,ink:r}=Ds(e.tone),s=`${e.icon} ${e.label}${e.meta?` ${e.meta}`:""}`.length+2,i=`${e.icon} ${r(e.label)}${e.meta?` ${P.default.dim(e.meta)}`:""}`,a=e.children.length>0,c=e.notes.map(Fn);return c.push(n(`\u256D${"\u2500".repeat(s)}\u256E`)),c.push(`${n(t?"\u2524":"\u2502")} ${i} ${n("\u2502")}`),c.push(n(a?`\u2570\u2500\u252C${"\u2500".repeat(s-2)}\u256F`:`\u2570${"\u2500".repeat(s)}\u256F`)),e.children.forEach((l,u)=>{let d=u===e.children.length-1,m=Bn(l,!0),g=l.notes.length+1;m.forEach((f,h)=>{let p;h===g?p=d?" \u2570\u2500\u2500":" \u251C\u2500\u2500":h<g?p=" \u2502 ":p=d?" ":" \u2502 ",c.push(P.default.dim(p)+f)})}),c}function He(e){let t=Bn(e.root,!1);return e.looseNotes.length&&(t.push(""),t.push(...e.looseNotes.map(Fn))),t}var Ge=B(D(),1);var me=class{rows=0;beat=0;bornAt=Date.now();ticker;live=!!process.stdout.isTTY;content=[];headline="";open(){this.live&&!this.ticker&&(this.ticker=setInterval(()=>this.pulse(),100))}draw(t,n){this.content=t,this.headline=n,this.repaint()}close(){this.ticker&&(clearInterval(this.ticker),this.ticker=void 0),this.live&&this.rows>0&&(process.stdout.write(`\x1B[${this.rows}A\r\x1B[0J`),this.rows=0)}banner(){let t=Ge.default.cyan(pe[this.beat%pe.length]),n=Math.floor((Date.now()-this.bornAt)/1e3),r=`${this.headline} ${n}s`,o=Math.max(10,(process.stdout.columns??80)-6),s=r.length>o?`${r.slice(0,o-1)}\u2026`:r;return` ${t} ${Ge.default.bold(s)}`}clamp(t){let n=Math.max(2,(process.stdout.rows??24)-3);if(t.length<=n)return t;let r=n-1,o=t.length-r;return[Ge.default.dim(` \u22EF ${o} earlier line${o===1?"":"s"}`),...t.slice(-r)]}repaint(){if(!this.live)return;let t=[this.banner(),"",...this.clamp(this.content)],n=this.rows>0?`\x1B[${this.rows}A`:"";for(let r of t)n+=`\x1B[2K${r}
|
|
37
|
+
`;t.length<this.rows&&(n+="\x1B[0J"),this.rows=t.length,process.stdout.write(n)}pulse(){!this.live||this.rows===0||(this.beat++,process.stdout.write(`\x1B[${this.rows}A\r\x1B[2K${this.banner()}\x1B[${this.rows}B\r`))}};var q={OK:0,RUN_FAILED:1,USAGE:2,API:3},Fs="public caps: 100 runs/24h per target \xB7 20 runs/24h per IP",Bs="keyed caps: 1000 runs/24h per key \xB7 no per-target cap",Js={id:"cas-haiku",label:"Claude Code",variant:"Haiku 4.5",harness:"claude-agent-sdk",model:"claude-haiku-4-5",blurb:"Fast, frugal navigator \u2014 the CLI default."};function kt(e){return console.error(b.default.red(`ax deep-journey: ${e}`)),q.API}function Hs(e,t){if(t==="failed")return b.default.red("\u2717 run failed");switch(e){case"satisfied":return b.default.green("\u2713 task satisfied");case"partial":return b.default.yellow("\u25D0 partially satisfied");case"unsatisfied":return b.default.red("\u2717 task not satisfied");default:return b.default.dim("\xB7 not gradable")}}function Et(e){return`${e.label} \xB7 ${e.variant}`}function Jn(e){let n=e.action==="search"?e.search_query:e.url_host||e.url_path?`https://${e.url_host??""}${e.url_path??""}`:e.url;return{id:e.id,turn:e.turn??0,type:e.type,kind:e.type==="text"?"reasoning":void 0,text:e.text,thinking:e.text,tool:e.tool,action:e.action,input_display:n,status:e.status,duration_ms:e.duration_ms,attribution:e.attribution?{kind:e.attribution.kind,referrer:{step_id:e.attribution.referrer?.step_id??e.parent_id}}:void 0}}function Hn(e,t,n){return[` ${Je(e)}`,"",...He(Be(e,t,n)).map(r=>` ${r}`)]}var Gs=e=>e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e);function Ks(e){return e<.01?`$${e.toFixed(4)}`:e<1?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function qs(e){if(!e)return;let{input_tokens:t,output_tokens:n}=e;if(!(t==null&&n==null))return(t??0)+(n??0)}function Ys(e){return(e?.trajectory?.steps??[]).filter(t=>t.action==="search").length}function Rt(e,t,n){return e>=t?b.default.green:e>=n?b.default.yellow:b.default.red}function Vs(e){let t=e.run_signals,r=(e.trajectory?.steps??[]).filter(s=>s.type==="tool_call"&&(s.action==="fetch"||s.action==="api_call")),o=[];if(t?.answer_basis!=null){let s=Math.round(t.answer_basis.site_share*100);o.push({label:"answer from your site",pct:s,paint:Rt(s,70,40)})}if(t?.answer_efficiency!=null){let s=Math.round(t.answer_efficiency*100);o.push({label:"answer efficiency",pct:s,paint:Rt(s,70,30)})}if(r.length){let s=t?.link_following_rate??r.filter(a=>a.attribution?.kind==="previous_artifact").length/r.length,i=Math.round(s*100);o.push({label:"followed site links",pct:i,paint:Rt(i,70,35)})}return o}function Xs(e,t=20,n=21){let r=Math.max(0,Math.min(t,Math.round(e.pct/100*t))),o=`${e.paint("\u25B0".repeat(r))}${b.default.dim("\u25B1".repeat(t-r))}`,s=`${e.pct}%`.padStart(4);return` ${b.default.dim(e.label.padEnd(n))} ${o} ${e.paint(b.default.bold(s))}`}function $t(e,t,n){let r=Math.max(0,t-e.length),o=Math.floor(r/2);return`${" ".repeat(o)}${n(e)}${" ".repeat(r-o)}`}function zs(e,t){let n=e.length;if(n===0)return null;let r=4,o=Math.min(t,100)-2,s=Math.floor((o-r*(n-1))/n);if(s<18)return null;let i=[],a=[],c=[],l=1;for(let m of e){i.push($t(`${m.pct}%`,s,p=>m.paint(b.default.bold(p))));let g=s-2,f=Math.max(1,Math.min(g,Math.round(m.pct/100*g)));a.push(` ${m.paint("\u2594".repeat(f))}${b.default.dim("\u2594".repeat(g-f))} `);let h=M(m.label.toUpperCase(),s).map(p=>$t(p,s,b.default.dim));c.push(h),l=Math.max(l,h.length)}let u=m=>` ${m.join(" ".repeat(r))}`,d=["",u(i),u(a)];for(let m=0;m<l;m++)d.push(u(c.map(g=>g[m]??$t("",s,b.default.dim))));return d}function Gn(e,t){let n=t.filter(i=>i.n>0),r=n.reduce((i,a)=>i+a.n,0);if(!n.length||!r)return[];let o=Math.max(...n.map(i=>i.label.length)),s=["",` ${b.default.dim(e)}`];for(let i of n){let a=Math.round(i.n/r*100),c=Math.max(0,Math.min(20,Math.round(a/100*20))),l=`${b.default.dim("\u25B0".repeat(c))}${b.default.dim("\u25B1".repeat(20-c))}`;s.push(` ${b.default.dim(i.label.padEnd(o))} ${l} ${b.default.dim(`${a}%`.padStart(4))}`)}return s}function Qs(e){return b.default.dim(` ${"\u2500".repeat(Math.min(e-4,52))}`)}function Zs(e,t){let n=e.run_signals,r=[];if(n?.reached_anchor!=null){let c=n.reached_anchor?b.default.green("\u2713 reached the site"):b.default.red("\u2717 never reached the site");r.push("",` ${c}`)}let o=Vs(e);if(o.length){let c=zs(o,t);if(c)r.push(...c);else{r.push("");for(let l of o)r.push(Xs(l))}}let s=n?.answer_basis;s&&s.sections_total>0&&r.push(...Gn("answer sources",[{label:"from this site",n:s.from_site},{label:"from external pages",n:s.from_external},{label:"from search results",n:s.from_search},{label:"from agent knowledge",n:s.from_memory}]));let a=(e.trajectory?.steps??[]).filter(c=>c.type==="tool_call"&&(c.action==="fetch"||c.action==="api_call"));if(a.length){let c=u=>{let d=u.attribution?.kind;return d==="previous_step"||d==="previous_artifact"?"previous_artifact":d==="web_search"?"web_search":d==="prior_knowledge"&&u.anchor_relation==="exact"&&(!u.url_path||u.url_path==="/")?"task_input":"prior_knowledge"},l={};for(let u of a){let d=c(u);l[d]=(l[d]??0)+1}r.push(...Gn("url discovery",[{label:"given in the task",n:l.task_input??0},{label:"followed a link",n:l.previous_artifact??0},{label:"found via web search",n:l.web_search??0},{label:"guessed the URL",n:l.prior_knowledge??0}]))}return r}function ei(e,t){let n=Z(60,120),{detail:r}=e,o=r.result,s=["",Qs(n),""];s.push(` ${Hs(r.verdict,r.status)} ${b.default.dim("\xB7")} ${b.default.dim(r.domain??t)}`);let i=[];r.step_count!=null&&i.push(`${r.step_count} steps`);let a=o?.run_signals?.search_count??Ys(o);a&&i.push(`${a} search${a===1?"":"es"}`),o?.duration_ms!=null&&i.push(`${(o.duration_ms/1e3).toFixed(1)}s`);let c=qs(o);if(c!=null&&i.push(`${Gs(c)} tokens`),o?.cost_usd!=null&&i.push(Ks(o.cost_usd)),i.length&&s.push(` ${b.default.dim(i.join(" \xB7 "))}`),o&&s.push(...Zs(o,n)),o?.insight?.summary){s.push("");for(let u of M(O(o.insight.summary),n-4))s.push(` ${u}`)}let l=o?.insight?.key_observations??[];if(l.length){s.push("",` ${b.default.bold("Observations")}`);for(let u of l){let[d,...m]=M(O(u),n-6);s.push(` ${b.default.cyan("\xB7")} ${d}`);for(let g of m)s.push(` ${g}`)}}return r.status==="failed"&&s.push("",b.default.dim(e.engineError?` Engine error: ${e.engineError} \u2014 re-running is free to try.`:" The run ended in an engine error; re-running is free to try.")),s.push("",b.default.dim(` For the 4-layer readiness audit, run: ax audit ${t}`)),s}async function Kn(e){let t=e.url.trim();if(!t)return console.error("ax deep-journey: a target URL or domain is required"),q.USAGE;let n=!e.json&&process.stderr.isTTY,r=e.task?.trim()||void 0,o=e.apiKey||process.env.ORA_PARTNER_API_KEY||process.env.ORA_SCAN_API_KEY||void 0;if(r&&e.intent!==void 0)return console.error("ax deep-journey: --task and --intent are mutually exclusive \u2014 a free-text task replaces the curated intent"),q.USAGE;if(r&&!o)return console.error("ax deep-journey: --task needs an ora partner API key \u2014 set ORA_PARTNER_API_KEY or pass --api-key (keys are issued by ora on request)"),q.USAGE;let s=e.intent,i,a=r??"journey";try{let[p,y]=await Promise.all([r?void 0:Un(),Wn()]);if(p){if(s===void 0)s=p.defaultId;else if(!p.intents.some(ae=>ae.id===s))return console.error(`ax deep-journey: unknown intent "${s}". Available intents:
|
|
38
38
|
${p.intents.map(ae=>` ${ae.id.padEnd(12)} ${ae.hint}`).join(`
|
|
39
|
-
`)}`),q.USAGE;let
|
|
40
|
-
${C.map(
|
|
41
|
-
`)}`),q.USAGE;i=
|
|
42
|
-
`}var
|
|
43
|
-
`):console.error(`generate-files failed: ${c instanceof Error?c.message:String(c)}`),c instanceof Y&&c.status===400
|
|
44
|
-
`)
|
|
45
|
-
`),i.result?.outcome==="success"?0:1}catch(i){return console.error(`Journey failed: ${i instanceof Error?i.message:String(i)}`),2}let n=new me,r=[],o=!1,s=()=>[` ${Je(r)}`,"",...He(Be(r,e.intent,o)).map(i=>` ${i}`)];console.log(),console.log(` ${
|
|
46
|
-
`)
|
|
47
|
-
`).map(i=>i.trim()).filter(i=>i.length>0).join(", ");t[o]=t[o]===void 0?s:`${t[o]}, ${s}`}return t}function
|
|
39
|
+
`)}`),q.USAGE;let L=p.intents.find(ae=>ae.id===s);a=(L?.template||L?.hint||L?.label||s||"journey").replace(/\{domain\}/g,t)}let C=y.agents.some(L=>L.harness==="claude-agent-sdk"&&/haiku/i.test(L.model))?y.agents:[Js,...y.agents],Re=C.find(L=>L.harness==="claude-agent-sdk"&&/haiku/i.test(L.model))?.id??y.defaultId,$e=e.agent??Re,Wt=C.find(L=>L.id===$e);if(!Wt)return console.error(`ax deep-journey: unknown agent "${$e}". Available agents:
|
|
40
|
+
${C.map(L=>` ${L.id.padEnd(12)} ${Et(L)}`).join(`
|
|
41
|
+
`)}`),q.USAGE;i=Wt}catch(p){return kt(p instanceof Error?p.message:String(p))}e.json||console.error(b.default.dim(o?Bs:Fs));let c=n&&!e.noStream,l=new me,u=[],d=`waking ${i.label}`,m=()=>l.draw(Hn(u,a,!1),d);c?(console.log(),console.log(` ${b.default.cyan("\u25B6")} ${b.default.bold(t)} ${b.default.dim("\xB7")} ${b.default.dim(Et(i))} ${b.default.dim("\xB7")} ${b.default.dim(r?"custom task":s??"default")}`),console.log(),l.open(),m()):n&&R.start(`Sending ${Et(i)} to ${t} (${r?`"${r}"`:s})`);let g=p=>{c?(d=p,m()):n&&R.update(p)},f;try{f=await Dn(t,{intentId:r?void 0:s,task:r,apiKey:o,harness:i.harness,model:i.model,noStream:e.noStream,progress:n?g:void 0,onTrajectory:c?p=>{u=p.map(Jn),m()}:void 0})}catch(p){return c?l.close():n&&R.stop(),p instanceof _?kt(p.message):kt(p instanceof Error?p.message:String(p))}if(c?l.close():n&&R.stop(),e.json)return console.log(JSON.stringify(f.detail,null,2)),f.detail.status==="failed"?q.RUN_FAILED:q.OK;f.cached?console.error(b.default.yellow(`This target hit its 24h cap \u2014 showing the most recent stored run${f.retryAfterMs?` (fresh run in ${xt(f.retryAfterMs)})`:""}.`)):f.allowance.remaining!==void 0&&f.allowance.limit!==void 0&&console.error(b.default.dim(`allowance: ${f.allowance.remaining} of ${f.allowance.limit} target runs left in the 24h window`));let h=(f.detail.result?.trajectory?.steps??[]).map(Jn);if(h.length){console.log();for(let p of Hn(h,a,!0))console.log(p)}for(let p of ei(f,t))console.log(p);return f.detail.status==="failed"?q.RUN_FAILED:q.OK}var he=require("fs"),F=require("path"),W=B(D(),1);var ti="https://ora.ai",ni=3e4,Y=class extends Error{status;payload;constructor(t,n={}){super(t),this.name="AgentFilesApiError",this.status=n.status??null,this.payload=n.payload}},ri=/^[a-z0-9._-]+$/;function oi(e){if(!e.startsWith("/"))return!1;let t=e.slice(1).split("/");return t.length>=1&&t.length<=6&&t.every(n=>ri.test(n)&&n!=="."&&n!=="..")}function qn(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t--;return e.slice(0,t)}function si(e){return qn(e.trim().replace(/^https?:\/\//i,""))}async function Yn(e,t={}){let n=qn(t.baseUrl??process.env.ORA_API_URL??ti),r=`${n}/api/agent-files/${encodeURIComponent(si(e))}?include=all`,o;try{o=await fetch(r,{headers:{accept:"application/json"},signal:AbortSignal.timeout(ni)})}catch(i){throw new Y(`could not reach ora at ${n}: ${i instanceof Error?i.message:String(i)}`)}if(!o.ok){let{message:i,payload:a}=await ve(o);throw new Y(i,{status:o.status,payload:a})}let s=await o.json();if(!Array.isArray(s?.files))throw new Y("ora answered without a files list",{status:o.status,payload:s});for(let i of s.files)if(!oi(i.path))throw new Y(`ora named a file path ax will not write: ${JSON.stringify(i.path)}`,{status:o.status,payload:s});return s}function ii(e){return typeof e.body=="string"?e.body:`${JSON.stringify(e.content,null,2)}
|
|
42
|
+
`}var ai=new Map([["/.well-known/ard.json",[".well-known","ard.json"]],["/.well-known/ai-catalog.json",[".well-known","ai-catalog.json"]],["/.well-known/poppy.json",[".well-known","poppy.json"]],["/.well-known/api-catalog",[".well-known","api-catalog"]],["/llms.txt",["llms.txt"]],["/robots.txt",["robots.txt"]]]),ci="/server-card";function li(e,t){if(!e.url)return!0;try{return new URL(e.url).hostname===t}catch(n){if(n instanceof TypeError)return!1;throw n}}function ui(e,t){let n=(0,F.resolve)(t),r={writes:[],elsewhere:[],unknown:[]};for(let o of e.files){if(!li(o,e.domain)){r.elsewhere.push(o);continue}let s=ai.get(o.path);if(s)r.writes.push({target:(0,F.join)(n,...s),file:o});else if(o.path.endsWith(ci)){let i=(0,F.join)(n,...o.path.slice(1).split("/"));if((0,F.relative)(n,i).startsWith(".."))throw new Y(`refusing to write outside ${n}: ${o.path}`);r.writes.push({target:i,file:o})}else r.unknown.push(o)}return r}function Vn(e,t=process.cwd()){let n=(0,F.relative)(t,e);return n&&!n.startsWith("..")&&!(0,F.isAbsolute)(n)?n:e}function di(e,t,n){let r=[],o="";for(let s of e.split(/\s+/))o&&`${o} ${s}`.length>t?(r.push(n+o),o=s):o=o?`${o} ${s}`:s;return o&&r.push(n+o),r}async function Xn(e){if(!e.domain?.trim())return console.error("Usage: ax generate-files <domain>"),E.USAGE;let t;try{t=await Yn(e.domain,{baseUrl:e.baseUrl})}catch(c){return e.json&&c instanceof Y&&c.payload!==void 0?process.stdout.write(`${JSON.stringify(c.payload,null,2)}
|
|
43
|
+
`):console.error(`generate-files failed: ${c instanceof Error?c.message:String(c)}`),c instanceof Y&&c.status===400?E.USAGE:E.API}if(e.json)return process.stdout.write(`${JSON.stringify(t,null,2)}
|
|
44
|
+
`),E.OK;let n=e.out??".",{writes:r,elsewhere:o,unknown:s}=ui(t,n);for(let c of s)console.error(W.default.yellow(`skipped ${c.path}: this version of ax does not write it - upgrade with npm i -g ax@latest`));let i=r.filter(c=>(0,he.existsSync)(c.target));if(i.length>0&&!e.force){console.error("These files already exist, so nothing was written:");for(let c of i)console.error(` ${Vn(c.target)}`);return console.error(W.default.dim("Pass --force to overwrite them, or --out <dir> to write somewhere else.")),E.USAGE}for(let{target:c,file:l}of r)(0,he.mkdirSync)((0,F.dirname)(c),{recursive:!0}),(0,he.writeFileSync)(c,ii(l));let a=c=>{for(let l of c){let[u,...d]=di(l,74,"");console.log(W.default.dim(` - ${u}`));for(let m of d)console.log(W.default.dim(` ${m}`))}};console.log(""),console.log(` ${W.default.bold(t.domain)} ${W.default.dim(t.scannedAt?`from ora's scan of ${t.scannedAt.slice(0,10)}`:"not scanned by ora yet")}`),console.log("");for(let{target:c,file:l}of r)console.log(` ${W.default.green("wrote")} ${Vn(c)} ${W.default.dim(`${l.spec.name} ${l.spec.version}`)}`),a(l.notes),console.log("");for(let c of o)console.log(` ${W.default.yellow("not written")} ${c.url} ${W.default.dim(`${c.spec.name} ${c.spec.version}`)}`),a(["This file is served from another host, so it is not written here. Run with --json to get its body.",...c.notes]),console.log("");return t.notes&&t.notes.length>0&&(console.log(` ${W.default.bold("Not drafted")}`),a(t.notes),console.log("")),console.log(W.default.dim(` Publish them at https://${t.domain}/ from your web root - these are drafts, review each before you ship it.`)),console.log(""),E.OK}var A=B(D(),1);var Ke=()=>Z(60,120);function pi(e){if(e.type==="tool_call"){let t=e.input_display??e.summary??"";if(se(e))return t?`searching ${oe(t,40)}`:"searching\u2026";let{host:n}=At(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 mi=e=>e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e);function hi(e){return e<.01?`$${e.toFixed(4)}`:e<1?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function gi(e,t){let n=e.outcome==="success",r=[];return e.num_turns!=null&&r.push(`${e.num_turns} turns`),e.duration_ms!=null&&r.push(`${(e.duration_ms/1e3).toFixed(1)}s`),t?.totalTokens!=null&&r.push(`${mi(t.totalTokens)} tokens`),t?.costUsd!=null&&r.push(hi(t.costUsd)),["",` ${A.default.dim("\u2500".repeat(Math.min(Ke()-4,52)))}`,` ${n?A.default.green("\u2713"):A.default.red("\u2717")} ${A.default.bold(n?"completed":e.outcome)}${r.length?` ${A.default.dim(r.join(" \xB7 "))}`:""}`]}function fi(e,t=22){let n=Math.min(100,Math.max(0,e)),r=Math.round(n/100*t);return(n>=70?A.default.green:n>=50?A.default.yellow:A.default.red)("\u2588".repeat(r))+A.default.dim("\u2591".repeat(t-r))}function yi(e){return e==="high"?A.default.red("\u25CF high "):e==="medium"?A.default.yellow("\u25CF medium"):e==="low"?A.default.dim("\u25CF low "):A.default.dim("\u25CF ")}function wi(e){let t=[""];if(e.visibility_score!=null){let n=e.visibility_score,r=n>=70?A.default.green:n>=50?A.default.yellow:A.default.red,o=e.intent_satisfied?A.default.green("\u2713 intent satisfied"):A.default.yellow("\u2717 intent not satisfied");t.push(` ${A.default.bold("Visibility")} ${fi(n)} ${r(A.default.bold(`${n}/100`))} ${o}`)}if(e.summary){t.push("");for(let n of M(e.summary,Ke()-4))t.push(` ${A.default.dim(n)}`)}if(e.friction_points?.length){t.push("",` ${A.default.bold("Friction")}`);for(let n of e.friction_points){let[r,...o]=M(n,Ke()-6);t.push(` ${A.default.yellow("\xB7")} ${r}`);for(let s of o)t.push(` ${s}`)}}if(e.recommendations?.length){t.push("",` ${A.default.bold("Recommendations")}`);for(let n of e.recommendations){t.push(` ${yi(n.priority)} ${A.default.bold(n.title)}`);for(let r of M(n.detail,Ke()-8))t.push(` ${A.default.dim(r)}`)}}return t.push(""),t}function bi(e){let t=e.insight??{};return JSON.stringify({runId:e.runId,intent:e.intent,domain:e.domain,harness:e.harness,model:e.result?.effective_model??e.result?.model,outcome:e.result?.outcome,durationMs:e.result?.duration_ms,numTurns:e.result?.num_turns,totalTokens:e.usage?.totalTokens,inputTokens:e.usage?.inputTokens,outputTokens:e.usage?.outputTokens,costUsd:e.usage?.costUsd,visibilityScore:t.visibility_score,intentSatisfied:t.intent_satisfied,taskSatisfied:t.task_satisfied,summary:t.summary,keyObservations:t.key_observations,frictionPoints:t.friction_points,recommendations:t.recommendations,journeyLayers:t.journey_layers,intentCategory:t.intent_category,steps:e.trajectory},null,2)}async function zn(e){let t={intent:e.intent,domain:e.domain,harness:e.harness,model:e.model};if(e.json)try{let i=await mt(t);return process.stdout.write(`${bi(i)}
|
|
45
|
+
`),i.result?.outcome==="success"?0:1}catch(i){return console.error(`Journey failed: ${i instanceof Error?i.message:String(i)}`),2}let n=new me,r=[],o=!1,s=()=>[` ${Je(r)}`,"",...He(Be(r,e.intent,o)).map(i=>` ${i}`)];console.log(),console.log(` ${A.default.cyan("\u25B6")} ${e.domain?A.default.bold(e.domain):A.default.dim("(no domain)")} ${A.default.dim("\xB7")} ${A.default.dim(e.harness)}`),console.log(),n.open(),n.draw(s(),"waking the agent");try{let i=await mt(t,{snapshot:a=>{r=a;let c=a[a.length-1];n.draw(s(),c?pi(c):"working")},finished:()=>{o=!0,n.draw(s(),"scoring the journey")}});n.close(),o=!0,i.trajectory.length&&(r=i.trajectory);for(let a of s())console.log(a);if(i.result)for(let a of gi(i.result,i.usage))console.log(a);if(i.insight)for(let a of wi(i.insight))console.log(a);else i.result&&(console.log(A.default.dim(" (insight not available for this run)")),console.log());return i.result?.outcome==="success"?0:1}catch(i){return n.close(),console.error(`Journey failed: ${i instanceof Error?i.message:String(i)}`),2}}var qe=require("fs"),_t=require("path"),ge=B(D(),1);var Zn=require("crypto"),vi="https://ora.ai",H=class extends Error{};function er(e){return(e??process.env.ORA_API_URL??vi).replace(/\/+$/,"")}async function Tt(e){let t=er(e),n;try{n=await fetch(`${t}/.well-known/agent-skills/index.json`,{headers:{accept:"application/json"},signal:AbortSignal.timeout(15e3)})}catch(o){throw new H(`could not reach the skill registry at ${t}: ${o instanceof Error?o.message:String(o)}`)}if(!n.ok)throw new H(`skill registry answered HTTP ${n.status}`);let r=await n.json();if(!Array.isArray(r.skills))throw new H("skill registry index has no skills[]");return r.skills}function Qn(e){return`sha256:${(0,Zn.createHash)("sha256").update(e).digest("hex")}`}async function tr(e,t){let n=er(t),r=await Tt(n),o=r.find(c=>c.name===e);if(!o){let c=r.map(l=>l.name).join(", ");throw new H(`unknown skill ${JSON.stringify(e)} - the registry has: ${c}`)}let s=o.url.startsWith("http")?o.url:`${n}${o.url}`,i;try{i=await fetch(s,{signal:AbortSignal.timeout(15e3)})}catch(c){throw new H(`could not fetch ${s}: ${c instanceof Error?c.message:String(c)}`)}if(!i.ok)throw new H(`skill fetch answered HTTP ${i.status} for ${s}`);let a=new Uint8Array(await i.arrayBuffer());if(o.digest&&Qn(a)!==o.digest)throw new H(`digest mismatch for ${e}: index says ${o.digest}, served bytes hash to ${Qn(a)} - refusing to use them`);return{entry:o,bytes:a}}var Si=".claude/skills";function xi(e,t,n){let r=[],o="";for(let s of e.split(/\s+/))o&&`${o} ${s}`.length>t?(r.push(n+o),o=s):o=o?`${o} ${s}`:s;return o&&r.push(n+o),r}async function nr(e){try{if(!e.name){let r=await Tt();if(e.json)return process.stdout.write(`${JSON.stringify(r,null,2)}
|
|
46
|
+
`),E.OK;console.log("");for(let o of r){let s=o.digest?ge.default.dim(` ${o.digest.slice(0,19)}\u2026`):"";if(console.log(` ${ge.default.bold(o.name)}${s}`),o.description)for(let i of xi(o.description,76," "))console.log(ge.default.dim(i));console.log("")}return console.log(ge.default.dim(" Install one with: ax skill <name> --install")),console.log(""),E.OK}let{entry:t,bytes:n}=await tr(e.name);if(e.install){let r=(0,_t.join)(e.dir??Si,t.name);(0,qe.mkdirSync)(r,{recursive:!0});let o=(0,_t.join)(r,"SKILL.md");return(0,qe.writeFileSync)(o,n),console.log(`Installed ${t.name} to ${o}`),t.digest&&console.log(ge.default.dim(`verified ${t.digest}`)),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 H&&n.includes("unknown skill")?E.USAGE:E.API}}var $=class extends Error{constructor(t,n){super(t,n),this.name="CdpError"}},rr=1e4,or=5e3,Pt=class e{socket;nextId=1;pending=new Map;handlers=new Map;closed=!1;closeReason=null;constructor(t){this.socket=t,t.addEventListener("message",n=>{this.dispatch(String(n.data))}),t.addEventListener("close",()=>{this.fail("the browser closed the DevTools connection")}),t.addEventListener("error",()=>{this.fail("the DevTools connection errored")})}static async open(t){let n=new WebSocket(t);return await new Promise((r,o)=>{let s=setTimeout(()=>{o(new $(`timed out connecting to ${t}`))},or);n.addEventListener("open",()=>{clearTimeout(s),r()},{once:!0}),n.addEventListener("error",()=>{clearTimeout(s),o(new $(`could not connect to ${t}`))},{once:!0})}),new e(n)}dispatch(t){let n;try{n=JSON.parse(t)}catch{return}let r=n.id;if(typeof r=="number"){let a=this.pending.get(r);if(!a)return;this.pending.delete(r),clearTimeout(a.timer);let c=n.error;c?a.reject(new $(c.message??"CDP call failed")):a.resolve(n.result??{});return}let o=n.method;if(typeof o!="string")return;let s=typeof n.sessionId=="string"?n.sessionId:"",i=n.params??{};for(let a of this.handlers.get(`${s}\0${o}`)??[])try{a(i)}catch{}}fail(t){if(!this.closed){this.closed=!0,this.closeReason=t;for(let[,n]of this.pending)clearTimeout(n.timer),n.reject(new $(t));this.pending.clear()}}send(t,n={},r={}){if(this.closed)return Promise.reject(new $(this.closeReason??"the connection is closed"));let o=this.nextId++,s=r.timeoutMs??rr;return new Promise((i,a)=>{let c=setTimeout(()=>{this.pending.delete(o),a(new $(`${t} timed out after ${s}ms`))},s);this.pending.set(o,{resolve:i,reject:a,timer:c});let l={id:o,method:t,params:n};r.sessionId&&(l.sessionId=r.sessionId);try{this.socket.send(JSON.stringify(l))}catch(u){this.pending.delete(o),clearTimeout(c),a(new $(`could not send ${t}`,{cause:u}))}})}on(t,n,r){let o=`${t}\0${n}`,s=this.handlers.get(o)??new Set;return s.add(r),this.handlers.set(o,s),()=>{s.delete(r)}}close(){this.closed=!0;try{this.socket.close()}catch{}}};async function It(e,t=or){if(e.startsWith("ws://")||e.startsWith("wss://"))return{webSocketDebuggerUrl:e,product:""};let n=e.startsWith("http://")||e.startsWith("https://")?e.replace(/\/+$/,""):`http://${e.replace(/\/+$/,"")}`,r;try{r=await fetch(`${n}/json/version`,{signal:AbortSignal.timeout(t)})}catch(s){throw new $(`no debuggable Chrome answered at ${n}`,{cause:s})}if(!r.ok)throw new $(`${n}/json/version returned HTTP ${r.status}`);let o=await r.json().catch(()=>null);if(!o?.webSocketDebuggerUrl)throw new $(`${n}/json/version carried no webSocketDebuggerUrl`);return{webSocketDebuggerUrl:o.webSocketDebuggerUrl,product:o.Browser??""}}var Ye=class e{connection;product;constructor(t,n){this.connection=t,this.product=n}static async connect(t){let n=await Pt.open(t.webSocketDebuggerUrl),r=t.product;if(!r){let o=await n.send("Browser.getVersion").catch(()=>({}));r=typeof o.product=="string"?o.product:""}return new e(n,r.replace(/^(?:Headless)?Chrome\//i,""))}async newContext(t){let{browserContextId:n}=await this.connection.send("Target.createBrowserContext",{disposeOnDetach:!0}),{targetId:r}=await this.connection.send("Target.createTarget",{url:"about:blank",browserContextId:n}),{sessionId:o}=await this.connection.send("Target.attachToTarget",{targetId:r,flatten:!0}),s=new Ot(this.connection,o,n,t.entryUrl);return await s.prepare(t.initScripts??[],t.viewport),s}close(){this.connection.close()}},Ai=8,ki=1024*1024,Ei=new Set(["Image","Media","Font"]),Ot=class{connection;sessionId;browserContextId;entryHost;currentUrl="about:blank";viewport=null;domContentFired=!1;loadFired=!1;documentResponses=new Map;scripts=[];scriptsStarted=0;pendingScriptRequests=new Map;constructor(t,n,r,o){this.connection=t,this.sessionId=n,this.browserContextId=r,this.entryHost=Ct(o)}async prepare(t,n){await this.send("Page.enable"),await this.send("Runtime.enable"),await this.send("Network.enable"),await this.send("Fetch.enable",{patterns:[{urlPattern:"*"}]}),this.connection.on(this.sessionId,"Fetch.requestPaused",r=>{this.onRequestPaused(r)}),n&&(this.viewport=n,await this.send("Emulation.setDeviceMetricsOverride",{width:n.width,height:n.height,deviceScaleFactor:1,mobile:!1})),this.connection.on(this.sessionId,"Page.domContentEventFired",()=>{this.domContentFired=!0}),this.connection.on(this.sessionId,"Page.loadEventFired",()=>{this.loadFired=!0}),this.connection.on(this.sessionId,"Page.frameNavigated",r=>{let o=r.frame;!o||o.parentId||typeof o.url=="string"&&(this.currentUrl=o.url)}),this.connection.on(this.sessionId,"Network.responseReceived",r=>{this.onResponse(r)}),this.connection.on(this.sessionId,"Network.loadingFinished",r=>{this.onLoadingFinished(r)});for(let r of t)await this.send("Page.addScriptToEvaluateOnNewDocument",{source:r})}send(t,n={},r){return this.connection.send(t,n,{sessionId:this.sessionId,timeoutMs:r})}onRequestPaused(t){let n=t.requestId;if(typeof n!="string")return;(Ei.has(String(t.resourceType))?this.send("Fetch.failRequest",{requestId:n,errorReason:"BlockedByClient"}):this.send("Fetch.continueRequest",{requestId:n})).catch(()=>{})}onResponse(t){let n=t.type,r=t.requestId,o=t.response;if(typeof r!="string"||!o)return;if(n==="Document"){let a=typeof t.frameId=="string"?t.frameId:"";this.documentResponses.set(a,{status:typeof o.status=="number"?o.status:0,headers:Ri(o.headers??{})});return}if(n!=="Script"||this.scriptsStarted>=Ai)return;let s=typeof o.url=="string"?o.url:"",i=Ct(s);i&&(i!==this.entryHost&&i!==Ct(this.currentUrl)||(this.scriptsStarted++,this.pendingScriptRequests.set(r,s)))}onLoadingFinished(t){let n=t.requestId;if(typeof n!="string")return;let r=this.pendingScriptRequests.get(n);r!==void 0&&(this.pendingScriptRequests.delete(n),this.send("Network.getResponseBody",{requestId:n}).then(o=>{let s=typeof o.body=="string"?o.body:"",i=o.base64Encoded===!0?Buffer.from(s,"base64").toString("utf8"):s;this.scripts.push({url:r,body:i.slice(0,ki)})}).catch(()=>{}))}async goto(t,n){this.domContentFired=!1,this.loadFired=!1;let r=await this.send("Page.navigate",{url:t},n),o=r.errorText;if(typeof o=="string"&&o.length>0)throw new $(`navigating to ${t} failed: ${o}`);let s=typeof r.frameId=="string"?r.frameId:"";return await this.waitFor(()=>this.domContentFired,n,`${t} never reached DOMContentLoaded`),this.currentUrl=await this.readLocation(t),this.documentResponses.get(s)??this.documentResponses.get("")??null}async waitForLoad(t){await this.waitFor(()=>this.loadFired,t,"load").catch(()=>{})}async waitFor(t,n,r){let o=Date.now()+n;for(;!t();){if(Date.now()>=o)throw new $(`timed out waiting for ${r}`);await new Promise(s=>setTimeout(s,25))}}async readLocation(t){let n=await this.evaluate("location.href",2e3).catch(()=>null);return typeof n=="string"&&n.length>0?n:t}async evaluate(t,n=rr){let r=await this.send("Runtime.evaluate",{expression:t,awaitPromise:!0,returnByValue:!0},n),o=r.exceptionDetails;if(o)throw new $(o.exception?.description??o.text??"evaluation threw");return r.result?.value}async content(){return await this.evaluate("document.documentElement ? document.documentElement.outerHTML : ''").catch(()=>"")??""}async inlineScripts(){return await this.evaluate('Array.from(document.querySelectorAll("script:not([src])")).map(function (s) { return s.textContent || ""; }).join("\\n")').catch(()=>"")??""}url(){return this.currentUrl}collectedScripts(){return this.scripts.slice()}viewportSize(){return this.viewport}async screenshot(t,n){try{let o=(await this.send("Page.captureScreenshot",{format:"jpeg",quality:t,captureBeyondViewport:!1},n)).data;return typeof o!="string"||o.length===0?null:Buffer.from(o,"base64")}catch{return null}}async close(){await this.connection.send("Target.disposeBrowserContext",{browserContextId:this.browserContextId}).catch(()=>{})}};function Ri(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.toLowerCase(),s=r.split(`
|
|
47
|
+
`).map(i=>i.trim()).filter(i=>i.length>0).join(", ");t[o]=t[o]===void 0?s:`${t[o]}, ${s}`}return t}function Ct(e){try{return new URL(e).host}catch{return""}}var $i=new Set([2,3]),Ti=8192,_i=864e10;function Ci(e){if(typeof e!="string")return null;let t=e.trim();if(t.length===0||t.length>Ti)return null;let n;try{n=Buffer.from(t,"base64")}catch{return null}if(n.length<=69||!$i.has(n[0])||n.readUInt32BE(65)!==n.length-69)return null;let o;try{o=JSON.parse(n.subarray(69).toString("utf8"))}catch{return null}if(!o||typeof o!="object")return null;let s=o,i=s.origin,a=s.feature,c=s.expiry;return typeof i!="string"||typeof a!="string"||typeof c!="number"||!Number.isFinite(c)||c<0||c>_i?null:{origin:i,feature:a,expiry:c,isSubdomain:s.isSubdomain===!0,isThirdParty:s.isThirdParty===!0}}function Pi(e){let t=e.toLowerCase().replace(/[^a-z]/g,"");return t==="webmcp"||t.includes("modelcontext")}function Oi(e,t,n){let r,o;try{r=new URL(e),o=new URL(t)}catch{return!1}if(r.protocol!==o.protocol||r.port!==o.port)return!1;let s=r.hostname.toLowerCase(),i=o.hostname.toLowerCase();return s===i?!0:n&&i.endsWith(`.${s}`)}function sr(e,t,n){let r=e.map(s=>s.trim()).filter(s=>s.length>0);if(r.length===0)return null;let o=null;for(let s of r){let i=Ci(s);if(!i)continue;let a=Pi(i.feature),c=i.expiry*1e3>n.getTime(),l=Oi(i.origin,t,i.isSubdomain),u=a&&c&&l,d=u?3:a?2:1;(!o||d>o.rank)&&(o={parsed:i,eligible:u,rank:d})}return o?{present:!0,payloadEligible:o.eligible,origin:o.parsed.origin,feature:o.parsed.feature,expiresAt:new Date(o.parsed.expiry*1e3).toISOString()}:{present:!0,payloadEligible:!1}}function ir(e){return e?e.split(",").map(t=>t.trim()).filter(t=>t.length>0):[]}var Mt="capture-incomplete:";function Ii(e){return e.imperative!==null||e.polyfillPackages.length>0}function ar(e){return e.blocked?"blocked":e.loadError?"load-error":e.nativeToolCount!==null&&e.nativeToolCount>0?"active":e.toolCount>0?"testing-only":e.nativeToolCount===0?"api-empty":e.nativeApi||e.shimTakenOver||Ii(e.staticSignals)?"declared-inactive":"absent"}function cr(e,t){switch(e){case"blocked":return"waf-blocked";case"load-error":return"unreachable";case"active":case"testing-only":{let n=t.filter(r=>r.via==="imperative");return n.length>0&&n.every(r=>!r.hasExecute)?"stub-only":"ok"}case"api-empty":case"declared-inactive":case"absent":return"no-tools";default:return e}}var lr={"shared-experience":30,"task-completion":25,"tool-quality":25,trust:20},ur={"page-experience":{title:"Page experience",category:"shared-experience",weight:16,docSlug:"page-experience"},"human-parity":{title:"Human parity",category:"shared-experience",weight:8,docSlug:"human-parity"},"visible-effect":{title:"Visible effect",category:"shared-experience",weight:6,docSlug:"visible-effect"},"tool-selection":{title:"Tool selection",category:"task-completion",weight:12,docSlug:"tool-selection"},"coverage-vs-site-type":{title:"Coverage vs. site type",category:"task-completion",weight:7,docSlug:"coverage-vs-site-type"},"invoke-success-rate":{title:"Invoke success rate",category:"task-completion",weight:6,docSlug:"invoke-success-rate"},"schema-validity":{title:"Schema validity",category:"tool-quality",weight:4,docSlug:"schema-validity"},"schema-quality":{title:"Schema quality",category:"tool-quality",weight:4,docSlug:"schema-quality"},"description-quality":{title:"Description quality",category:"tool-quality",weight:5,docSlug:"description-quality"},"stub-detection":{title:"Stub detection",category:"tool-quality",weight:4,docSlug:"stub-detection"},"canonical-entry-point":{title:"Canonical entry point",category:"tool-quality",weight:3,docSlug:"canonical-entry-point"},"naming-quality":{title:"Naming quality",category:"tool-quality",weight:2,docSlug:"naming-quality"},"registration-errors":{title:"Registration errors",category:"tool-quality",weight:2,docSlug:"registration-errors"},"registration-timing":{title:"Registration timing",category:"tool-quality",weight:1,docSlug:"registration-timing"},"annotations-present":{title:"Annotations present",category:"trust",weight:5,docSlug:"annotations-present"},"annotation-mismatch":{title:"Annotation mismatch",category:"trust",weight:5,docSlug:"annotation-mismatch"},"injection-surface":{title:"Injection surface",category:"trust",weight:3,docSlug:"injection-surface"},"untrusted-content-hint":{title:"Untrusted content hint",category:"trust",weight:3,docSlug:"untrusted-content-hint"},"hint-vs-observed":{title:"Hint vs. observed",category:"trust",weight:4,docSlug:"hint-vs-observed"}},ie="3";function Mi(e,t,n){return!!(t["cf-mitigated"]==="challenge"||e===403&&n.includes("cf-browser-verification")||e===503&&n.includes("challenge-platform"))}function dr(e,t,n){return!!(Mi(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 Ni=100,mr=4096,Li=32768,ji=50,Ui=200,pr="__oraWebmcpCapture",hr=`(function () {
|
|
48
48
|
"use strict";
|
|
49
49
|
try {
|
|
50
50
|
var W = typeof globalThis !== "undefined" ? globalThis : window;
|
|
51
|
-
if (W.${
|
|
51
|
+
if (W.${pr}) return;
|
|
52
52
|
|
|
53
53
|
var SHIM_VERSION = ${JSON.stringify(ie)};
|
|
54
|
-
var MAX_TOOLS = ${
|
|
55
|
-
var MAX_DESCRIPTION_CHARS = ${
|
|
56
|
-
var MAX_SCHEMA_CHARS = ${
|
|
57
|
-
var MAX_ERRORS = ${
|
|
54
|
+
var MAX_TOOLS = ${Ni};
|
|
55
|
+
var MAX_DESCRIPTION_CHARS = ${mr};
|
|
56
|
+
var MAX_SCHEMA_CHARS = ${Li};
|
|
57
|
+
var MAX_ERRORS = ${ji};
|
|
58
58
|
// Internal bound only: a page looping on addEventListener must not grow
|
|
59
59
|
// the shim's retained set without limit.
|
|
60
60
|
var MAX_LISTENERS = 50;
|
|
@@ -84,6 +84,20 @@ ${C.map(N=>` ${N.id.padEnd(12)} ${kt(N)}`).join(`
|
|
|
84
84
|
} catch (e) {
|
|
85
85
|
// A hostile performance getter cannot be pinned; the Date fallback holds.
|
|
86
86
|
}
|
|
87
|
+
// The serialized origin getTools() reports on every RegisteredTool.
|
|
88
|
+
// Pinned at install like the natives: location is unforgeable in a
|
|
89
|
+
// browser and this script runs before any page script, so the value read
|
|
90
|
+
// here is the document's real origin. Empty on any failure (the vm test
|
|
91
|
+
// sandbox has no location; an exotic environment may throw) - a degraded
|
|
92
|
+
// origin must never break the page.
|
|
93
|
+
var pinnedOrigin = "";
|
|
94
|
+
try {
|
|
95
|
+
if (W.location && typeof W.location.origin === "string") {
|
|
96
|
+
pinnedOrigin = W.location.origin;
|
|
97
|
+
}
|
|
98
|
+
} catch (e) {
|
|
99
|
+
// Expected: an exotic location getter. The "" default stands.
|
|
100
|
+
}
|
|
87
101
|
|
|
88
102
|
var entries = [];
|
|
89
103
|
var byKey = nativeObjectCreate(null);
|
|
@@ -362,6 +376,88 @@ ${C.map(N=>` ${N.id.padEnd(12)} ${kt(N)}`).join(`
|
|
|
362
376
|
return nativePromise ? nativePromise.resolve() : undefined;
|
|
363
377
|
}
|
|
364
378
|
|
|
379
|
+
// A stored inputSchema/annotations value as getTools() may hand it to
|
|
380
|
+
// page code. Absence is undefined (the draft: "undefined if none was
|
|
381
|
+
// registered"), and so are this shim's own {__truncated} and
|
|
382
|
+
// {__unserializable} markers - they are instrument internals, and handing
|
|
383
|
+
// a page an object it never wrote would leak how the capture works. A
|
|
384
|
+
// real stored value is re-copied on EVERY call: snapshot() shares the
|
|
385
|
+
// stored references, so returning them here would let the page mutate the
|
|
386
|
+
// registry record and rewrite what a later snapshot reports.
|
|
387
|
+
function projectStoredValue(value) {
|
|
388
|
+
if (value === null || value === undefined) return undefined;
|
|
389
|
+
if (value.__truncated === true || value.__unserializable === true) {
|
|
390
|
+
return undefined;
|
|
391
|
+
}
|
|
392
|
+
return safeCopy(value, MAX_SCHEMA_CHARS);
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
// The draft's RegisteredTool list (section 4.5): the CURRENT tool map,
|
|
396
|
+
// sorted ascending by name in code-unit order. Unregistered records are
|
|
397
|
+
// audit evidence, not live tools, so they are filtered; a name live under
|
|
398
|
+
// both sources is returned twice rather than deduped (the real map could
|
|
399
|
+
// never hold both, but picking a winner here would invent one). title
|
|
400
|
+
// is "" because the shim does not record it yet (Stage 2, with the
|
|
401
|
+
// title-present check) and "" is what Chrome currently reports for a
|
|
402
|
+
// missing title (spec issue 224 is unresolved).
|
|
403
|
+
function getToolsList() {
|
|
404
|
+
var list = [];
|
|
405
|
+
for (var i = 0; i < entries.length; i++) {
|
|
406
|
+
var entry = entries[i];
|
|
407
|
+
if (entry.unregistered) continue;
|
|
408
|
+
list.push({
|
|
409
|
+
name: entry.name,
|
|
410
|
+
title: "",
|
|
411
|
+
description: entry.description,
|
|
412
|
+
inputSchema: projectStoredValue(entry.inputSchema),
|
|
413
|
+
annotations: projectStoredValue(entry.annotations),
|
|
414
|
+
window: W,
|
|
415
|
+
origin: pinnedOrigin
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
// String < / > IS code-unit comparison, which is the draft's order.
|
|
419
|
+
// sort is deliberately not pinned: pinning protects capture integrity,
|
|
420
|
+
// and a page sabotaging its own getTools() result harms only itself -
|
|
421
|
+
// the same reasoning as the unpinned push/indexOf/splice above.
|
|
422
|
+
list.sort(function (a, b) {
|
|
423
|
+
return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
|
|
424
|
+
});
|
|
425
|
+
return list;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
// The read half of the draft's API, and the reason it exists here is a
|
|
429
|
+
// bug this shim caused: a page's own polyfill correctly stands down when
|
|
430
|
+
// document.modelContext already exists (this shim IS that object), and a
|
|
431
|
+
// page that then awaits getTools() before registering threw on the
|
|
432
|
+
// missing method, killing its whole registration path while the audit
|
|
433
|
+
// blamed the site. Observed on the Le Petit Bistro demo in Google's
|
|
434
|
+
// webmcp-tools repo: its DEFAULT surface is the declarative form, and its
|
|
435
|
+
// imperative path (behind the imperative query param) awaits
|
|
436
|
+
// document.modelContext.getTools() before registerTool - the shape that
|
|
437
|
+
// died under capture.
|
|
438
|
+
//
|
|
439
|
+
// Divergences from the draft, each deliberate: options.fromOrigins is
|
|
440
|
+
// accepted and ignored (this registry only ever holds same-document
|
|
441
|
+
// tools, so the cross-origin filter has nothing to do), and none of the
|
|
442
|
+
// draft's error conditions (InvalidStateError, NotAllowedError,
|
|
443
|
+
// SecurityError) are raised - the shim cannot evaluate permissions
|
|
444
|
+
// policy, and its prime directive is to never break the page, so this
|
|
445
|
+
// function must never throw.
|
|
446
|
+
function getTools() {
|
|
447
|
+
var list;
|
|
448
|
+
try {
|
|
449
|
+
list = getToolsList();
|
|
450
|
+
} catch (e) {
|
|
451
|
+
list = [];
|
|
452
|
+
}
|
|
453
|
+
// The provideContext fallback convention, not registerTool's: that
|
|
454
|
+
// bare-object shape exists to carry .unregister, and getTools carries
|
|
455
|
+
// nothing. A page that awaits necessarily runs where Promise existed
|
|
456
|
+
// at install, so the sync-array arm only ever serves callers that
|
|
457
|
+
// treat the return value as data.
|
|
458
|
+
return nativePromise ? nativePromise.resolve(list) : list;
|
|
459
|
+
}
|
|
460
|
+
|
|
365
461
|
function addEventListener(type, listener) {
|
|
366
462
|
if (typeof listener !== "function") return;
|
|
367
463
|
var key = safeText(type, "");
|
|
@@ -404,6 +500,14 @@ ${C.map(N=>` ${N.id.padEnd(12)} ${kt(N)}`).join(`
|
|
|
404
500
|
// Two distinct delegate objects over one registry, so we can tell which
|
|
405
501
|
// global the page reached for.
|
|
406
502
|
function createDelegate(entryPoint) {
|
|
503
|
+
// executeTool is deliberately ABSENT, not stubbed: the live tool
|
|
504
|
+
// objects and their execute handlers are structurally dropped (the
|
|
505
|
+
// audit's no-invoke property), so any stub would be a permanent
|
|
506
|
+
// rejector - and a page feature-detecting executeTool would then build
|
|
507
|
+
// its agent path on infrastructure that always fails, which is worse
|
|
508
|
+
// than honest absence. Stage 2's invoke work owns the real thing.
|
|
509
|
+
// Stage 2 also: count getTools calls as an in-page-agent signal (needs
|
|
510
|
+
// snapshot-shape, capture-server and consumer updates).
|
|
407
511
|
return {
|
|
408
512
|
registerTool: function (tool, options) {
|
|
409
513
|
return registerTool(tool, options, entryPoint);
|
|
@@ -411,6 +515,7 @@ ${C.map(N=>` ${N.id.padEnd(12)} ${kt(N)}`).join(`
|
|
|
411
515
|
provideContext: function (context) {
|
|
412
516
|
return provideContext(context, entryPoint);
|
|
413
517
|
},
|
|
518
|
+
getTools: getTools,
|
|
414
519
|
addEventListener: addEventListener,
|
|
415
520
|
removeEventListener: removeEventListener,
|
|
416
521
|
dispatchEvent: dispatchEvent
|
|
@@ -508,7 +613,7 @@ ${C.map(N=>` ${N.id.padEnd(12)} ${kt(N)}`).join(`
|
|
|
508
613
|
// Non-writable and non-configurable: the capture payload is the audit's
|
|
509
614
|
// evidence, so a page must not be able to replace snapshot() and report
|
|
510
615
|
// whatever tools it wishes it had.
|
|
511
|
-
nativeDefineProperty(W, ${JSON.stringify(
|
|
616
|
+
nativeDefineProperty(W, ${JSON.stringify(pr)}, {
|
|
512
617
|
value: {
|
|
513
618
|
shimVersion: SHIM_VERSION,
|
|
514
619
|
installedAt: now(),
|
|
@@ -525,26 +630,27 @@ ${C.map(N=>` ${N.id.padEnd(12)} ${kt(N)}`).join(`
|
|
|
525
630
|
// Nothing left to report to; never let the shim break the page.
|
|
526
631
|
}
|
|
527
632
|
}
|
|
528
|
-
})();`,
|
|
529
|
-
var MAX_FORMS = ${
|
|
530
|
-
var MAX_DESCRIPTION_CHARS = ${
|
|
633
|
+
})();`,gr=`(function () {
|
|
634
|
+
var MAX_FORMS = ${Ui};
|
|
635
|
+
var MAX_DESCRIPTION_CHARS = ${mr};
|
|
531
636
|
var forms = [];
|
|
532
|
-
var nodes = document.querySelectorAll("form[toolname]
|
|
637
|
+
var nodes = document.querySelectorAll("form[toolname]");
|
|
533
638
|
for (var i = 0; i < nodes.length && forms.length < MAX_FORMS; i++) {
|
|
534
639
|
var node = nodes[i];
|
|
535
|
-
var isForm = node.tagName === "FORM";
|
|
536
640
|
var description = node.getAttribute("tooldescription") || "";
|
|
641
|
+
var toolName = node.getAttribute("toolname") || "";
|
|
642
|
+
if (!toolName.trim()) continue;
|
|
537
643
|
forms.push({
|
|
538
|
-
toolName:
|
|
644
|
+
toolName: toolName,
|
|
539
645
|
toolDescription: description.slice(0, MAX_DESCRIPTION_CHARS),
|
|
540
|
-
action:
|
|
541
|
-
method:
|
|
646
|
+
action: node.getAttribute("action") || "",
|
|
647
|
+
method: (node.getAttribute("method") || "get").toLowerCase(),
|
|
542
648
|
fieldCount: node.querySelectorAll("input, select, textarea").length
|
|
543
649
|
});
|
|
544
650
|
}
|
|
545
651
|
return { forms: forms };
|
|
546
|
-
})()`;var
|
|
547
|
-
`)),s=new Set;for(let a of r){let c=a.toLowerCase();for(let l of
|
|
652
|
+
})()`;var yr=["@mcp-b/global","@mcp-b/react-webmcp","usewebmcp"];function Wi(e){let t=e.toLowerCase(),n=/document\.modelcontext/.test(t),r=/navigator\.modelcontext/.test(t),o=/modelcontext\??\.registertool/.test(t)||(n||r)&&/\.registertool\s*\(/.test(t),s=/modelcontext\??\.providecontext/.test(t),i=yr.find(c=>t.includes(c));return!o&&!s&&!i?null:{marker:o?n?"document.modelContext.registerTool":r?"navigator.modelContext.registerTool":"modelContext.registerTool":s?"modelContext.provideContext":`${i} package`,deprecatedAliasOnly:o&&r&&!n,removedApiOnly:!o&&s}}var Di=["webmcp","web model context protocol"];function fr(e){let t=e.toLowerCase();return Di.some(n=>t.includes(n))}function wr(e,t,n){let r=[t,...n.map(a=>a.body)],o=Wi(r.join(`
|
|
653
|
+
`)),s=new Set;for(let a of r){let c=a.toLowerCase();for(let l of yr)c.includes(l)&&s.add(l)}let i=fr(e)||r.some(fr);return{imperative:o,polyfillPackages:[...s],keywordMention:i}}var Sr=15e3,Fi=3e4,Bi=2e3,xr=250,Ar={fast:5e3,deep:1e4},Ji={fast:12e3,deep:2e4},Hi=2*1024*1024,kr=512,Gi=512,Ki=60,qi=15e5,Er={width:1280,height:720},br={imperative:null,polyfillPackages:[],keywordMention:!1},Yi=`(function () {
|
|
548
654
|
var tokens = [];
|
|
549
655
|
try {
|
|
550
656
|
var metas = document.querySelectorAll('meta[http-equiv="origin-trial" i]');
|
|
@@ -557,19 +663,28 @@ ${C.map(N=>` ${N.id.padEnd(12)} ${kt(N)}`).join(`
|
|
|
557
663
|
}
|
|
558
664
|
var nativeApi = false;
|
|
559
665
|
try {
|
|
560
|
-
nativeApi = (
|
|
666
|
+
nativeApi = Boolean(document.modelContext || navigator.modelContext);
|
|
561
667
|
} catch (e) {
|
|
562
668
|
// A hostile getter on either global; absence is the honest answer.
|
|
563
669
|
}
|
|
564
670
|
return { nativeApi: nativeApi, metaTokens: tokens };
|
|
565
|
-
})()`,
|
|
671
|
+
})()`,Vi=`(async function () {
|
|
672
|
+
try {
|
|
673
|
+
var modelContext = document.modelContext || navigator.modelContext;
|
|
674
|
+
if (!modelContext || typeof modelContext.getTools !== "function") return null;
|
|
675
|
+
var tools = await modelContext.getTools();
|
|
676
|
+
return tools && typeof tools.length === "number" ? tools.length : null;
|
|
677
|
+
} catch (e) {
|
|
678
|
+
return null;
|
|
679
|
+
}
|
|
680
|
+
})()`,Rr=`(function () {
|
|
566
681
|
try {
|
|
567
682
|
var g = window.__oraWebmcpCapture;
|
|
568
683
|
return g ? g.snapshot() : null;
|
|
569
684
|
} catch (e) {
|
|
570
685
|
return null;
|
|
571
686
|
}
|
|
572
|
-
})()`,
|
|
687
|
+
})()`,Xi=`(function () {
|
|
573
688
|
try {
|
|
574
689
|
var g = window.__oraWebmcpCapture;
|
|
575
690
|
if (!g) return "none";
|
|
@@ -579,26 +694,24 @@ ${C.map(N=>` ${N.id.padEnd(12)} ${kt(N)}`).join(`
|
|
|
579
694
|
} catch (e) {
|
|
580
695
|
return "error";
|
|
581
696
|
}
|
|
582
|
-
})()`;function
|
|
583
|
-
`)[0].slice(0,300)}function Xe(e,t){return Math.max(250,Math.min(t,e-Date.now()))}function
|
|
584
|
-
`)}}try{let t=await
|
|
585
|
-
`):null}function
|
|
586
|
-
`)[0]?.trim(),s=Number(o);if(Number.isInteger(s)&&s>0)return s}catch{}await new Promise(o=>setTimeout(o,100))}throw new
|
|
587
|
-
`)}var
|
|
697
|
+
})()`;function $r(e,t){return e.filter(n=>!n.unregistered).map(n=>({name:n.name.slice(0,kr),description:n.description,via:"imperative",entryPoint:n.source==="provideContext"?"provideContext":n.entryPoint,pageUrl:t,inputSchema:n.inputSchema,annotations:Qi(n.annotations),hasExecute:n.hasExecute,registrationMs:n.registrationMs}))}function zi(e,t){return e.map(n=>({name:n.toolName.slice(0,kr),description:n.toolDescription,via:"declarative",entryPoint:"form",pageUrl:t,inputSchema:null,annotations:{},hasExecute:!0,registrationMs:null}))}function Qi(e){if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e,n={};for(let r of["readOnlyHint","destructiveHint","idempotentHint","openWorldHint","untrustedContentHint"])typeof t[r]=="boolean"&&(n[r]=t[r]);return typeof t.title=="string"&&(n.title=t.title.slice(0,Gi)),n}function Zi(e){if(!e)return[];let t=[...e.registrationErrors];return e.takenOver.length>0&&t.push(`${Mt} the page replaced modelContext on ${e.takenOver.join(", ")}, so imperative tools may be under-reported`),e.extraToolCount>0&&t.push(`${Mt} the capture's tool cap was reached and ${e.extraToolCount} further registration attempts were not stored`),t}function ea(e){if(!e)return null;for(let t of e.split(",")){let n=/^\s*([a-z0-9-]+)\s*=\s*(.*)$/i.exec(t);if(!n||n[1].toLowerCase()!=="tools")continue;let r=n[2].trim().replace(/^\(|\)$/g,"").trim();return r==="*"?!0:r===""||r.toLowerCase()==="self"?!1:r.split(/\s+/).some(o=>o.toLowerCase()!=="self"&&o.length>0)}return null}async function ta(e,t,n,r,o){let s=Date.now(),i={finalUrl:t,navMs:0,blocked:!1,nativeApi:!1,nativeToolCount:null,originTrialTokens:[],permissionsPolicy:null,html:"",inlineJs:"",scripts:[],screenshot:null,loadError:null},a=null;try{a=await e.newContext({entryUrl:t,viewport:Er});let c;try{c=await a.goto(t,Xe(r,Sr))}catch(x){return{...i,navMs:Date.now()-s,loadError:Ve(x)}}let l=Date.now()-s;await a.waitForLoad(Xe(r,5e3));let u=c?.headers??{},d=c?.status??0,m=(await a.content()).slice(0,Hi),g=await a.inlineScripts(),f=await a.evaluate(Yi).catch(()=>null)??{},h=f.nativeApi===!0,p=h?await sa(a,n,r):null,y=o?await ca(a,r):null;return{finalUrl:a.url(),navMs:l,blocked:dr(d,u,m),nativeApi:h,nativeToolCount:p,originTrialTokens:[...ir(u["origin-trial"]),...Array.isArray(f.metaTokens)?f.metaTokens:[]],permissionsPolicy:u["permissions-policy"]??null,html:m,inlineJs:g,scripts:a.collectedScripts(),screenshot:y,loadError:null}}catch(c){return{...i,navMs:Date.now()-s,loadError:Ve(c)}}finally{await a?.close()}}async function na(e,t,n,r,o){let s=null;try{s=await e.newContext({initScripts:[hr],entryUrl:t,viewport:Er});try{await s.goto(t,Xe(r,Sr))}catch(l){return{snapshot:null,declarative:null,quietMs:0,loadError:Ve(l)}}let i=await ra(s,n,r,o),a=await s.evaluate(Rr).catch(()=>null),c=await s.evaluate(gr).catch(()=>null);return{snapshot:a,declarative:c,quietMs:i,loadError:null}}catch(i){return{snapshot:null,declarative:null,quietMs:0,loadError:Ve(i)}}finally{await s?.close()}}async function ra(e,t,n,r){let o=Date.now(),s=Math.min(Ji[t],Math.max(0,n-o)),i=Math.min(Ar[t],s),a=null,c=o,l=!1;for(;Date.now()-o<s;){let u=await e.evaluate(Xi).catch(()=>null);typeof u=="string"&&/^[1-9]\d*:/.test(u)&&(l=!0),u!==a&&(a=typeof u=="string"?u:null,c=Date.now(),r&&await ia(e,r));let d=Date.now();if(oa({elapsedMs:d-o,quietMs:d-c,hasRegistered:l,initialWaitMs:i,maxWaitMs:s})||(await _r(Math.min(xr,Math.max(0,n-Date.now()))),Date.now()>=n))break}return Date.now()-o}function oa(e){return e.elapsedMs>=e.maxWaitMs?!0:e.hasRegistered?e.quietMs>=Bi:e.elapsedMs>=e.initialWaitMs}async function sa(e,t,n){let r=Date.now(),o=Math.min(Ar[t],Math.max(0,n-r)),s=null;for(;Date.now()-r<o;){let i=await e.evaluate(Vi).catch(()=>null);if(typeof i=="number"&&Number.isSafeInteger(i)&&i>=0&&(s=i,i>0))return i;if(await _r(Math.min(xr,Math.max(0,n-Date.now()))),Date.now()>=n)break}return s}async function ia(e,t){let n=await e.evaluate(Rr).catch(()=>null);n&&t($r(n.tools,e.url()))}async function aa(e,t,n,r,o){let s=Date.now(),i=s+Fi,a=await ta(e,t,n,i,r),l=a.loadError!==null||a.blocked?{snapshot:null,declarative:null,quietMs:0,loadError:null}:await na(e,t,n,i,o),u=a.loadError??l.loadError,d=l.snapshot,m=(l.declarative?.forms??[]).filter($e=>$e.toolName.trim()!==""),g=a.finalUrl||t,f=d?$r(d.tools,g):[],h=zi(m,g),p=[...f,...h],y=la(a.html,a.inlineJs,a.scripts),x=sr(a.originTrialTokens,vr(g)??vr(t)??"",new Date),C={loadError:u,blocked:a.blocked,nativeApi:a.nativeApi,nativeToolCount:a.nativeToolCount,declarativeToolCount:h.length,toolCount:p.length,shimTakenOver:(d?.takenOver.length??0)>0,staticSignals:y},Re=ar(C);return{page:{url:t,finalUrl:g,verdict:Re,status:cr(Re,p),tools:p,declarativeFormCount:h.length,consumer:{nativeApi:a.nativeApi,nativeToolCount:a.nativeToolCount,originTrial:x,permissionsPolicy:a.permissionsPolicy,iframeAllow:ea(a.permissionsPolicy)},staticSignals:y,apiSurface:{toolchangeEvents:d?.toolchangeEvents??0,provideContextCalls:d?.provideContextCalls??0,registrationErrors:Zi(d)},timing:{navMs:a.navMs,quietMs:l.quietMs,totalMs:Date.now()-s},error:u},screenshot:a.blocked?null:a.screenshot}}async function Tr(e){let{url:t,endpoint:n,mode:r="fast",screenshot:o=!0,onTools:s}=e,i=Date.now(),a=new Date().toISOString(),c=await Ye.connect(n);try{let l=await aa(c,t,r,o,s);return{url:t,pages:[l.page],chromeVersion:c.product,shimVersion:ie,capturedAt:a,durationMs:Date.now()-i,screenshot:l.screenshot}}finally{c.close()}}async function ca(e,t){let n=await e.screenshot(Ki,Xe(t,5e3));if(!n||n.byteLength===0||n.byteLength>qi)return null;let r=e.viewportSize();return{data:n.toString("base64"),mimeType:"image/jpeg",width:r?.width??0,height:r?.height??0}}function la(e,t,n){if(!e)return br;try{return wr(e,t,n)}catch{return br}}function vr(e){try{return new URL(e).origin}catch{return null}}function Ve(e){return(e instanceof Error?e.message:String(e)).split(`
|
|
698
|
+
`)[0].slice(0,300)}function Xe(e,t){return Math.max(250,Math.min(t,e-Date.now()))}function _r(e){return new Promise(t=>setTimeout(t,e))}var Pr=require("child_process"),G=require("fs"),Or=require("os"),Lt=require("path");var Ir=9222;async function Mr(e){if(e)try{return{ok:!0,endpoint:await It(e),close:async()=>{},launched:!1}}catch(t){let n=Nt(t);return{ok:!1,message:[`No debuggable Chrome answered at ${e}.`,...n.startsWith("no debuggable Chrome answered")?[]:[n],"",...ua(Ir)].join(`
|
|
699
|
+
`)}}try{let t=await ba();return{ok:!0,endpoint:t.endpoint,close:t.close,launched:!0}}catch(t){return{ok:!1,message:Nt(t)}}}function Nr(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(`
|
|
700
|
+
`):null}function ua(e){return["The audit drives a Chrome you already have; it never downloads one.","Start one with a debugging port and a scratch profile:","",` ${Lr(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 Lr(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 Nt(e){return e instanceof $||e instanceof Error?e.message:String(e)}function da(){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 pa(){for(let e of da())try{if((0,G.statSync)(e).isFile())return e}catch{}return null}var ma=["--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 ha(){return process.env.AX_WEBMCP_NO_SANDBOX==="1"}var Cr=2e4,ga=3e3,fa=4,ya=150;function wa(e,t){return e.exitCode!==null||e.signalCode!==null?Promise.resolve():new Promise(n=>{let r=()=>{clearTimeout(o),e.off("exit",r),n()},o=setTimeout(r,t);e.once("exit",r)})}async function ba(){let e=pa();if(!e)throw new $(xa());let t=(0,G.mkdtempSync)((0,Lt.join)((0,Or.tmpdir)(),"ax-webmcp-")),n=(0,Pr.spawn)(e,[...ma,...ha()?["--no-sandbox"]:[],"--remote-debugging-port=0",`--user-data-dir=${t}`,"about:blank"],{stdio:"ignore",detached:!0}),r=s=>{o().finally(()=>{process.removeListener("SIGINT",r),process.removeListener("SIGTERM",r),process.kill(process.pid,s)})},o=async()=>{process.removeListener("SIGINT",r),process.removeListener("SIGTERM",r);let s=n.pid;try{s!==void 0?process.kill(-s,"SIGTERM"):n.kill("SIGTERM")}catch{try{n.kill("SIGTERM")}catch{}}await wa(n,ga),await Sa(t)};process.once("SIGINT",r),process.once("SIGTERM",r);try{let s=await va(t,n);return{endpoint:await It(`127.0.0.1:${s}`),close:o}}catch(s){throw await o(),s instanceof $?s:new $(Nt(s))}}async function va(e,t){let n=(0,Lt.join)(e,"DevToolsActivePort"),r=Date.now()+Cr;for(;Date.now()<r;){if(t.exitCode!==null)throw new $(`Chrome exited with code ${t.exitCode} before it was ready.`);try{let o=(0,G.readFileSync)(n,"utf8").split(`
|
|
701
|
+
`)[0]?.trim(),s=Number(o);if(Number.isInteger(s)&&s>0)return s}catch{}await new Promise(o=>setTimeout(o,100))}throw new $(`Chrome did not publish a debugging port within ${Cr/1e3}s.`)}async function Sa(e){for(let t=0;t<fa;t++){try{if((0,G.rmSync)(e,{recursive:!0,force:!0}),!(0,G.existsSync)(e))return}catch{}await new Promise(n=>setTimeout(n,ya))}try{(0,G.rmSync)(e,{recursive:!0,force:!0})}catch{}}function xa(){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:","",` ${Lr(Ir)}`].join(`
|
|
702
|
+
`)}var Aa="https://ora.ai",ka=12e4,N=class extends Error{code;retryAfterMs;constructor(t,n={}){super(t),this.name="WebmcpIngestError",this.code=n.code??null,this.retryAfterMs=n.retryAfterMs??null}},jr=4*1024*1024,Ur=10,Wr=100,Dr=32768,Fr=4096,Br=512;function Jr(e){if(e.shimVersion!==ie)return`this build captures with shim version ${e.shimVersion}, which is not the version it was built against (${ie})`;if(e.pages.length>Ur)return`capture covers ${e.pages.length} pages; the limit is ${Ur}`;for(let t of e.pages){if(t.tools.length>Wr)return`${t.url} registered ${t.tools.length} tools; the limit is ${Wr} per page`;for(let n of t.tools){if(n.name.length>Br)return`tool name on ${t.url} is ${n.name.length} characters; the limit is ${Br}`;if(n.description.length>Fr)return`description for "${n.name}" is ${n.description.length} characters; the limit is ${Fr}`;for(let[r,o]of[["inputSchema",n.inputSchema],["annotations",n.annotations]]){let s=Ea(o);if(s===null)return`${r} for "${n.name}" could not be serialized (a cycle, or a value JSON cannot carry)`;if(s.length>Dr)return`${r} for "${n.name}" serializes to ${s.length} characters; the limit is ${Dr}`}}}return null}function Hr(e){let t=e.screenshot;if(!t)return{capture:e,droppedScreenshot:!1};let n=t.data.length>2*1024*1024,r=t.mimeType!=="image/jpeg";return!n&&!r?{capture:e,droppedScreenshot:!1}:{capture:{...e,screenshot:null},droppedScreenshot:!0}}function Ea(e){try{return JSON.stringify(e)??"null"}catch{return null}}async function Gr(e,t,n={}){let r=(n.baseUrl??process.env.ORA_API_URL??Aa).replace(/\/+$/,""),o=n.idleMs??ka,s=z(o),i=()=>new N(`ora scoring timed out \u2014 no progress for ${Math.round(o/1e3)}s`),a=JSON.stringify({url:e,capture:t});if(Buffer.byteLength(a,"utf8")>jr)throw s.disarm(),new N(`this capture serializes to ${Math.round(Buffer.byteLength(a,"utf8")/1024)} KB; the ingest limit is ${jr/1024/1024} MB`,{code:"BODY_TOO_LARGE"});let c;try{c=await fetch(`${r}/api/webmcp/audit/ingest`,{method:"POST",headers:{accept:"text/event-stream","content-type":"application/json",...n.apiKey?{authorization:`Bearer ${n.apiKey}`}:{}},body:a,signal:s.signal})}catch(l){throw s.disarm(),s.tripped()?i():new N(`ora ingest request failed: ${l instanceof Error?l.message:String(l)}`)}if(!c.ok||!c.body)throw s.disarm(),await Ra(c);return $a(c,s,n,i)}async function Ra(e){let t=await e.clone().json().catch(()=>null),n=t?.code??null;if(e.status===429){let r=Number(e.headers.get("retry-after")),o=t?.retry_after_ms??(Number.isFinite(r)&&r>0?r*1e3:null),s=o?` \u2014 retry in ${Math.ceil(o/1e3)}s`:"";return new N(`ora rate limit exceeded${s} (10/min and 20 per 24h per IP). An ora partner or scan API key lifts the daily limit: set ORA_PARTNER_API_KEY or pass --api-key.`,{code:n??"RATE_LIMITED",retryAfterMs:o})}return n==="SHIM_VERSION_MISMATCH"?new N(`This ax build captures with a shim ora no longer scores, so the audit was refused.
|
|
588
703
|
Upgrade with \`npm i -g ax@latest\` (or \`npx ax@latest webmcp-audit \u2026\`) and run it again.
|
|
589
704
|
|
|
590
|
-
ora said: ${t?.error??"shim version mismatch"}`,{code:n}):e.status===503?new
|
|
705
|
+
ora said: ${t?.error??"shim version mismatch"}`,{code:n}):e.status===503?new N(`ora cannot score right now: ${Ta(t?.error??"scoring is unavailable")} Nothing was spent against your rate limit; try again shortly.`,{code:n??"SCORING_UNAVAILABLE"}):new N(`ora ingest failed: ${t?.error??await ce(e)}`,{code:n})}async function $a(e,t,n,r){let o=new TextDecoder,s="",i;try{e:for await(let a of e.body){t.poke(),s=`${s}${o.decode(a,{stream:!0})}`.replace(/\r\n?/g,`
|
|
591
706
|
`);let c=s.indexOf(`
|
|
592
707
|
|
|
593
|
-
`);for(;c!==-1;){let l=
|
|
708
|
+
`);for(;c!==-1;){let l=_a(s.slice(0,c));if(s=s.slice(c+2),c=s.indexOf(`
|
|
594
709
|
|
|
595
|
-
`),!l)continue;let u;try{u=JSON.parse(l)}catch{continue}if(n.onEvent?.(u),u.type==="error")throw new
|
|
710
|
+
`),!l)continue;let u;try{u=JSON.parse(l)}catch{continue}if(n.onEvent?.(u),u.type==="error")throw new N(`ora audit failed: ${u.message}`,{code:u.status});if(u.type==="done"){i=u.audit;break e}}}}catch(a){throw t.tripped()?r():a instanceof N?a:new N(`ora ingest stream failed: ${a instanceof Error?a.message:String(a)}`)}finally{t.disarm()}if(!i)throw new N("ora ingest stream ended before the audit completed");return i}function Ta(e){let t=e.trim();return/[.!?]$/.test(t)?t:`${t}.`}function _a(e){let t=[];for(let n of e.split(`
|
|
596
711
|
`))n.startsWith("data:")&&t.push(n.slice(5).replace(/^ /,""));return t.join(`
|
|
597
|
-
`)}var w=
|
|
598
|
-
${u}`),n.value!==void 0){if(l.
|
|
599
|
-
|
|
600
|
-
`),B.BELOW_MIN_SCORE;if(l.score===null)return e.json||console.error(`
|
|
601
|
-
ora returned no score, so --min-score cannot be evaluated.`),B.API;if(l.score<n.value)return e.json||console.log(`
|
|
712
|
+
`)}var w=B(D(),1);var jt=12,Ca=["fail","warning","unmeasured","na","pass"],Ut={fail:["\u2716",w.default.red],warning:["\u25B2",w.default.yellow],unmeasured:["?",w.default.magenta],na:["\u2013",w.default.dim],pass:["\u2714",w.default.green]},Pa={fail:"Failing",warning:"Warnings",unmeasured:"Not measured",na:"Not applicable",pass:"Passing"},Oa=["shared-experience","task-completion","tool-quality","trust"],Ia={"shared-experience":"Shared experience","task-completion":"Task completion","tool-quality":"Tool quality",trust:"Trust"};function Kr(e,t={}){let n=Z(80,120);return["",...Ma(e,n),"",...La(e.availability,n),"",...ja(e,n),"",...Wa(e),"",...Fa(e.findings,n,t.showPassing===!0),...Ha(e.simulation,n),"",...Ga(e,n)]}function Ma(e,t){let n=[` ${w.default.bold(O(e.url))}`],r=`${e.toolCount} tool${e.toolCount===1?"":"s"}`,o=[Na(e.verdict),r,`Chrome ${O(e.chromeVersion)}`];return e.error&&o.push(w.default.red(O(e.error))),n.push(` ${w.default.dim(o.join(" \xB7 "))}`),n.map(s=>qr(s,t))}function Na(e){switch(e){case"active":return w.default.green("active");case"testing-only":case"declared-inactive":case"api-empty":return w.default.yellow(e);case"blocked":case"load-error":return w.default.red(e);default:return w.default.dim(e)}}function La(e,t){let[n,r]=e.status==="ready"?["agent-ready",w.default.green]:e.status==="not-ready"?["not agent-ready",w.default.red]:["availability unknown",w.default.yellow],o=[` ${r(w.default.bold(n))}`];for(let s of e.reasons)o.push(...M(O(s.detail),t-4).map(i=>` ${w.default.dim(i)}`));return o}function ja(e,t){let n=e.score===null?"\u2014":String(e.score),r=[` ${w.default.bold(`${n}/100`)} ${Ua(e)}`],o=e.availability.reasons.some(s=>s.id==="declarative-only");return e.grade===null&&e.score!==null&&!o&&r.push(...M(`The grade is withheld because only ${e.evidenceCoverage}% of the applicable check weight was actually measured. The score above still stands; the "Not measured" checks below are what is missing.`,t-4).map(s=>` ${w.default.dim(s)}`)),r}function Ua(e){return e.grade!==null?w.default.bold(w.default.green(`grade ${e.grade}`)):w.default.dim("grade withheld")}function Wa(e){let t=[` ${w.default.bold("Pillars")}`];for(let n of Oa){let r=e.categoryScores[n]??0,o=lr[n],s=e.applicableCategories.includes(n),i=s?Da(r):w.default.dim("\u2591".repeat(jt)),a=s?`weight ${o}`:`weight ${o} \xB7 nothing measured`;t.push(` ${Ia[n].padEnd(18)} ${i} ${String(r).padStart(3)}% ${w.default.dim(a)}`)}return t}function Da(e){let t=Math.round(Math.min(100,Math.max(0,e))/100*jt);return`${(e>=75?w.default.green:e>=40?w.default.yellow:w.default.red)("\u2588".repeat(t))}${w.default.dim("\u2591".repeat(jt-t))}`}function Fa(e,t,n){let r=[` ${w.default.bold("Checks")}`];for(let o of Ca){let s=e.filter(i=>i.status===o);if(s.length!==0){if(o==="pass"&&!n){r.push(` ${w.default.dim(`${s.length} passing (--show-passing to list)`)}`);continue}r.push("",` ${w.default.bold(Pa[o])} (${s.length})`);for(let i of s)r.push(...Ba(i,t))}}return e.length===0&&r.push(` ${w.default.dim("no checks reported")}`),r}function Ba(e,t){let[n,r]=Ut[e.status],o=Ja(e.checkId),i=[` ${r(n)} ${o}${e.toolName?w.default.dim(` ${O(e.toolName)}`):""}`];return e.details&&i.push(...M(O(e.details),t-10).map(a=>` ${w.default.dim(a)}`)),e.evidence&&i.push(...M(O(e.evidence),t-10).map(a=>` ${w.default.dim(a)}`)),i}function Ja(e){return ur[e]?.title??e}function Ha(e,t){if(!e)return[];let n=["",` ${w.default.bold("Tool selection")}`];if(e.skipped)return n.push(...M(O(e.skipReason??"The selection simulation did not run."),t-4).map(o=>` ${w.default.dim(o)}`)),n;let r=Math.round(e.accuracy*100);n.push(` ${r}% of ${e.steps.length} intent${e.steps.length===1?"":"s"} picked the right tool ${w.default.dim(O(e.model))}`);for(let o of e.steps){let[s,i]=o.ok?Ut.pass:Ut.fail,a=o.chosenTool?O(o.chosenTool):w.default.dim("nothing");n.push(` ${i(s)} ${qr(O(o.intent),t-30)} ${w.default.dim("\u2192")} ${a}`)}return n}function Ga(e,t){let n=e.source==="local"?"Captured by your own browser and scored without being stored \u2014 this result is not published or ranked anywhere. Run the audit at webmcp.ora.ai for a public one.":"";return n?M(n,t-4).map(r=>` ${w.default.dim(r)}`):[]}function qr(e,t){return e.length>t?`${e.slice(0,t-1)}\u2026`:e}var K={OK:0,BELOW_MIN_SCORE:1,USAGE:2,API:3};function Ka(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 qa(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 Yr(e){let t=Ka(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"),K.USAGE;let n=qa(e.minScore);if(n.error)return console.error(n.error),K.USAGE;let r=await Mr(e.chromeEndpoint);if(!r.ok)return console.error(r.message),K.USAGE;e.json||R.start(r.launched?`Starting Chrome and capturing ${t}`:`Capturing ${t}`);let o;try{o=await Tr({url:t,endpoint:r.endpoint,onTools:d=>{e.json||R.update(`Capturing ${t} \u2014 ${d.length} tools`)}})}catch(d){return R.stop(),console.error(`Capture failed: ${d instanceof Error?d.message:String(d)}`),K.API}finally{await r.close()}let s=o.pages[0];if(s?.error)return R.stop(),console.error(`Could not capture ${t}: ${s.error}`),console.error("Is the dev server running?"),K.USAGE;let i=Jr(o);if(i)return R.stop(),console.error(`ora would refuse this capture: ${i}`),K.USAGE;let{capture:a,droppedScreenshot:c}=Hr(o);e.json||R.update("Scoring with ora");let l;try{l=await Gr(t,a,{apiKey:e.apiKey||process.env.ORA_PARTNER_API_KEY||process.env.ORA_SCAN_API_KEY||void 0,onEvent:d=>{e.json||R.update(Ya(d))}})}catch(d){return R.stop(),d instanceof N?(console.error(d.message),K.API):(console.error(`Scoring failed: ${d instanceof Error?d.message:String(d)}`),K.API)}if(R.stop(),e.json)console.log(JSON.stringify(l,null,2));else for(let d of Kr(l,{showPassing:e.showPassing}))console.log(d);c&&console.error("Note: the screenshot exceeded ora's 2 MB limit and was not sent, so page-experience could not be graded.");let u=Nr(o);if(u&&console.error(`
|
|
713
|
+
${u}`),n.value!==void 0){if(l.score===null)return e.json||console.error(`
|
|
714
|
+
ora returned no score, so --min-score cannot be evaluated.`),K.API;if(l.score<n.value)return e.json||console.log(`
|
|
602
715
|
Score ${l.score} is below the required minimum ${n.value}
|
|
603
|
-
`),B.BELOW_MIN_SCORE}return B.OK}function Ba(e){switch(e.type){case"phase":return`Scoring with ora \u2014 ${e.phase}`;case"tool-discovered":return`Scoring with ora \u2014 found ${O(e.tool.name)}`;case"finding":return`Scoring with ora \u2014 ${e.finding.checkId}`;case"simulation-step":return`Scoring with ora \u2014 simulating "${O(e.step.intent)}"`;default:return"Scoring with ora"}}function Gr(){if(typeof process.loadEnvFile!="function")return!1;try{return process.loadEnvFile(),!0}catch{return!1}}var V="ax",Ja={meta:{name:"audit",description:"Score a site's agent readiness (exit codes: 0 ok, 1 below --min-score, 2 usage, 3 API error)"},args:{url:{type:"positional",description:"URL or domain to audit (e.g. https://docs.example.com)",required:!0},json:{type:"boolean",description:"Print the raw ora audit payload as JSON",default:!1},"min-score":{type:"string",description:"Exit 1 when the score is below this threshold (0-100); the CI gate"},"max-age":{type:"string",description:"Accept a cached result up to this many seconds old (server default 6h)"},force:{type:"boolean",description:"Bypass the cache and rescan (spends the stricter 6/day force budget)",default:!1},tunnel:{type:"string",description:"Open ora's own tunnel to a local target (value: ora); needs ORA_API_KEY with the tunnels:write + tunnels:connect scopes. Also read from ORA_TUNNEL. The result is stored as ephemeral"},"tunnel-cmd":{type:"string",description:"Bring your own tunnel: a command that exposes a local target and prints its public https URL (e.g. 'ngrok http 3000 --log stdout'); also read from ORA_TUNNEL_CMD. The result is stored as ephemeral"},"api-key":{type:"string",description:"ora-issued scan API key that lifts the scan rate limits; also read from ORA_SCAN_API_KEY"},"show-passing":{type:"boolean",description:"List each passing check individually",default:!1},"show-skipped":{type:"boolean",description:"List not-applicable / pending checks too",default:!1}},async run({args:e}){process.exitCode=await Nn({url:e.url,json:!!e.json,showSkipped:!!e["show-skipped"],showPassing:!!e["show-passing"],minScore:e["min-score"],maxAge:e["max-age"],force:!!e.force,tunnelCmd:e["tunnel-cmd"],tunnel:e.tunnel,apiKey:e["api-key"]})}},Ha={meta:{name:"journey",description:"Send a real AI agent at a site and watch it navigate live"},args:{intent:{type:"positional",description:'Goal for the agent (e.g. "Find the API docs and how to auth")',required:!0},domain:{type:"string",description:"Site the agent targets (e.g. stripe.com)"},harness:{type:"string",description:"Agent harness: claude-code, codex, openclaw, hermess, claude-agent, eve, \u2026",default:"claude-code"},model:{type:"string",description:"Model override (harness default when omitted)"},json:{type:"boolean",description:"Output as JSON",default:!1}},async run({args:e}){process.exitCode=await zn({intent:e.intent,domain:e.domain,harness:e.harness,model:e.model,json:!!e.json})}},Ga={meta:{name:"deep-journey",description:"Run a real AI agent at a site on a curated task \u2014 or, with a partner API key, a free-text one \u2014 via ora's public API (exit codes: 0 ok, 1 run failed, 2 usage, 3 API error)"},args:{url:{type:"positional",description:"URL or domain the agent targets (e.g. stripe.com)",required:!0},intent:{type:"string",description:"Curated intent id (see GET /api/journey/intents; server default when omitted)"},agent:{type:"string",description:"Agent id (see GET /api/journey/agents); defaults to cas-haiku (Claude Code \xB7 Haiku 4.5)"},json:{type:"boolean",description:"Print the terminal run detail as JSON",default:!1},task:{type:"string",description:"Free-text task for the agent (needs a partner API key; mutually exclusive with --intent)"},"api-key":{type:"string",description:"ora-issued partner API key: unlocks --task and the 1000/24h keyed allowance; also read from ORA_PARTNER_API_KEY"},"no-stream":{type:"boolean",description:"Hide the live trajectory view and print only the final result",default:!1}},async run({args:e}){process.exitCode=await Kn({url:e.url,intent:e.intent,task:e.task,apiKey:e["api-key"],agent:e.agent,json:!!e.json,noStream:!!e["no-stream"]})}},Ka={meta:{name:"generate-files",description:"Draft a domain's agent files (ard.json, ai-catalog.json, poppy.json, llms.txt, a robots.txt edit, api-catalog, MCP server cards) into <out> (exit codes: 0 ok, 2 usage or files already exist, 3 API error)"},args:{domain:{type:"positional",description:"Domain the files speak for (e.g. example.com)",required:!0},out:{type:"string",description:"Your site's web root; files land under it (.well-known/, robots.txt, llms.txt) (default: current directory)"},force:{type:"boolean",description:"Overwrite files that already exist",default:!1},json:{type:"boolean",description:"Print ora's payload as JSON and write nothing",default:!1}},async run({args:e}){process.exitCode=await Xn({domain:e.domain,out:e.out,force:!!e.force,json:!!e.json})}},qa={meta:{name:"skill",description:"List, print, or install ora's agent skills (digest-verified from the registry, never bundled)"},args:{name:{type:"positional",description:"Skill name (omit to list the registry)",required:!1},install:{type:"boolean",description:"Write <dir>/<name>/SKILL.md instead of printing",default:!1},dir:{type:"string",description:"Install directory (default .claude/skills)"},json:{type:"boolean",description:"Print the raw registry index as JSON",default:!1}},async run({args:e}){process.exitCode=await nr({name:e.name,install:!!e.install,dir:e.dir,json:!!e.json})}},Ya={meta:{name:"webmcp-audit",description:"Audit a page's WebMCP tools in a real browser - localhost included, so you can check before you publish (exit codes: 0 ok, 1 below --min-score, 2 usage, 3 API error)"},args:{url:{type:"positional",description:"Page to audit, scheme included (e.g. http://localhost:3000)",required:!0},"chrome-endpoint":{type:"string",description:"Drive a Chrome you started instead of launching one: ws:// URL, http origin, or host:port"},"min-score":{type:"string",description:"Exit 1 when the score is below this threshold (0-100); the CI gate"},"api-key":{type:"string",description:"ora API key that lifts the ingest rate limits; also read from ORA_API_KEY"},json:{type:"boolean",description:"Print the raw ora audit payload as JSON",default:!1},"show-passing":{type:"boolean",description:"List each passing check individually",default:!1}},async run({args:e}){process.exitCode=await Hr({url:e.url,json:!!e.json,showPassing:!!e["show-passing"],minScore:e["min-score"],chromeEndpoint:e["chrome-endpoint"],apiKey:e["api-key"]})}};function Va(){let e=ze.default.green("$"),t=ze.default.dim;return["",` ${ze.default.bold(V)} ${t(`v${we.version}`)}`,` ${t("Score any site's agent readiness \u2014 and watch real AI agents navigate it")}`,"",` ${t("Commands:")}`,` audit ${t("<url>")} ${t("Score a site's agent readiness")}`,` webmcp-audit ${t("<url>")} ${t("Audit a WebMCP surface in a real browser, localhost included")}`,` deep-journey ${t("<url>")} ${t("Run a real agent at a site on a curated or free-text task")}`,` journey ${t("<intent>")} ${t("Send a real agent at a site and watch it live (workspace)")}`,` skill ${t("[name]")} ${t("List, print, or install ora's agent skills")}`,` generate-files ${t("<domain>")} ${t("Draft a domain's agent files: ARD catalog, poppy.json, llms.txt, robots.txt edit, \u2026")}`,"",` ${t("Examples:")}`,` ${e} ${V} audit https://docs.example.com`,` ${e} ${V} audit https://docs.example.com --min-score 70 ${t("# CI gate")}`,` ${e} ${V} audit https://docs.example.com --json`,` ${e} ${V} audit localhost:3000 --tunnel ora ${t("# audit a local dev server")}`,` ${e} ${V} webmcp-audit http://localhost:3000`,` ${e} ${V} deep-journey stripe.com --intent pricing`,` ${e} ${V} journey "Find the API docs and how to authenticate" --domain stripe.com`,` ${e} ${V} generate-files example.com --out public`,"",` ${t("audit options:")}`,` --min-score <n> ${t("Exit 1 when the score is below n (0-100); the CI gate")}`,` --max-age <s> ${t("Accept a cached result up to s seconds old (default 6h)")}`,` --force ${t("Bypass the cache and rescan (6/day budget)")}`,` --tunnel ora ${t("Expose a local target through ora's own tunnel (needs ORA_API_KEY: tunnels:write + tunnels:connect)")}`,` --tunnel-cmd <c> ${t("...or through your own tunnel command (e.g. 'ngrok http 3000 --log stdout')")}`,` --api-key <k> ${t("ora-issued scan API key that lifts the rate limits; also read from ORA_SCAN_API_KEY")}`,` --json ${t("Print the raw ora audit payload as JSON")}`,` --show-passing ${t("List each passing check (hidden by default)")}`,` --show-skipped ${t("List skipped checks (hidden by default)")}`,"",` ${t("audit exit codes:")}`,` ${t("0 success \xB7 1 below --min-score \xB7 2 usage error \xB7 3 API unreachable/rate-limited")}`,"",` ${t("webmcp-audit options:")}`,` --chrome-endpoint ${t("<e> Drive a Chrome you started: ws:// URL, http origin, or host:port")}`,` --min-score <n> ${t("Exit 1 when the score is below n (0-100); the CI gate")}`,` --api-key <k> ${t("ora API key that lifts the ingest rate limits; also read from ORA_API_KEY")}`,` --json ${t("Print the raw ora audit payload as JSON")}`,` --show-passing ${t("List each passing check (hidden by default)")}`,` ${t("starts a headless Chrome you already have installed; never downloads one")}`,` ${t("scored by ora, stored nowhere: the result is never published or ranked")}`,"",` ${t("deep-journey options:")}`,` --intent <id> ${t("Curated task id, e.g. pricing, signup, api-docs (server default when omitted)")}`,` --task <text> ${t("Free-text task (needs a partner API key; replaces --intent)")}`,` --api-key <k> ${t("ora partner API key: unlocks --task + 1000 runs/24h; also read from ORA_PARTNER_API_KEY")}`,` --agent <id> ${t("Agent to run (default: cas-haiku \u2014 Claude Code \xB7 Haiku 4.5)")}`,` --no-stream ${t("Hide the live trajectory view and print only the final result")}`,` --json ${t("Print the terminal run detail as JSON")}`,` ${t("no key needed \xB7 public caps: 100 runs/24h per target, 20 runs/24h per IP")}`,"",` ${t("generate-files options:")}`,` --out <dir> ${t("Your site's web root: writes .well-known/*, robots.txt, llms.txt there (default: .)")}`,` --force ${t("Overwrite files that already exist (otherwise nothing is written)")}`,` --json ${t("Print ora's payload as JSON and write nothing")}`,` ${t("drafts from ora's last scan of the domain - review each file before you publish it")}`,"",` ${t("journey options:")}`,` --domain <d> ${t("Site the agent targets (e.g. stripe.com)")}`,` --harness <h> ${t("Agent harness: claude-code (default), codex, openclaw, hermess, claude-agent, eve, \u2026")}`,` --model <m> ${t("Model override (harness default when omitted)")}`,` --json ${t("Output as JSON")}`,` ${t("requires ORA_API_KEY (see .env.example)")}`,""].join(`
|
|
604
|
-
`)}var
|
|
716
|
+
`),K.BELOW_MIN_SCORE}return K.OK}function Ya(e){switch(e.type){case"phase":return`Scoring with ora \u2014 ${e.phase}`;case"tool-discovered":return`Scoring with ora \u2014 found ${O(e.tool.name)}`;case"finding":return`Scoring with ora \u2014 ${e.finding.checkId}`;case"simulation-step":return`Scoring with ora \u2014 simulating "${O(e.step.intent)}"`;default:return"Scoring with ora"}}function Vr(){if(typeof process.loadEnvFile!="function")return!1;try{return process.loadEnvFile(),!0}catch{return!1}}var V="ax",Va={meta:{name:"audit",description:"Score a site's agent readiness (exit codes: 0 ok, 1 below --min-score, 2 usage, 3 API error)"},args:{url:{type:"positional",description:"URL or domain to audit (e.g. https://docs.example.com)",required:!0},json:{type:"boolean",description:"Print the raw ora audit payload as JSON",default:!1},"min-score":{type:"string",description:"Exit 1 when the score is below this threshold (0-100); the CI gate"},"max-age":{type:"string",description:"Accept a cached result up to this many seconds old (server default 6h)"},force:{type:"boolean",description:"Bypass the cache and rescan (spends the stricter 6/day force budget)",default:!1},tunnel:{type:"string",description:"Open ora's own tunnel to a local target (value: ora); needs ORA_API_KEY with the tunnels:write + tunnels:connect scopes. Also read from ORA_TUNNEL. The result is stored as ephemeral"},"tunnel-cmd":{type:"string",description:"Bring your own tunnel: a command that exposes a local target and prints its public https URL (e.g. 'ngrok http 3000 --log stdout'); also read from ORA_TUNNEL_CMD. The result is stored as ephemeral"},"api-key":{type:"string",description:"ora-issued scan API key that lifts the scan rate limits; also read from ORA_SCAN_API_KEY"},"show-passing":{type:"boolean",description:"List each passing check individually",default:!1},"show-skipped":{type:"boolean",description:"List not-applicable / pending checks too",default:!1}},async run({args:e}){process.exitCode=await Ln({url:e.url,json:!!e.json,showSkipped:!!e["show-skipped"],showPassing:!!e["show-passing"],minScore:e["min-score"],maxAge:e["max-age"],force:!!e.force,tunnelCmd:e["tunnel-cmd"],tunnel:e.tunnel,apiKey:e["api-key"]})}},Xa={meta:{name:"journey",description:"Send a real AI agent at a site and watch it navigate live"},args:{intent:{type:"positional",description:'Goal for the agent (e.g. "Find the API docs and how to auth")',required:!0},domain:{type:"string",description:"Site the agent targets (e.g. stripe.com)"},harness:{type:"string",description:"Agent harness: claude-code, codex, openclaw, hermess, claude-agent, eve, \u2026",default:"claude-code"},model:{type:"string",description:"Model override (harness default when omitted)"},json:{type:"boolean",description:"Output as JSON",default:!1}},async run({args:e}){process.exitCode=await zn({intent:e.intent,domain:e.domain,harness:e.harness,model:e.model,json:!!e.json})}},za={meta:{name:"deep-journey",description:"Run a real AI agent at a site on a curated task \u2014 or, with a partner API key, a free-text one \u2014 via ora's public API (exit codes: 0 ok, 1 run failed, 2 usage, 3 API error)"},args:{url:{type:"positional",description:"URL or domain the agent targets (e.g. stripe.com)",required:!0},intent:{type:"string",description:"Curated intent id (see GET /api/journey/intents; server default when omitted)"},agent:{type:"string",description:"Agent id (see GET /api/journey/agents); defaults to cas-haiku, Claude Code on the Haiku model ora's roster lists"},json:{type:"boolean",description:"Print the terminal run detail as JSON",default:!1},task:{type:"string",description:"Free-text task for the agent (needs a partner API key; mutually exclusive with --intent)"},"api-key":{type:"string",description:"ora-issued partner API key: unlocks --task and the 1000/24h keyed allowance; also read from ORA_PARTNER_API_KEY, then ORA_SCAN_API_KEY"},"no-stream":{type:"boolean",description:"Hide the live trajectory view and print only the final result",default:!1}},async run({args:e}){process.exitCode=await Kn({url:e.url,intent:e.intent,task:e.task,apiKey:e["api-key"],agent:e.agent,json:!!e.json,noStream:!!e["no-stream"]})}},Qa={meta:{name:"generate-files",description:"Draft a domain's agent files (ard.json, ai-catalog.json, poppy.json, llms.txt, a robots.txt edit, api-catalog, MCP server cards) into <out> (exit codes: 0 ok, 2 usage or files already exist, 3 API error)"},args:{domain:{type:"positional",description:"Domain the files speak for (e.g. example.com)",required:!0},out:{type:"string",description:"Your site's web root; files land under it (.well-known/, robots.txt, llms.txt) (default: current directory)"},force:{type:"boolean",description:"Overwrite files that already exist",default:!1},json:{type:"boolean",description:"Print ora's payload as JSON and write nothing",default:!1}},async run({args:e}){process.exitCode=await Xn({domain:e.domain,out:e.out,force:!!e.force,json:!!e.json})}},Za={meta:{name:"skill",description:"List, print, or install ora's agent skills (digest-verified from the registry, never bundled)"},args:{name:{type:"positional",description:"Skill name (omit to list the registry)",required:!1},install:{type:"boolean",description:"Write <dir>/<name>/SKILL.md instead of printing",default:!1},dir:{type:"string",description:"Install directory (default .claude/skills)"},json:{type:"boolean",description:"Print the raw registry index as JSON",default:!1}},async run({args:e}){process.exitCode=await nr({name:e.name,install:!!e.install,dir:e.dir,json:!!e.json})}},ec={meta:{name:"webmcp-audit",description:"Audit a page's WebMCP tools in a real browser - localhost included, so you can check before you publish (exit codes: 0 ok, 1 below --min-score, 2 usage, 3 API error)"},args:{url:{type:"positional",description:"Page to audit, scheme included (e.g. http://localhost:3000)",required:!0},"chrome-endpoint":{type:"string",description:"Drive a Chrome you started instead of launching one: ws:// URL, http origin, or host:port"},"min-score":{type:"string",description:"Exit 1 when the score is below this threshold (0-100); the CI gate"},"api-key":{type:"string",description:"ora partner or scan API key that lifts the daily ingest limit; also read from ORA_PARTNER_API_KEY, then ORA_SCAN_API_KEY"},json:{type:"boolean",description:"Print the raw ora audit payload as JSON",default:!1},"show-passing":{type:"boolean",description:"List each passing check individually",default:!1}},async run({args:e}){process.exitCode=await Yr({url:e.url,json:!!e.json,showPassing:!!e["show-passing"],minScore:e["min-score"],chromeEndpoint:e["chrome-endpoint"],apiKey:e["api-key"]})}};function zr(){let e=ze.default.green("$"),t=ze.default.dim;return["",` ${ze.default.bold(V)} ${t(`v${we.version}`)}`,` ${t("Score any site's agent readiness \u2014 and watch real AI agents navigate it")}`,"",` ${t("Commands:")}`,` audit ${t("<url>")} ${t("Score a site's agent readiness")}`,` webmcp-audit ${t("<url>")} ${t("Audit a WebMCP surface in a real browser, localhost included")}`,` deep-journey ${t("<url>")} ${t("Run a real agent at a site on a curated or free-text task")}`,` journey ${t("<intent>")} ${t("Send a real agent at a site and watch it live (needs a platform key)")}`,` skill ${t("[name]")} ${t("List, print, or install ora's agent skills")}`,` generate-files ${t("<domain>")} ${t("Draft a domain's agent files: ARD catalog, poppy.json, llms.txt, robots.txt edit, \u2026")}`,"",` ${t("Examples:")}`,` ${e} ${V} audit https://docs.example.com`,` ${e} ${V} audit https://docs.example.com --min-score 70 ${t("# CI gate")}`,` ${e} ${V} audit https://docs.example.com --json`,` ${e} ${V} audit localhost:3000 --tunnel ora ${t("# audit a local dev server")}`,` ${e} ${V} webmcp-audit http://localhost:3000`,` ${e} ${V} deep-journey stripe.com --intent pricing`,` ${e} ${V} journey "Find the API docs and how to authenticate" --domain stripe.com`,` ${e} ${V} generate-files example.com --out public`,"",` ${t("audit options:")}`,` --min-score <n> ${t("Exit 1 when the score is below n (0-100); the CI gate")}`,` --max-age <s> ${t("Accept a cached result up to s seconds old (default 6h)")}`,` --force ${t("Bypass the cache and rescan (6/day budget)")}`,` --tunnel ora ${t("Expose a local target through ora's own tunnel (needs ORA_API_KEY: tunnels:write + tunnels:connect)")}`,` --tunnel-cmd <c> ${t("...or through your own tunnel command (e.g. 'ngrok http 3000 --log stdout')")}`,` --api-key <k> ${t("ora-issued scan API key that lifts the rate limits; also read from ORA_SCAN_API_KEY")}`,` --json ${t("Print the raw ora audit payload as JSON")}`,` --show-passing ${t("List each passing check (hidden by default)")}`,` --show-skipped ${t("List skipped checks (hidden by default)")}`,"",` ${t("audit exit codes:")}`,` ${t("0 success \xB7 1 below --min-score \xB7 2 usage error \xB7 3 API unreachable/rate-limited")}`,"",` ${t("webmcp-audit options:")}`,` --chrome-endpoint ${t("<e> Drive a Chrome you started: ws:// URL, http origin, or host:port")}`,` --min-score <n> ${t("Exit 1 when the score is below n (0-100); the CI gate")}`,` --api-key <k> ${t("ora partner or scan API key that lifts the daily ingest limit; also read from ORA_PARTNER_API_KEY")}`,` --json ${t("Print the raw ora audit payload as JSON")}`,` --show-passing ${t("List each passing check (hidden by default)")}`,` ${t("starts a headless Chrome you already have installed; never downloads one")}`,` ${t("scored by ora, stored nowhere: the result is never published or ranked")}`,` ${t("exit codes: 0 ok \xB7 1 below --min-score \xB7 2 usage \xB7 3 API error")}`,"",` ${t("deep-journey options:")}`,` --intent <id> ${t("Curated task id, e.g. pricing, signup, api-docs (server default when omitted)")}`,` --task <text> ${t("Free-text task (needs a partner API key; replaces --intent)")}`,` --api-key <k> ${t("ora partner API key: unlocks --task + 1000 runs/24h; also read from ORA_PARTNER_API_KEY, then ORA_SCAN_API_KEY")}`,` --agent <id> ${t("Agent to run (default: cas-haiku \u2014 Claude Code on the Haiku model ora's roster lists)")}`,` --no-stream ${t("Hide the live trajectory view and print only the final result")}`,` --json ${t("Print the terminal run detail as JSON")}`,` ${t("no key needed \xB7 public caps: 100 runs/24h per target and task, 20 runs/24h per IP")}`,` ${t("exit codes: 0 run succeeded (any verdict) \xB7 1 run failed \xB7 2 usage \xB7 3 API unreachable/rate-limited")}`,"",` ${t("generate-files options:")}`,` --out <dir> ${t("Your site's web root: writes .well-known/*, robots.txt, llms.txt there (default: .)")}`,` --force ${t("Overwrite files that already exist (otherwise nothing is written)")}`,` --json ${t("Print ora's payload as JSON and write nothing")}`,` ${t("drafts from ora's last scan of the domain - review each file before you publish it")}`,` ${t("exit codes: 0 written \xB7 2 usage or files already exist \xB7 3 API error")}`,"",` ${t("skill options:")}`,` --install ${t("Write <dir>/<name>/SKILL.md instead of printing it")}`,` --dir <path> ${t("Install directory (default .claude/skills)")}`,` --json ${t("Print the raw registry index as JSON")}`,"",` ${t("journey options:")}`,` --domain <d> ${t("Site the agent targets (e.g. stripe.com)")}`,` --harness <h> ${t("Agent harness: claude-code (default), codex, openclaw, hermess, claude-agent, eve, \u2026")}`,` --model <m> ${t("Model override (harness default when omitted)")}`,` --json ${t("Output as JSON")}`,` ${t("requires ORA_API_KEY (see .env.example)")}`,""].join(`
|
|
717
|
+
`)}var Xr={meta:{name:V,version:we.version,description:"Score any site's agent readiness \u2014 and watch real AI agents navigate it"},subCommands:{audit:Va,"webmcp-audit":ec,"deep-journey":za,journey:Xa,skill:Za,"generate-files":Qa},setup(){process.argv[2]||(console.log(zr()),process.exit(0))}};Vr();Yt(Xr,{showUsage:async(e,t)=>{e===Xr?console.log(zr()):await rt(e,t)}});
|