ax 0.9.1 → 0.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +6 -6
- package/README.md +48 -30
- package/dist/api/agent-files.d.ts +10 -2
- package/dist/contract/types.gen.d.ts +20 -8
- package/dist/contract/version.d.ts +1 -1
- package/dist/index.cjs +6 -4
- package/dist/index.js +6 -4
- package/dist/main.cjs +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
|
|
4
|
-
`)}catch(n){console.error(n)}}var
|
|
5
|
-
`)}function Ze(e){let t=e.valueHint?`=<${e.valueHint}>`:"",n=t||`=<${
|
|
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 Vr=Object.create;var Wt=Object.defineProperty;var Xr=Object.getOwnPropertyDescriptor;var zr=Object.getOwnPropertyNames;var Qr=Object.getPrototypeOf,Zr=Object.prototype.hasOwnProperty;var eo=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var to=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of zr(t))!Zr.call(e,o)&&o!==n&&Wt(e,o,{get:()=>t[o],enumerable:!(r=Xr(t,o))||r.enumerable});return e};var B=(e,t,n)=>(n=e!=null?Vr(Qr(e)):{},to(t||!e||!e.__esModule?Wt(n,"default",{value:e,enumerable:!0}):n,e));var D=eo((ic,rt)=>{"use strict";var Me=process||{},Yt=Me.argv||[],Ie=Me.env||{},wo=!(Ie.NO_COLOR||Yt.includes("--no-color"))&&(!!Ie.FORCE_COLOR||Yt.includes("--color")||Me.platform==="win32"||(Me.stdout||{}).isTTY&&Ie.TERM!=="dumb"||!!Ie.CI),bo=(e,t,n=e)=>r=>{let o=""+r,s=o.indexOf(t,e.length);return~s?e+vo(o,t,n,s)+t:e+o+t},vo=(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)},Vt=(e=wo)=>{let t=e?bo:()=>String;return{isColorSupported:e,reset:t("\x1B[0m","\x1B[0m"),bold:t("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:t("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:t("\x1B[3m","\x1B[23m"),underline:t("\x1B[4m","\x1B[24m"),inverse:t("\x1B[7m","\x1B[27m"),hidden:t("\x1B[8m","\x1B[28m"),strikethrough:t("\x1B[9m","\x1B[29m"),black:t("\x1B[30m","\x1B[39m"),red:t("\x1B[31m","\x1B[39m"),green:t("\x1B[32m","\x1B[39m"),yellow:t("\x1B[33m","\x1B[39m"),blue:t("\x1B[34m","\x1B[39m"),magenta:t("\x1B[35m","\x1B[39m"),cyan:t("\x1B[36m","\x1B[39m"),white:t("\x1B[37m","\x1B[39m"),gray:t("\x1B[90m","\x1B[39m"),bgBlack:t("\x1B[40m","\x1B[49m"),bgRed:t("\x1B[41m","\x1B[49m"),bgGreen:t("\x1B[42m","\x1B[49m"),bgYellow:t("\x1B[43m","\x1B[49m"),bgBlue:t("\x1B[44m","\x1B[49m"),bgMagenta:t("\x1B[45m","\x1B[49m"),bgCyan:t("\x1B[46m","\x1B[49m"),bgWhite:t("\x1B[47m","\x1B[49m"),blackBright:t("\x1B[90m","\x1B[39m"),redBright:t("\x1B[91m","\x1B[39m"),greenBright:t("\x1B[92m","\x1B[39m"),yellowBright:t("\x1B[93m","\x1B[39m"),blueBright:t("\x1B[94m","\x1B[39m"),magentaBright:t("\x1B[95m","\x1B[39m"),cyanBright:t("\x1B[96m","\x1B[39m"),whiteBright:t("\x1B[97m","\x1B[39m"),bgBlackBright:t("\x1B[100m","\x1B[49m"),bgRedBright:t("\x1B[101m","\x1B[49m"),bgGreenBright:t("\x1B[102m","\x1B[49m"),bgYellowBright:t("\x1B[103m","\x1B[49m"),bgBlueBright:t("\x1B[104m","\x1B[49m"),bgMagentaBright:t("\x1B[105m","\x1B[49m"),bgCyanBright:t("\x1B[106m","\x1B[49m"),bgWhiteBright:t("\x1B[107m","\x1B[49m")}};rt.exports=Vt();rt.exports.createColors=Vt});var no=/\d/,ro=["-","_","/","."];function oo(e=""){if(!no.test(e))return e!==e.toLowerCase()}function Dt(e,t){let n=t??ro,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=oo(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 so(e){return e?e[0].toUpperCase()+e.slice(1):""}function io(e){return e?e[0].toLowerCase()+e.slice(1):""}function ao(e,t){return e?(Array.isArray(e)?e:Dt(e)).map(n=>so(t?.normalize?n.toLowerCase():n)).join(""):""}function fe(e,t){return io(ao(e||"",t))}function Te(e,t){return e?(Array.isArray(e)?e:Dt(e)).map(n=>n.toLowerCase()).join(t??"-"):""}function Ft(e){return Te(e||"","_")}var Ht=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 co(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,Ht.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 lo=(()=>{let e=globalThis.process?.env??{};return e.NO_COLOR==="1"||e.TERM==="dumb"||e.TEST||e.CI})(),Oe=(e,t=39)=>n=>lo?n:`\x1B[${e}m${n}\x1B[${t}m`,_e=Oe(1,22),J=Oe(36),Pe=Oe(90),Ce=Oe(4,24);function uo(e,t){let n={boolean:[],string:[],alias:{},default:{}},r=Gt(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=co(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 Gt(e){let t=[];for(let[n,r]of Object.entries(e||{}))t.push({...r,name:n,alias:ye(r.alias)});return t}async function po(e){return Promise.all(e.map(t=>I(t)))}async function et(e,t){let n=await I(e.args||{}),r=uo(t.rawArgs,n),o={rawArgs:t.rawArgs,args:r,data:t.data,cmd:e},s=await po(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=Kt(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=Kt(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 Kt(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(r==="--")return-1;if(r.startsWith("-")){!r.includes("=")&&mo(r,t)&&n++;continue}return n}return-1}function mo(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 ho(e,t){try{console.log(await fo(e,t)+`
|
|
4
|
+
`)}catch(n){console.error(n)}}var go=/^no[-A-Z]/;async function fo(e,t){let n=await I(e.meta||{}),r=Gt(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)),Bt(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),Bt(g,f)]),g.type==="boolean"&&(g.default===!0||g.negativeDescription)&&!go.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||`=<${Ft(e.name)}>`;return!e.type||e.type==="positional"||e.type==="boolean"?t:e.type==="enum"&&e.options?.length?`=<${e.options.join("|")}>`:n}function Bt(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 qt(e,t={}){let n=t.rawArgs||process.argv.slice(2),r=t.showUsage||ho;try{let o=await yo(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 yo(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:Jt("help","h",n,r),version:Jt("version","v",n,r)}}function Jt(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.1",description:"Score any site's agent readiness and watch real AI agents navigate it \u2014 powered by ora",type:"module",packageManager:"pnpm@10.34.5",bin:{ax:"./dist/main.cjs"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"}},main:"./dist/index.cjs",types:"./dist/index.d.ts",files:["dist",".env.example"],engines:{node:">=22.4.0"},scripts:{build:"rm -rf dist && tsup && tsc -p tsconfig.lib.json","contract:gen":"node scripts/contract-gen.mjs",smoke:"node scripts/smoke.mjs","smoke:webmcp":"node scripts/smoke-webmcp.mjs","verify:pack":"node scripts/verify-pack.mjs",test:"vitest","test:ci":"vitest run --coverage","test:capture":"vitest run src/webmcp/capture.live.test.ts",lint:"biome check .","lint:fix":"biome check --write .",typecheck:"tsc --noEmit",prepublishOnly:"npm run build"},devDependencies:{"@biomejs/biome":"^2.5.7","@commitlint/cli":"^21.2.2","@commitlint/config-conventional":"^21.2.2","@ora-ai/tunnel-protocol":"^0.4.1","@types/node":"^26.2.0","@vitest/coverage-v8":"^3",citty:"^0.2.2","openapi-typescript":"^6.7.6",picocolors:"^1",tsup:"^8",typescript:"^7.0.2",vitest:"^3"},publishConfig:{access:"public"},pnpm:{onlyBuiltDependencies:["@biomejs/biome","esbuild"],overrides:{"undici@<6.28.0":"^6.28.0"}},license:"MIT",author:{name:"Era AI Labs",url:"https://ora.ai"},homepage:"https://ora.ai/docs#cli",bugs:"https://github.com/ora/ax/issues",repository:{type:"git",url:"git+https://github.com/ora/ax.git"},keywords:["ai","agents","agent-readiness","agent-experience","llms.txt","ora","cli","scan"]};var wt=B(D(),1);var ot="1.31.0";function Xt(e){let[t=0,n=0]=e.split(".").map(r=>Number.parseInt(r,10));return[t,n]}function xo(e){if(!e||!/^\d+\.\d+\.\d+$/.test(e))return!1;let[t,n]=Xt(e),[r,o]=Xt(ot);return t>r||t===r&&n>o}var zt=!1;function be(e){zt||!xo(e)||(zt=!0,process.stderr.write(`ora reports contract ${e}; this CLI was built against ${ot}. Newer fields may be missing from the output - upgrade with: npm i -g ax@latest
|
|
7
|
+
`))}function z(e){let t=new AbortController,n=!1,r,o=()=>{clearTimeout(r),r=setTimeout(()=>{n=!0,t.abort()},e)};return o(),{signal:t.signal,poke:o,disarm:()=>clearTimeout(r),tripped:()=>n}}async function ve(e){let t=null;try{t=await e.clone().json()}catch{}return e.body?.cancel().catch(()=>{}),{message:t?.message||t?.error||`HTTP ${e.status}`,code:t?.code??null,payload:t}}async function ce(e){return(await ve(e)).message}var Q=e=>new Promise(t=>setTimeout(t,e));var Ao="https://ora.ai",ko=6e4,Eo=2e3,Ro=45,st=14,j=class extends Error{code;payload;constructor(t,n={}){super(t),this.name="AuditApiError",this.code=n.code??null,this.payload=n.payload}},$o="MCP_AUTH_REQUIRED";function Qt(e){return e instanceof j&&e.code===$o}function Zt(e){return e?{authorization:`Bearer ${e}`}:{}}async function en(e,t={}){let n=(t.baseUrl??process.env.ORA_API_URL??Ao).replace(/\/+$/,"");t={...t,apiKey:t.apiKey||process.env.ORA_SCAN_API_KEY||void 0},t.progress?.(`Auditing ${e} with ora`);let r=await _o(n,e,t);be(r.result.contractVersion);let o=r.result;return tn(o)&&(o=await Oo(n,o,t)),{result:o,verdict:r.verdict}}function To(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 _o(e,t,n){let r=n.idleMs??ko,o=z(r),s=()=>new j(`ora audit timed out \u2014 no progress for ${Math.round(r/1e3)}s`),i;try{i=await fetch(To(e,t,n),{headers:{accept:"text/event-stream",...Zt(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=Po(),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=Co(l.slice(0,g));if(l=l.slice(g+2),g=l.indexOf(`
|
|
11
11
|
|
|
12
|
-
`),!f)continue;let
|
|
12
|
+
`),!f)continue;let h;try{h=JSON.parse(f)}catch{continue}let p=a(h);if(p&&n.progress?.(p),h.type==="error")throw new j(`ora audit failed: ${typeof h.message=="string"?h.message:"scan error"}`,{code:typeof h.code=="string"?h.code:null,payload:h});if(h.type==="scan_complete"&&h.result?u=h.result:h.type==="summary_ready"&&typeof h.agenticSummary=="string"&&(d=h.agenticSummary),u&&d)break e}}}catch(m){if(o.tripped())throw s();if(m instanceof j)throw m;let g=m instanceof Error?m.message:String(m);throw new j(`ora audit stream error: ${g}`)}finally{o.disarm(),i.body.cancel().catch(()=>{})}if(!u)throw new j("ora audit stream ended before completing");return{result:u,verdict:d}}function Co(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 Po(){let e=0,t=0,n="";return r=>{switch(r.type){case"kind_detecting":return"Detecting URL kind\u2026";case"kind_detected":return typeof r.kind=="string"?`Detected ${r.kind}, scanning\u2026`:void 0;case"scan_init":Array.isArray(r.checkRoster)&&(e=r.checkRoster.length);return;case"discovery_phase":return typeof r.label=="string"?r.label:void 0;case"check_complete":{if(t+=1,typeof r.checkName=="string"&&(n=r.checkName),e<=0)return`Running checks\u2026 (${t})`;let o=Math.min(t,e),s=Math.min(st,Math.max(0,Math.round(o/e*st)));return`${`${"\u2588".repeat(s)}${"\u2591".repeat(st-s)}`} ${o}/${e}${n?` \xB7 ${n}`:""}`}case"scan_complete":return"Finishing up\u2026";default:return}}}function tn(e){return e.analysisStatus==="complete"||e.analysisStatus==="stuck"?!1:e.analysisStatus==="partial"?!0:(e.pendingChecks?.length??0)>0}async function Oo(e,t,n){let r=`${e}/api/score/${encodeURIComponent(t.domain)}?format=audit`,o=n.pollEveryMs??Eo,s=n.pollLimit??Ro,i=t;for(let a=0;a<s&&tn(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",...Zt(n.apiKey)},signal:AbortSignal.timeout(15e3)});l.ok&&(i=await l.json())}catch{}}return i}function Io(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 Mo(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 nn(e,t){let{result:n}=e,r=(n.layers??[]).map(i=>Io(i.name,(i.checks??[]).map(Mo))),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),at="\u26A0 MCP handshake requires credentials \u2014 target is unscored",No=" (0/F means could not evaluate, not failed everything)",Lo=80,jo=120,Ne=10;function Uo(){return Math.min(jo,Math.max(Lo,process.stdout.columns??100))}function ct(e,t){return e.length<t?e+" ".repeat(t-e.length):e}function on(e,t){if(t<=0||e.length<=t)return[e];let n=[],r="";for(let o of e.split(/\s+/))for(r=r?`${r} ${o}`:o;r.length>t;){let s=r.lastIndexOf(" ");s>0&&r.length-s-1<=t?(n.push(r.slice(0,s)),r=r.slice(s+1)):(n.push(r.slice(0,t)),r=r.slice(t))}return r&&n.push(r),n.length?n:[""]}function it(e,t){let n=(i,a,c)=>v.default.dim(i+e.map(l=>"\u2500".repeat(l.width+2)).join(a)+c),r=v.default.dim("\u2502"),o=(i,a)=>{let c=i.map((d,m)=>on(typeof d=="string"?d:d[0],e[m].width)),l=Math.max(1,...c.map(d=>d.length)),u=[];for(let d=0;d<l;d++){let m=c.map((g,f)=>{let h=ct(g[d]??"",e[f].width),p=a??(typeof i[f]=="string"?e[f].paint:i[f][1]);return` ${p?p(h):h} `});u.push(r+m.join(r)+r)}return u},s=[n("\u250C","\u252C","\u2510")];return s.push(...o(e.map(i=>i.title),v.default.bold)),s.push(n("\u251C","\u253C","\u2524")),t.forEach((i,a)=>{s.push(...o(i)),a<t.length-1&&s.push(n("\u251C","\u253C","\u2524"))}),s.push(n("\u2514","\u2534","\u2518")),s}function Wo(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 rn(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 Do(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 Fo(e,t,n,r){let o=[""],s=e.total>0?`${e.passed}/${e.total} passed`:"no applicable checks",i=e.skipped>0?` \xB7 ${e.skipped} skipped`:"";o.push(` ${v.default.bold(ct(e.name,n))} ${Do(e.passed,e.total)} ${v.default.dim(s+i)}`);let a=e.checks.filter(c=>!c.passed&&!c.skipped);if(a.length){o.push(` ${v.default.red("\u2717")} ${v.default.bold(`Issues (${a.length})`)}`);let c=it(Wo(t,a.map(u=>u.name)),a.map(u=>[u.status==="warning"?["\u26A0",v.default.yellow]:["\u2717",v.default.red],u.name,[u.detail??"",d=>d],u.hint??""]));o.push(...c.map(u=>` ${u}`));let l=a.filter(u=>u.specUrl);for(let u of l)o.push(v.default.dim(` \u21B3 ${u.id} spec: ${u.specUrl}`))}if(r.showPassing){let c=e.checks.filter(l=>l.passed&&!l.skipped);if(c.length){o.push(` ${v.default.green("\u2713")} ${v.default.bold(`Passed (${c.length})`)}`);let l=it(rn(t,c.map(u=>u.name),["Check","Details"]),c.map(u=>[u.name,u.detail??""]));o.push(...l.map(u=>` ${u}`))}}if(r.showSkipped){let c=e.checks.filter(l=>l.skipped);if(c.length){o.push(` ${v.default.dim(`\u25CB Skipped (${c.length})`)}`);let l=it(rn(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 Bo(e){if(!e.topFixes.length)return[];let t=["",` ${v.default.bold("Top fixes")} ${v.default.dim("(ranked by ora)")}`],n=e.topFixes.reduce((r,o)=>Math.max(r,o.id.length),0);return e.topFixes.forEach((r,o)=>{let s=typeof r.estScoreGain=="number"?v.default.green(`\u2248 +${r.estScoreGain} pts`):v.default.dim("\u2014"),i=r.bonus?v.default.dim(" (bonus)"):"";t.push(` ${o+1}. ${v.default.bold(ct(r.id,n))} ${s}${i}`)}),t}function Jo(e){return e<90?`${e}s`:e<5400?`${Math.round(e/60)} min`:`${Math.round(e/3600)}h`}function sn(e,t={}){let n=Uo(),r=e.sections.reduce((l,u)=>Math.max(l,u.name.length),0),o=[""],s=e.score>=70?v.default.green:e.score>=50?v.default.yellow:v.default.red;if(o.push(` ${v.default.bold(e.target)} ${s(v.default.bold(`${e.score}/100 ${e.grade}`))}`),t.tunnel&&o.push(v.default.dim(" tunnel audit \u2014 disposable result, excluded from rankings; off-site checks (registry listings, brand search) usually fail for a throwaway hostname")),e.mcpAuthRequired&&o.push(v.default.yellow(` ${at}${No}`)),e.summary)for(let l of on(e.summary,n-4))o.push(` ${v.default.dim(l)}`);for(let l of e.sections)o.push(...Fo(l,n,r,t));o.push(...Bo(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 (${Jo(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 an=require("child_process"),T=class extends Error{},Ho=3e4,cn=9e4,Go=1e4;function lt(e){try{let n=new URL(e.includes("://")?e:`http://${e}`).hostname;return n==="localhost"||n==="127.0.0.1"||n==="::1"||n==="[::1]"||n.endsWith(".local")||n.endsWith(".localhost")}catch{return!1}}function Ko(e){for(let t of e.matchAll(/https:\/\/[^\s"'|]+/g))try{let n=new URL(t[0]);if(n.pathname==="/"&&!n.search&&!lt(n.hostname))return n.origin}catch{}}async function ln(e,t=Ho){let n=await qo(e,t);try{await ut(n.url,cn)}catch(r){throw n.close(),r}return n}async function ut(e,t=cn,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(Go)})).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 qo(e,t){return new Promise((n,r)=>{let o=process.platform!=="win32",s=(0,an.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=Ko(a);g&&!i&&(i=!0,clearTimeout(u),s.removeAllListeners("exit"),n({url:g,close:c}))})})}var _n=require("crypto"),Cn=require("events"),Pn=require("http");var un="https://api.agentfront.sh";function dn(e){return(e??process.env.ORA_PLATFORM_URL??un).replace(/\/+$/,"")}var Yo=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 Vo(e,t,n){let r={intent:n.intent};n.domain&&(r.domain=n.domain),n.harness&&(r.harness=n.harness),n.model&&(r.model=n.model),n.executionKind&&(r.execution_kind=n.executionKind);let o=await fetch(`${e}/experiment/v1/runs`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify(r)});if(o.status===429)throw new Error("ora rate limit hit (429). Wait a moment and retry.");let s=await o.text(),i;try{i=JSON.parse(s)}catch{throw new Error(`ora returned a non-JSON response (${o.status})`)}if(!o.ok||!i.runId)throw new Error(`ora run failed (${o.status}): ${i.message??i.error??s}`);return i}function dt(e){let t="message",n=[];for(let r of e.split(`
|
|
17
17
|
`))r.startsWith(":")||(r.startsWith("event:")?t=r.slice(6).trim():r.startsWith("data:")&&n.push(r.slice(5).replace(/^ /,"")));return n.length?{event:t,data:n.join(`
|
|
18
|
-
`)}:null}async function
|
|
19
|
-
`);let
|
|
20
|
-
|
|
21
|
-
`);for(;
|
|
22
|
-
|
|
23
|
-
`),!g)continue;let f;try{f=JSON.parse(g.data)}catch{continue}if(Yo(l,g.event,f,r),l.summary&&l.insight)break e}}}catch(d){throw i.tripped()?new Error(`ora run stream timed out after ${o}ms of silence`):d}finally{i.disarm(),a.body.cancel().catch(()=>{})}return l}function Yo(e,t,n,r){switch(t){case"trajectory":{let o=n.steps;Array.isArray(o)&&(e.trajectory=o,r.snapshot?.(e.trajectory));return}case"step":{let o=n.step;o&&(e.steps.push(o),r.step?.(o,Number(n.seq??e.steps.length)));return}case"result":{let o=n.result;o&&(e.summary=o,r.finished?.(o));return}case"insight":{let o=n.insight;o&&(e.insight=o,r.scored?.(o));return}default:return}}async function Vo(e,t,n){for(let r=0;;r++){let o;try{let s=await fetch(`${e}/experiment/v1/runs?pageSize=50`,{headers:{authorization:`Bearer ${t}`}});if(!s.ok)return;o=(await s.json()).results?.find(a=>a.id===n)}catch{return}if(!o)return;if(o.total_tokens!=null||o.cost_usd!=null)return{totalTokens:o.total_tokens??void 0,inputTokens:o.input_tokens??void 0,outputTokens:o.output_tokens??void 0,cacheReadTokens:o.cache_read_tokens??void 0,cacheCreationTokens:o.cache_creation_tokens??void 0,costUsd:o.cost_usd??void 0};if(r>0)return;await Q(1200)}}async function pt(e,t={}){let n=(e.baseUrl??process.env.ORA_PLATFORM_URL??dn).replace(/\/+$/,""),r=e.apiKey??process.env.ORA_API_KEY;if(!r)throw new Error("Missing ORA_API_KEY. Set it in your environment or a local .env file (see .env.example).");let o=await Ne(n,r),s=await Ko(n,o,e),i={runId:s.runId,intent:e.intent,domain:e.domain,harness:e.harness};if(s.status==="succeeded"&&!s.streamUrl)return{...i,steps:[],trajectory:[]};t.opened?.(s.runId);let a=await qo(n,o,s.streamUrl??`/experiment/v1/runs/${s.runId}/stream`,t,e.idleMs??Go),c=a.summary?await Vo(n,o,s.runId):void 0;return{...i,result:a.summary,insight:a.insight,usage:c,steps:a.steps,trajectory:a.trajectory}}var k=class extends Error{constructor(n,r){super(r);this.code=n;this.name="ProtocolError"}code},S={frameTooShort:"FRAME_TOO_SHORT",frameTooLarge:"FRAME_TOO_LARGE",frameLengthMismatch:"FRAME_LENGTH_MISMATCH",unknownFrameType:"UNKNOWN_FRAME_TYPE",badJson:"BAD_JSON",badPayload:"BAD_PAYLOAD",handshakeTimeout:"HANDSHAKE_TIMEOUT",handshakeProtocol:"HANDSHAKE_PROTOCOL",maxStreams:"MAX_STREAMS",streamClosed:"STREAM_CLOSED",streamReset:"STREAM_RESET",forwardError:"FORWARD_ERROR",connectionClosed:"CONNECTION_CLOSED",superseded:"SUPERSEDED",timeout:"TIMEOUT"};function mn(e,t){return e.safeParse(t)}var U=class extends Error{};function te(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new U(`${t}: expected object`);return e}function ee(e,t,n=0,r=Number.POSITIVE_INFINITY){if(typeof e!="string")throw new U(`${t}: expected string`);if(e.length<n)throw new U(`${t}: expected at least ${n} characters`);if(e.length>r)throw new U(`${t}: expected at most ${r} characters`);return e}function le(e,t,n,r=Number.POSITIVE_INFINITY){if(typeof e!="number"||!Number.isInteger(e))throw new U(`${t}: expected integer`);if(e<n||e>r)throw new U(`${t}: expected ${n}..${r}`);return e}function hn(e,t){if(e===void 0)return{};let n={};for(let[r,o]of Object.entries(te(e,t)))if(typeof o=="string")n[r]=o;else if(Array.isArray(o)&&o.every(s=>typeof s=="string"))n[r]=o;else throw new U(`${t}.${r}: expected string or string[]`);return n}function ue(e){return{safeParse(t){try{return{success:!0,data:e(t)}}catch(n){if(n instanceof U)return{success:!1,error:{message:n.message}};throw n}}}}function gn(e,t){let n=te(e,t);if(n.protocol!=="http")throw new U(`${t}.protocol: expected "http"`);return{protocol:"http",host:ee(n.host,`${t}.host`,1),port:le(n.port,`${t}.port`,1,65535)}}var gc=ue(e=>gn(e,"target")),fc=ue(e=>{let t=te(e,"hello");return{agentVersion:ee(t.agentVersion,"hello.agentVersion",1,64),target:gn(t.target,"hello.target"),maxStreams:t.maxStreams===void 0?32:le(t.maxStreams,"hello.maxStreams",1,256)}}),fn=ue(e=>{let t=te(e,"helloAck");return{tunnelId:ee(t.tunnelId,"helloAck.tunnelId",1),heartbeatMs:le(t.heartbeatMs,"helloAck.heartbeatMs",1),maxStreams:le(t.maxStreams,"helloAck.maxStreams",1),maxFrame:le(t.maxFrame,"helloAck.maxFrame",1)}}),yn=ue(e=>{let t=te(e,"open"),n=ee(t.path,"open.path");if(!n.startsWith("/"))throw new U('open.path: expected a path starting with "/"');let r={method:ee(t.method,"open.method",1,16),path:n,headers:hn(t.headers,"open.headers")};if(t.hasBody!==void 0){if(typeof t.hasBody!="boolean")throw new U("open.hasBody: expected boolean");r.hasBody=t.hasBody}return r}),wn=ue(e=>{let t=te(e,"responseHeaders");return{status:le(t.status,"responseHeaders.status",100,599),headers:hn(t.headers,"responseHeaders.headers")}});function bn(e){return ue(t=>{let n=te(t,e);return{code:ee(n.code,`${e}.code`,1,64),message:n.message===void 0?"":ee(n.message,`${e}.message`,0,1024)}})}var vn=bn("reset"),Sn=bn("goaway");var ne=9,Se=64*1024,re=0,de=(c=>(c[c.Hello=1]="Hello",c[c.HelloAck=2]="HelloAck",c[c.Open=16]="Open",c[c.Headers=17]="Headers",c[c.Data=18]="Data",c[c.End=19]="End",c[c.Reset=20]="Reset",c[c.Goaway=32]="Goaway",c))(de||{}),Xo=new Set(Object.values(de).filter(e=>typeof e=="number"));function xn(e,t=Se){if(e.payload.byteLength>t)throw new k(S.frameTooLarge,`frame payload ${e.payload.byteLength} exceeds max ${t}`);let n=new Uint8Array(ne+e.payload.byteLength),r=new DataView(n.buffer);return r.setUint8(0,e.type),r.setUint32(1,e.streamId,!1),r.setUint32(5,e.payload.byteLength,!1),n.set(e.payload,ne),n}function An(e,t=Se){if(e.byteLength<ne)throw new k(S.frameTooShort,`frame is ${e.byteLength} bytes, header alone is ${ne}`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=n.getUint8(0);if(!Xo.has(r))throw new k(S.unknownFrameType,`unknown frame type 0x${r.toString(16)}`);let o=n.getUint32(1,!1),s=n.getUint32(5,!1);if(s>t)throw new k(S.frameTooLarge,`declared payload ${s} exceeds max ${t}`);if(e.byteLength!==ne+s)throw new k(S.frameLengthMismatch,`declared payload ${s} but message carries ${e.byteLength-ne}`);return{type:r,streamId:o,payload:e.subarray(ne)}}var $n="ora-tunnel.v1",kn=Se,zo=new TextEncoder,Qo=new TextDecoder,xe=class{constructor(t=Se){this.maxFrame=t}maxFrame;subprotocol=$n;encode(t){return xn(t,this.capFor(t.type))}decode(t){let n=An(t,Math.max(this.maxFrame,kn)),r=this.capFor(n.type);if(n.payload.byteLength>r)throw new k(S.frameTooLarge,`payload ${n.payload.byteLength} exceeds max ${r} for frame type 0x${n.type.toString(16)}`);return n}encodeJson(t,n,r){return this.encode({type:t,streamId:n,payload:zo.encode(JSON.stringify(r))})}decodeJson(t,n){let r;try{r=JSON.parse(Qo.decode(t.payload))}catch{throw new k(S.badJson,"frame payload is not valid JSON")}let o=mn(n,r);if(!o.success)throw new k(S.badPayload,o.error.message);return o.data}capFor(t){return t===18?this.maxFrame:kn}};var En=1e4;function Rn(e,t,n,r,o){return new Promise((s,i)=>{let a=!1,c=u=>{a||(a=!0,clearTimeout(l),u())},l=setTimeout(()=>{c(()=>{e.close(1002,S.handshakeTimeout),i(new k(S.handshakeTimeout,`no handshake frame within ${o}ms`))})},o);l.unref?.(),e.onError(u=>c(()=>i(u))),e.onClose((u,d)=>c(()=>i(new k(S.connectionClosed,`connection closed during handshake (${u}${d?`: ${d}`:""})`)))),e.onMessage(u=>{c(()=>{try{let d=t.decode(u);if(d.streamId!==re||d.type!==n)throw new k(S.handshakeProtocol,`expected handshake frame 0x${n.toString(16)}, got 0x${d.type.toString(16)} on stream ${d.streamId}`);s(t.decodeJson(d,r))}catch(d){e.close(1002,S.handshakeProtocol),i(d)}})})})}var je=class{constructor(t,n,r,o){this.id=t;this.codec=n;this.writer=r;this.onFinalized=o}id;codec;writer;onFinalized;localEnded=!1;remoteEnded=!1;resetPayload=null;handlers={};cancellation=new AbortController;get signal(){return this.cancellation.signal}get isFinalized(){return this.resetPayload!==null||this.localEnded&&this.remoteEnded}setHandlers(t){Object.assign(this.handlers,t)}sendData(t){this.assertWritable();let n=this.codec.maxFrame;for(let r=0;r<t.byteLength;r+=n)this.writer.writeFrame(this.codec.encode({type:18,streamId:this.id,payload:t.subarray(r,Math.min(r+n,t.byteLength))}))}sendHeaders(t){this.assertWritable(),this.writer.writeFrame(this.codec.encodeJson(17,this.id,t))}sendEnd(){this.localEnded||this.resetPayload||(this.localEnded=!0,this.writer.writeFrame(this.codec.encode({type:19,streamId:this.id,payload:new Uint8Array(0)})),this.maybeFinalize())}sendReset(t,n=""){if(this.resetPayload)return;let r={code:t,message:n};this.resetPayload=r;try{this.writer.writeFrame(this.codec.encodeJson(20,this.id,r))}finally{this.notifyReset(r)}}receive(t){if(!this.resetPayload)switch(t.type){case 17:this.handlers.onHeaders?.(this.codec.decodeJson(t,wn));return;case 18:if(this.remoteEnded)return;this.handlers.onData?.(t.payload);return;case 19:if(this.remoteEnded)return;this.remoteEnded=!0,this.handlers.onEnd?.(),this.maybeFinalize();return;case 20:{let n=this.codec.decodeJson(t,vn);this.resetPayload=n,this.notifyReset(n);return}default:throw new k(S.badPayload,`frame type 0x${t.type.toString(16)} is not valid on an open stream`)}}failLocally(t){this.resetPayload||(this.resetPayload=t,this.notifyReset(t))}notifyReset(t){this.cancellation.abort(new k(S.streamReset,`${t.code}: ${t.message}`)),this.handlers.onReset?.(t),this.onFinalized(this)}assertWritable(){if(this.resetPayload)throw new k(S.streamReset,`stream ${this.id} was reset (${this.resetPayload.code})`);if(this.localEnded)throw new k(S.streamClosed,`stream ${this.id} already ended locally`)}maybeFinalize(){this.localEnded&&this.remoteEnded&&this.onFinalized(this)}};var Ue=class{constructor(t,n){this.socket=t;this.opts=n}socket;opts;streams=new Map;nextStreamId=1;goingAway=!1;closed=!1;start(){this.socket.onMessage(t=>this.handleMessage(t)),this.socket.onClose((t,n)=>this.teardown(new k(S.connectionClosed,`connection closed (${t}${n?`: ${n}`:""})`))),this.socket.onError(t=>this.teardown(new k(S.connectionClosed,t.message)))}get activeStreamCount(){return this.streams.size}openStream(t){if(this.closed||this.goingAway)throw new k(S.connectionClosed,"connection is closed or draining");if(this.streams.size>=this.opts.maxStreams)throw new k(S.maxStreams,`stream cap ${this.opts.maxStreams} reached`);let n=this.createStream(this.nextStreamId);return this.nextStreamId+=2,this.socket.send(this.opts.codec.encodeJson(16,n.id,t)),n}goaway(t,n=""){this.closed||this.goingAway||(this.goingAway=!0,this.socket.send(this.opts.codec.encodeJson(32,re,{code:t,message:n})))}close(t,n){this.socket.close(t,n)}handleMessage(t){let n;try{n=this.opts.codec.decode(t),this.dispatch(n)}catch(r){if(r instanceof k){this.goaway(r.code,r.message),this.close(1002,r.code),this.teardown(r);return}throw r}}dispatch(t){if(t.streamId===re){t.type===32&&(this.goingAway=!0,this.opts.onGoaway?.(this.opts.codec.decodeJson(t,Sn)));return}if(t.type===16){this.handleOpen(t);return}let n=this.streams.get(t.streamId);if(!n){t.type!==19&&t.type!==20&&this.socket.send(this.opts.codec.encodeJson(20,t.streamId,{code:S.streamClosed,message:"unknown stream"}));return}n.receive(t)}handleOpen(t){if(!this.opts.onOpen){this.socket.send(this.opts.codec.encodeJson(20,t.streamId,{code:S.badPayload,message:"this side does not accept streams"}));return}if(this.goingAway)return;let n=this.opts.codec.decodeJson(t,yn);if(this.streams.size>=this.opts.maxStreams){this.socket.send(this.opts.codec.encodeJson(20,t.streamId,{code:S.maxStreams,message:`stream cap ${this.opts.maxStreams} reached`}));return}let r=this.createStream(t.streamId);this.opts.onOpen(r,n)}createStream(t){let n={writeFrame:o=>this.socket.send(o)},r=new je(t,this.opts.codec,n,o=>this.streams.delete(o.id));return this.streams.set(t,r),r}teardown(t){if(!this.closed){this.closed=!0;for(let n of[...this.streams.values()])n.failLocally({code:t.code,message:t.message});this.streams.clear(),this.opts.onConnectionClosed?.(t)}}};var De=class{constructor(t){this.onCancel=t}onCancel;buffered=[];pending=null;ended=!1;error=null;cancelled=!1;push(t){if(!(this.ended||this.error)){if(this.pending){let n=this.pending;this.pending=null,n.resolve({value:t,done:!1});return}this.buffered.push(t)}}end(){if(!(this.ended||this.error)&&(this.ended=!0,this.pending&&this.buffered.length===0)){let t=this.pending;this.pending=null,t.resolve({value:void 0,done:!0})}}fail(t){if(!(this.ended||this.error)&&(this.error=t,this.buffered.length=0,this.pending)){let n=this.pending;this.pending=null,n.reject(t)}}[Symbol.asyncIterator](){let t=!1,n=()=>{t||this.cancelled||(this.cancelled=!0,this.ended=!0,this.error=null,this.buffered.length=0,this.pending?.resolve({value:void 0,done:!0}),this.pending=null,this.onCancel?.())};return{next:()=>this.buffered.length>0?Promise.resolve({value:this.buffered.shift(),done:!1}):this.error?Promise.reject(this.error):this.ended?(t=!0,Promise.resolve({value:void 0,done:!0})):new Promise((r,o)=>{this.pending={resolve:s=>{s.done&&(t=!0),r(s)},reject:o}}),return:async()=>(n(),{value:void 0,done:!0}),throw:async r=>{throw n(),r}}}};function _n(e){let t=new De;return e.setHandlers({onData:n=>t.push(Uint8Array.from(n)),onEnd:()=>t.end(),onReset:n=>t.fail(new k(S.streamReset,`${n.code}: ${n.message}`))}),t}async function Tn(e,t){try{for await(let n of t)e.sendData(n);e.sendEnd()}catch(n){throw e.sendReset(S.forwardError,n instanceof Error?n.message:String(n)),n}}var Ae=class{constructor(t){this.opts=t}opts;mux=null;async start(){if(this.mux)throw new Error("connector already started");let{socket:t,codec:n,hello:r}=this.opts,o=Rn(t,n,2,fn,this.opts.handshakeTimeoutMs??En);t.send(n.encodeJson(1,re,r));let s=await o;return this.mux=new Ue(t,{codec:n,maxStreams:s.maxStreams,onOpen:(i,a)=>{this.serve(i,a)},onGoaway:this.opts.onGoaway,onConnectionClosed:this.opts.onConnectionClosed}),this.mux.start(),s}get activeStreamCount(){return this.mux?.activeStreamCount??0}close(t,n){(this.mux??this.opts.socket).close(t,n)}async serve(t,n){try{let r=await this.opts.forwarder.forward({method:n.method,path:n.path,headers:n.headers,body:_n(t),hasBody:n.hasBody,signal:t.signal});t.sendHeaders({status:r.status,headers:r.headers}),await Tn(t,r.body)}catch(r){try{t.sendReset(S.forwardError,r instanceof Error?r.message:String(r))}catch{}}}};var ht="tunnels:write + tunnels:connect",gt=[`--tunnel ora needs ORA_API_KEY: an ora platform key (ora_sk_...) with the ${ht} scopes.`,"Create one at https://agentfront.sh (API keys), export it or put it in a local .env,","or bring your own tunnel instead: --tunnel-cmd 'ngrok http 3000 --log stdout'"].join(`
|
|
24
|
-
`),
|
|
25
|
-
(--tunnel ora needs a platform key with the ${ht} scopes)`)}if(t.signal?.aborted)throw mt();let i=await
|
|
26
|
-
`)))),l=u=>{let{code:d,reason:
|
|
27
|
-
`;function
|
|
28
|
-
`))
|
|
29
|
-
`)}else{console.log(""),console.log(wt.default.yellow(` ${at}`));let p=
|
|
30
|
-
`);else for(let
|
|
31
|
-
`)
|
|
32
|
-
`);let
|
|
33
|
-
|
|
34
|
-
`);for(;
|
|
35
|
-
|
|
36
|
-
`),!g)continue;let f;try{f=JSON.parse(g.data)}catch{continue}if(g.event==="trajectory"){let
|
|
37
|
-
`;t.length<this.rows&&(n+="\x1B[0J"),this.rows=t.length,process.stdout.write(n)}pulse(){!this.live||this.rows===0||(this.beat++,process.stdout.write(`\x1B[${this.rows}A\r\x1B[2K${this.banner()}\x1B[${this.rows}B\r`))}};var
|
|
18
|
+
`)}:null}async function Xo(e,t,n,r,o){let s=n.startsWith("http")?n:`${e}${n}`,i=z(o),a=await fetch(s,{headers:{authorization:`Bearer ${t}`,accept:"text/event-stream"},signal:i.signal});if(!a.ok||!a.body)throw i.disarm(),new Error(`ora run stream failed (${a.status})`);let c=new TextDecoder,l={steps:[],trajectory:[]},u="";try{e:for await(let d of a.body){i.poke(),u=`${u}${c.decode(d,{stream:!0})}`.replace(/\r\n?/g,`
|
|
19
|
+
`);let m=u.indexOf(`
|
|
20
|
+
|
|
21
|
+
`);for(;m!==-1;){let g=dt(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 Qo(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??un).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 Vo(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 Xo(n,o,s.streamUrl??`/experiment/v1/runs/${s.runId}/stream`,t,e.idleMs??Yo),c=a.summary?await Qo(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 pn(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 mn(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 hn(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=>hn(e,"target")),xc=ue(e=>{let t=te(e,"hello");return{agentVersion:ee(t.agentVersion,"hello.agentVersion",1,64),target:hn(t.target,"hello.target"),maxStreams:t.maxStreams===void 0?32:le(t.maxStreams,"hello.maxStreams",1,256)}}),gn=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)}}),fn=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:mn(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}),yn=ue(e=>{let t=te(e,"responseHeaders");return{status:le(t.status,"responseHeaders.status",100,599),headers:mn(t.headers,"responseHeaders.headers")}});function wn(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 bn=wn("reset"),vn=wn("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||{}),Zo=new Set(Object.values(de).filter(e=>typeof e=="number"));function Sn(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 xn(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(!Zo.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 kn="ora-tunnel.v1",An=Se,es=new TextEncoder,ts=new TextDecoder,xe=class{constructor(t=Se){this.maxFrame=t}maxFrame;subprotocol=kn;encode(t){return Sn(t,this.capFor(t.type))}decode(t){let n=xn(t,Math.max(this.maxFrame,An)),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:es.encode(JSON.stringify(r))})}decodeJson(t,n){let r;try{r=JSON.parse(ts.decode(t.payload))}catch{throw new k(S.badJson,"frame payload is not valid JSON")}let o=pn(n,r);if(!o.success)throw new k(S.badPayload,o.error.message);return o.data}capFor(t){return t===18?this.maxFrame:An}};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,yn));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,bn);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,vn)));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,fn);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 $n(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 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,gn,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
|
+
`),ns=1,rs=32,mt=()=>new T("interrupted before the tunnel was ready");function os(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 On(e,t={}){let n=os(e),r=t.apiKey??process.env.ORA_API_KEY;if(!r)throw new T(gt);let o=dn(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 ${ht} scopes)`)}if(t.signal?.aborted)throw mt();let i=await is(o,s),a=()=>cs(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(mt()),t.signal?.addEventListener("abort",()=>C(mt()),{once:!0})}),f;try{f=ss(i),c=await Promise.race([ls(f,s),g]),l=new Ae({socket:us(c),codec:new xe,hello:{agentVersion:`ax/${we.version}`,target:{protocol:"http",host:n.host,port:n.port},maxStreams:rs},forwarder:ps(n.host,n.port),onConnectionClosed:x=>{u||d(new T(`ora tunnel connection dropped: ${x.message}`))}}),await Promise.race([l.start(),g]),await ut(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 ss(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 is(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,_n.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(`${as(n.status)}${s?`: ${s}`:""}`)}if(!o.id)throw new T("ora created a tunnel but returned no id");return o}function as(e){switch(e){case 401:return"ora rejected the platform key (401). Check ORA_API_KEY";case 403:return`the platform key lacks the ${ht} scopes (403). Issue one with both and retry`;case 429:return"ora rate-limited the tunnel request (429). Wait a moment and retry";default:return`ora could not create a tunnel (${e})`}}async function cs(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 ls(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 us(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===ns&&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 ds=new Set(["host","connection","keep-alive","transfer-encoding","upgrade","te"]);function ps(e,t){return{forward:n=>new Promise((r,o)=>{let s=(0,Pn.request)({host:e,port:t,path:n.path,method:n.method,headers:hs(n.headers)},i=>r({status:i.statusCode??502,headers:gs(i),body:i}));s.on("error",o),ms(n.body,s).catch(i=>{s.destroy(i instanceof Error?i:new Error(String(i))),o(i)})})}}async function ms(e,t){try{for await(let n of e)t.write(n)||await(0,Cn.once)(t,"drain")}finally{t.end()}}function hs(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!ds.has(t.toLowerCase())))}function gs(e){let t={};for(let[n,r]of Object.entries(e.headers))r!==void 0&&(t[n]=r);return t}var ft=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 fs=80,De,yt=0,ke="";function ys(){let e=ft.default.cyan(pe[yt%pe.length]),t=Math.max(10,(process.stderr.columns??80)-2),n=ke.length>t?`${ke.slice(0,t-1)}\u2026`:ke;process.stderr.write(`\r\x1B[K${e} ${ft.default.dim(n)}`),yt++}var R={start(e){R.stop(),yt=0,ke=e,process.stderr.isTTY&&(De=setInterval(ys,fs))},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},In=`--min-score skipped: the MCP handshake requires credentials, so the target is unscored
|
|
27
|
+
`;function Mn(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 ws(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 bs(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 vs(e){let t=e?.mcpUrl;return typeof t=="string"&&t?t:void 0}async function Nn(e){let t=ws(e.url);if(!t)return console.error(`Not a scannable URL or domain: ${JSON.stringify(e.url)}`),E.USAGE;let n=Mn(e.minScore,"--min-score",0,100),r=Mn(e.maxAge,"--max-age",0,86400);for(let h of[n,r])if(h.error)return console.error(h.error),E.USAGE;let o=bs(e);if("error"in o)return console.error(o.error),E.USAGE;let s=o.kind!=="none";if(!s&<(t))return console.error([`${t} only exists on this machine, and ora audits public URLs.`,"Either audit a publicly reachable deployment of this site (e.g. a preview URL),","or run it through a tunnel:"," ax audit localhost:3000 --tunnel ora # ora's own tunnel; needs ORA_API_KEY"," ax audit localhost:3000 --tunnel-cmd 'ora tunnel 3000 --access public'"," ax audit localhost:3000 --tunnel-cmd 'ngrok http 3000 --log stdout'","Any command that prints a public https URL works; the result is stored as","ephemeral (excluded from rankings, deleted after 7 days)."].join(`
|
|
28
|
+
`)),E.USAGE;if(o.kind==="ora"&&!process.env.ORA_API_KEY)return console.error(gt),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"?On(t,{signal:l.signal}):ln(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=en(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(),Qt(h)){if(e.json){let p=h.payload===void 0?{code:h.code,message:h.message}:h.payload;process.stdout.write(`${JSON.stringify(p,null,2)}
|
|
29
|
+
`)}else{console.log(""),console.log(wt.default.yellow(` ${at}`));let p=vs(h.payload);p&&console.log(wt.default.dim(` MCP endpoint: ${p}`)),console.log("")}return n.value!==void 0&&process.stderr.write(In),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 sn(nn(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(In),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 Ss="https://ora.ai",xs=12e4,As=5e3,ks=180,Es=15*6e4,Rs=6e4,$s=5,Ts=2e3,_=class extends Error{},Ee=class extends _{constructor(n,r,o){super(n);this.status=r;this.retryAfterMs=o}status;retryAfterMs};function bt(e){return(e??process.env.ORA_API_URL??Ss).replace(/\/+$/,"")}async function vt(e){let t;try{t=await fetch(e,{headers:{accept:"application/json"},signal:AbortSignal.timeout(15e3)})}catch(n){let r=n instanceof Error?n.message:String(n);throw new _(`ora request failed: ${r}`)}if(!t.ok)throw new _(`ora request failed: ${await ce(t)}`);return await t.json()}function jn(e){return vt(`${bt(e)}/api/journey/intents`)}function Un(e){return vt(`${bt(e)}/api/journey/agents`)}function _s(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 Cs(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 ${St(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:_s(o)}}function St(e){if(!Number.isFinite(e)||e<=0)return"soon";let t=e/36e5;if(t>=1)return`${Math.ceil(t)}h`;let n=e/6e4;return n>=1?`${Math.ceil(n)}m`:`${Math.ceil(e/1e3)}s`}function Ps(e){if(!e)return"starting\u2026";if(e.type==="text")return"thinking\u2026";if(e.action==="search")return e.search_query?`searching \u201C${Ln(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} ${Ln(t,48)}`:`${n}\u2026`}function Ln(e,t){return e.length>t?`${e.slice(0,t-1)}\u2026`:e}async function Os(e,t,n){let r=t.startsWith("http")?t:`${e}${t}`,o=n.idleMs??xs,s=z(o),i=()=>new _(`ora journey stream timed out \u2014 no frames for ${Math.round(o/1e3)}s`),a;try{a=await fetch(r,{headers:{accept:"text/event-stream",...n.apiKey?{authorization:`Bearer ${n.apiKey}`}:{}},signal:s.signal})}catch(d){if(s.disarm(),s.tripped())throw i();let m=d instanceof Error?d.message:String(d);throw new _(`ora journey stream failed: ${m}`)}if(!a.ok||!a.body){s.disarm();let d=Number(a.headers.get("retry-after"));throw new Ee(`ora journey stream failed (${a.status}): ${await ce(a)}`,a.status,Number.isFinite(d)&&d>0?d*1e3:void 0)}let c=new TextDecoder,l={},u="";try{e:for await(let d of a.body){s.poke(),u=`${u}${c.decode(d,{stream:!0})}`.replace(/\r\n?/g,`
|
|
32
|
+
`);let m=u.indexOf(`
|
|
33
|
+
|
|
34
|
+
`);for(;m!==-1;){let g=dt(u.slice(0,m));if(u=u.slice(m+2),m=u.indexOf(`
|
|
35
|
+
|
|
36
|
+
`),!g)continue;let f;try{f=JSON.parse(g.data)}catch{continue}if(g.event==="trajectory"){let h=f.steps??[],p=h.filter(y=>y.type==="tool_call").at(-1);n.progress?.(`step ${h.length} \xB7 ${Ps(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 Is(e,t,n,r){let o=n.reopenPauseMs??Ts,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 Os(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,Rs)}}}throw s??new _("ora journey stream was never opened")}function Fe(e,t){return vt(`${e}/api/journey/runs/${encodeURIComponent(t)}`)}async function Ms(e,t,n,r){let o=n.pollEveryMs??As,s=n.pollLimit??ks,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 Wn(e,t){let n=bt(t.baseUrl);t={...t,apiKey:t.apiKey||process.env.ORA_PARTNER_API_KEY||process.env.ORA_SCAN_API_KEY||void 0};let r=await Cs(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??Es),l=t.noStream?{...t,onTrajectory:void 0}:t;try{s=await Is(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 Ms(n,o.id,t,c)}}let a=await Ns(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 Ns(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 xt(e){if(!e)return{};let t=e.match(/https?:\/\/([^/\s]+)(\/\S*)?/i);return t?{host:t[1],path:t[2]??"/"}:{}}function se(e){return/search/i.test(`${e.tool??""} ${e.action??""}`)}function Ls(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 js(e,t){if(se(e)){let c=e.input_display??String(e.input?.query??"search"),l=e.output_structured?.links?.length;return{id:e.id,kind:"search",icon:"\u{1F50D}",label:oe(`"${c}"`,t),meta:l?`${l} results`:void 0,tone:"ok",notes:[],children:[]}}let{host:n,path:r}=xt(e.input_display??String(e.input?.url??"")),o=e.status,s=o!=null&&o>=300&&o<400,i=!!e.is_error||o!=null&&o>=400,a;if(s)a=`\u21B3 ${o}`;else if(i)a=`\u2717 ${o??"error"}`;else{let c=["\u2713"];o&&c.push(String(o)),e.duration_ms&&c.push(`${(e.duration_ms/1e3).toFixed(1)}s`),a=c.join(" ")}return{id:e.id,kind:"fetch",icon:Ls(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=js(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 Us(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 Dn=e=>P.default.dim(`(\u2026) ${e}`);function Fn(e,t){let{frame:n,ink:r}=Us(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(Dn);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=Fn(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=Fn(e.root,!1);return e.looseNotes.length&&(t.push(""),t.push(...e.looseNotes.map(Dn))),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},Ws="public caps: 100 runs/24h per target \xB7 20 runs/24h per IP",Ds="keyed caps: 1000 runs/24h per key \xB7 no per-target cap",Fs={id:"cas-haiku",label:"Claude Code",variant:"Haiku 4.5",harness:"claude-agent-sdk",model:"claude-haiku-4-5",blurb:"Fast, frugal navigator \u2014 the CLI default."};function At(e){return console.error(b.default.red(`ax deep-journey: ${e}`)),q.API}function Bs(e,t){if(t==="failed")return b.default.red("\u2717 run failed");switch(e){case"satisfied":return b.default.green("\u2713 task satisfied");case"partial":return b.default.yellow("\u25D0 partially satisfied");case"unsatisfied":return b.default.red("\u2717 task not satisfied");default:return b.default.dim("\xB7 not gradable")}}function kt(e){return`${e.label} \xB7 ${e.variant}`}function Bn(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 Jn(e,t,n){return[` ${Je(e)}`,"",...He(Be(e,t,n)).map(r=>` ${r}`)]}var Js=e=>e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e);function Hs(e){return e<.01?`$${e.toFixed(4)}`:e<1?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function Gs(e){if(!e)return;let{input_tokens:t,output_tokens:n}=e;if(!(t==null&&n==null))return(t??0)+(n??0)}function Ks(e){return(e?.trajectory?.steps??[]).filter(t=>t.action==="search").length}function Et(e,t,n){return e>=t?b.default.green:e>=n?b.default.yellow:b.default.red}function qs(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:Et(s,70,40)})}if(t?.answer_efficiency!=null){let s=Math.round(t.answer_efficiency*100);o.push({label:"answer efficiency",pct:s,paint:Et(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:Et(i,70,35)})}return o}function Ys(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 Rt(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 Vs(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(Rt(`${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=>Rt(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]??Rt("",s,b.default.dim))));return d}function Hn(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 Xs(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=qs(e);if(o.length){let c=Vs(o,t);if(c)r.push(...c);else{r.push("");for(let l of o)r.push(Ys(l))}}let s=n?.answer_basis;s&&s.sections_total>0&&r.push(...Hn("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(...Hn("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 Qs(e,t){let n=Z(60,120),{detail:r}=e,o=r.result,s=["",Xs(n),""];s.push(` ${Bs(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??Ks(o);a&&i.push(`${a} search${a===1?"":"es"}`),o?.duration_ms!=null&&i.push(`${(o.duration_ms/1e3).toFixed(1)}s`);let c=Gs(o);if(c!=null&&i.push(`${Js(c)} tokens`),o?.cost_usd!=null&&i.push(Hs(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 Gn(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:jn(),Un()]);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
|
-
`)}`),
|
|
40
|
-
${C.map(
|
|
41
|
-
`)}`),
|
|
42
|
-
`}var
|
|
43
|
-
`):console.error(`generate-files failed: ${
|
|
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:[Fs,...y.agents],Re=C.find(L=>L.harness==="claude-agent-sdk"&&/haiku/i.test(L.model))?.id??y.defaultId,$e=e.agent??Re,Ut=C.find(L=>L.id===$e);if(!Ut)return console.error(`ax deep-journey: unknown agent "${$e}". Available agents:
|
|
40
|
+
${C.map(L=>` ${L.id.padEnd(12)} ${kt(L)}`).join(`
|
|
41
|
+
`)}`),q.USAGE;i=Ut}catch(p){return At(p instanceof Error?p.message:String(p))}e.json||console.error(b.default.dim(o?Ds:Ws));let c=n&&!e.noStream,l=new me,u=[],d=`waking ${i.label}`,m=()=>l.draw(Jn(u,a,!1),d);c?(console.log(),console.log(` ${b.default.cyan("\u25B6")} ${b.default.bold(t)} ${b.default.dim("\xB7")} ${b.default.dim(kt(i))} ${b.default.dim("\xB7")} ${b.default.dim(r?"custom task":s??"default")}`),console.log(),l.open(),m()):n&&R.start(`Sending ${kt(i)} to ${t} (${r?`"${r}"`:s})`);let g=p=>{c?(d=p,m()):n&&R.update(p)},f;try{f=await Wn(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(Bn),m()}:void 0})}catch(p){return c?l.close():n&&R.stop(),p instanceof _?At(p.message):At(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 ${St(f.retryAfterMs)})`:""}.`)):f.allowance.remaining!==void 0&&f.allowance.limit!==void 0&&console.error(b.default.dim(`allowance: ${f.allowance.remaining} of ${f.allowance.limit} target runs left in the 24h window`));let h=(f.detail.result?.trajectory?.steps??[]).map(Bn);if(h.length){console.log();for(let p of Jn(h,a,!0))console.log(p)}for(let p of Qs(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 Zs="https://ora.ai",ei=3e4,Y=class extends Error{status;payload;constructor(t,n={}){super(t),this.name="AgentFilesApiError",this.status=n.status??null,this.payload=n.payload}},ti=/^[a-z0-9._-]+$/;function ni(e){if(!e.startsWith("/"))return!1;let t=e.slice(1).split("/");return t.length>=1&&t.length<=6&&t.every(n=>ti.test(n)&&n!=="."&&n!=="..")}function Kn(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t--;return e.slice(0,t)}function ri(e){return Kn(e.trim().replace(/^https?:\/\//i,""))}async function qn(e,t={}){let n=Kn(t.baseUrl??process.env.ORA_API_URL??Zs),r=`${n}/api/agent-files/${encodeURIComponent(ri(e))}?include=all`,o;try{o=await fetch(r,{headers:{accept:"application/json"},signal:AbortSignal.timeout(ei)})}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(!ni(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 oi(e){return typeof e.body=="string"?e.body:`${JSON.stringify(e.content,null,2)}
|
|
42
|
+
`}var si=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"]]]),ii="/server-card";function ai(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 ci(e,t){let n=(0,F.resolve)(t),r={writes:[],elsewhere:[],unknown:[]};for(let o of e.files){if(!ai(o,e.domain)){r.elsewhere.push(o);continue}let s=si.get(o.path);if(s)r.writes.push({target:(0,F.join)(n,...s),file:o});else if(o.path.endsWith(ii)){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 Yn(e,t=process.cwd()){let n=(0,F.relative)(t,e);return n&&!n.startsWith("..")&&!(0,F.isAbsolute)(n)?n:e}function li(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 Vn(e){if(!e.domain?.trim())return console.error("Usage: ax generate-files <domain>"),E.USAGE;let t;try{t=await qn(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}=ci(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(` ${Yn(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,oi(l));let a=c=>{for(let l of c){let[u,...d]=li(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")} ${Yn(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 ui(e){if(e.type==="tool_call"){let t=e.input_display??e.summary??"";if(se(e))return t?`searching ${oe(t,40)}`:"searching\u2026";let{host:n}=xt(t);return n?`fetching ${n}`:"fetching\u2026"}return e.type==="text"&&e.kind==="reasoning"?"deciding next step\u2026":e.type==="text"?"writing the answer\u2026":"working\u2026"}var di=e=>e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e);function pi(e){return e<.01?`$${e.toFixed(4)}`:e<1?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function mi(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(`${di(t.totalTokens)} tokens`),t?.costUsd!=null&&r.push(pi(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 hi(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 gi(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 fi(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")} ${hi(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(` ${gi(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 yi(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 Xn(e){let t={intent:e.intent,domain:e.domain,harness:e.harness,model:e.model};if(e.json)try{let i=await pt(t);return process.stdout.write(`${yi(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 pt(t,{snapshot:a=>{r=a;let c=a[a.length-1];n.draw(s(),c?ui(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 mi(i.result,i.usage))console.log(a);if(i.insight)for(let a of fi(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"),Tt=require("path"),ge=B(D(),1);var Qn=require("crypto"),wi="https://ora.ai",H=class extends Error{};function Zn(e){return(e??process.env.ORA_API_URL??wi).replace(/\/+$/,"")}async function $t(e){let t=Zn(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 zn(e){return`sha256:${(0,Qn.createHash)("sha256").update(e).digest("hex")}`}async function er(e,t){let n=Zn(t),r=await $t(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&&zn(a)!==o.digest)throw new H(`digest mismatch for ${e}: index says ${o.digest}, served bytes hash to ${zn(a)} - refusing to use them`);return{entry:o,bytes:a}}var bi=".claude/skills";function vi(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 tr(e){try{if(!e.name){let r=await $t();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 vi(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 er(e.name);if(e.install){let r=(0,Tt.join)(e.dir??bi,t.name);(0,qe.mkdirSync)(r,{recursive:!0});let o=(0,Tt.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"}},nr=1e4,rr=5e3,Ct=class e{socket;nextId=1;pending=new Map;handlers=new Map;closed=!1;closeReason=null;constructor(t){this.socket=t,t.addEventListener("message",n=>{this.dispatch(String(n.data))}),t.addEventListener("close",()=>{this.fail("the browser closed the DevTools connection")}),t.addEventListener("error",()=>{this.fail("the DevTools connection errored")})}static async open(t){let n=new WebSocket(t);return await new Promise((r,o)=>{let s=setTimeout(()=>{o(new $(`timed out connecting to ${t}`))},rr);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??nr;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 Ot(e,t=rr){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 Ct.open(t.webSocketDebuggerUrl),r=t.product;if(!r){let o=await n.send("Browser.getVersion").catch(()=>({}));r=typeof o.product=="string"?o.product:""}return new e(n,r.replace(/^(?:Headless)?Chrome\//i,""))}async newContext(t){let{browserContextId:n}=await this.connection.send("Target.createBrowserContext",{disposeOnDetach:!0}),{targetId:r}=await this.connection.send("Target.createTarget",{url:"about:blank",browserContextId:n}),{sessionId:o}=await this.connection.send("Target.attachToTarget",{targetId:r,flatten:!0}),s=new Pt(this.connection,o,n,t.entryUrl);return await s.prepare(t.initScripts??[],t.viewport),s}close(){this.connection.close()}},Si=8,xi=1024*1024,Ai=new Set(["Image","Media","Font"]),Pt=class{connection;sessionId;browserContextId;entryHost;currentUrl="about:blank";viewport=null;domContentFired=!1;loadFired=!1;documentResponses=new Map;scripts=[];scriptsStarted=0;pendingScriptRequests=new Map;constructor(t,n,r,o){this.connection=t,this.sessionId=n,this.browserContextId=r,this.entryHost=_t(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;(Ai.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:ki(o.headers??{})});return}if(n!=="Script"||this.scriptsStarted>=Si)return;let s=typeof o.url=="string"?o.url:"",i=_t(s);i&&(i!==this.entryHost&&i!==_t(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,xi)})}).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=nr){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 ki(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 _t(e){try{return new URL(e).host}catch{return""}}var Ei=new Set([2,3]),Ri=8192,$i=864e10;function Ti(e){if(typeof e!="string")return null;let t=e.trim();if(t.length===0||t.length>Ri)return null;let n;try{n=Buffer.from(t,"base64")}catch{return null}if(n.length<=69||!Ei.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 _i(e){let t=e.toLowerCase().replace(/[^a-z]/g,"");return t==="webmcp"||t.includes("modelcontext")}function Ci(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 or(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=Ti(s);if(!i)continue;let a=_i(i.feature),c=i.expiry*1e3>n.getTime(),l=Ci(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 sr(e){return e?e.split(",").map(t=>t.trim()).filter(t=>t.length>0):[]}var It="capture-incomplete:";function Pi(e){return e.imperative!==null||e.polyfillPackages.length>0}function ir(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||Pi(e.staticSignals)?"declared-inactive":"absent"}function ar(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 cr={"shared-experience":30,"task-completion":25,"tool-quality":25,trust:20},lr={"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 Oi(e,t,n){return!!(t["cf-mitigated"]==="challenge"||e===403&&n.includes("cf-browser-verification")||e===503&&n.includes("challenge-platform"))}function ur(e,t,n){return!!(Oi(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 Ii=100,pr=4096,Mi=32768,Ni=50,Li=200,dr="__oraWebmcpCapture",mr=`(function () {
|
|
48
48
|
"use strict";
|
|
49
49
|
try {
|
|
50
50
|
var W = typeof globalThis !== "undefined" ? globalThis : window;
|
|
51
51
|
if (W.${dr}) return;
|
|
52
52
|
|
|
53
53
|
var SHIM_VERSION = ${JSON.stringify(ie)};
|
|
54
|
-
var MAX_TOOLS = ${
|
|
54
|
+
var MAX_TOOLS = ${Ii};
|
|
55
55
|
var MAX_DESCRIPTION_CHARS = ${pr};
|
|
56
|
-
var MAX_SCHEMA_CHARS = ${
|
|
57
|
-
var MAX_ERRORS = ${
|
|
56
|
+
var MAX_SCHEMA_CHARS = ${Mi};
|
|
57
|
+
var MAX_ERRORS = ${Ni};
|
|
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
|
|
@@ -526,25 +631,26 @@ ${C.map(N=>` ${N.id.padEnd(12)} ${kt(N)}`).join(`
|
|
|
526
631
|
}
|
|
527
632
|
}
|
|
528
633
|
})();`,hr=`(function () {
|
|
529
|
-
var MAX_FORMS = ${
|
|
634
|
+
var MAX_FORMS = ${Li};
|
|
530
635
|
var MAX_DESCRIPTION_CHARS = ${pr};
|
|
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 fr=["@mcp-b/global","@mcp-b/react-webmcp","usewebmcp"];function
|
|
547
|
-
`)),s=new Set;for(let a of r){let c=a.toLowerCase();for(let l of fr)c.includes(l)&&s.add(l)}let i=gr(e)||r.some(gr);return{imperative:o,polyfillPackages:[...s],keywordMention:i}}var vr=15e3,
|
|
652
|
+
})()`;var fr=["@mcp-b/global","@mcp-b/react-webmcp","usewebmcp"];function ji(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=fr.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 Ui=["webmcp","web model context protocol"];function gr(e){let t=e.toLowerCase();return Ui.some(n=>t.includes(n))}function yr(e,t,n){let r=[t,...n.map(a=>a.body)],o=ji(r.join(`
|
|
653
|
+
`)),s=new Set;for(let a of r){let c=a.toLowerCase();for(let l of fr)c.includes(l)&&s.add(l)}let i=gr(e)||r.some(gr);return{imperative:o,polyfillPackages:[...s],keywordMention:i}}var vr=15e3,Wi=3e4,Di=2e3,Sr=250,xr={fast:5e3,deep:1e4},Fi={fast:12e3,deep:2e4},Bi=2*1024*1024,Ar=512,Ji=512,Hi=60,Gi=15e5,kr={width:1280,height:720},wr={imperative:null,polyfillPackages:[],keywordMention:!1},Ki=`(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
|
+
})()`,qi=`(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
|
+
})()`,Er=`(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
|
+
})()`,Yi=`(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 Rr(e,t){return e.filter(n=>!n.unregistered).map(n=>({name:n.name.slice(0,Ar),description:n.description,via:"imperative",entryPoint:n.source==="provideContext"?"provideContext":n.entryPoint,pageUrl:t,inputSchema:n.inputSchema,annotations:Xi(n.annotations),hasExecute:n.hasExecute,registrationMs:n.registrationMs}))}function Vi(e,t){return e.map(n=>({name:n.toolName.slice(0,Ar),description:n.toolDescription,via:"declarative",entryPoint:"form",pageUrl:t,inputSchema:null,annotations:{},hasExecute:!0,registrationMs:null}))}function Xi(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,Ji)),n}function zi(e){if(!e)return[];let t=[...e.registrationErrors];return e.takenOver.length>0&&t.push(`${It} the page replaced modelContext on ${e.takenOver.join(", ")}, so imperative tools may be under-reported`),e.extraToolCount>0&&t.push(`${It} the capture's tool cap was reached and ${e.extraToolCount} further registration attempts were not stored`),t}function Qi(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 Zi(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:kr});let c;try{c=await a.goto(t,Xe(r,vr))}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,Bi),g=await a.inlineScripts(),f=await a.evaluate(Ki).catch(()=>null)??{},h=f.nativeApi===!0,p=h?await ra(a,n,r):null,y=o?await ia(a,r):null;return{finalUrl:a.url(),navMs:l,blocked:ur(d,u,m),nativeApi:h,nativeToolCount:p,originTrialTokens:[...sr(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 ea(e,t,n,r,o){let s=null;try{s=await e.newContext({initScripts:[mr],entryUrl:t,viewport:kr});try{await s.goto(t,Xe(r,vr))}catch(l){return{snapshot:null,declarative:null,quietMs:0,loadError:Ve(l)}}let i=await ta(s,n,r,o),a=await s.evaluate(Er).catch(()=>null),c=await s.evaluate(hr).catch(()=>null);return{snapshot:a,declarative:c,quietMs:i,loadError:null}}catch(i){return{snapshot:null,declarative:null,quietMs:0,loadError:Ve(i)}}finally{await s?.close()}}async function ta(e,t,n,r){let o=Date.now(),s=Math.min(Fi[t],Math.max(0,n-o)),i=Math.min(xr[t],s),a=null,c=o,l=!1;for(;Date.now()-o<s;){let u=await e.evaluate(Yi).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 oa(e,r));let d=Date.now();if(na({elapsedMs:d-o,quietMs:d-c,hasRegistered:l,initialWaitMs:i,maxWaitMs:s})||(await Tr(Math.min(Sr,Math.max(0,n-Date.now()))),Date.now()>=n))break}return Date.now()-o}function na(e){return e.elapsedMs>=e.maxWaitMs?!0:e.hasRegistered?e.quietMs>=Di:e.elapsedMs>=e.initialWaitMs}async function ra(e,t,n){let r=Date.now(),o=Math.min(xr[t],Math.max(0,n-r)),s=null;for(;Date.now()-r<o;){let i=await e.evaluate(qi).catch(()=>null);if(typeof i=="number"&&Number.isSafeInteger(i)&&i>=0&&(s=i,i>0))return i;if(await Tr(Math.min(Sr,Math.max(0,n-Date.now()))),Date.now()>=n)break}return s}async function oa(e,t){let n=await e.evaluate(Er).catch(()=>null);n&&t(Rr(n.tools,e.url()))}async function sa(e,t,n,r,o){let s=Date.now(),i=s+Wi,a=await Zi(e,t,n,i,r),l=a.loadError!==null||a.blocked?{snapshot:null,declarative:null,quietMs:0,loadError:null}:await ea(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?Rr(d.tools,g):[],h=Vi(m,g),p=[...f,...h],y=aa(a.html,a.inlineJs,a.scripts),x=or(a.originTrialTokens,br(g)??br(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=ir(C);return{page:{url:t,finalUrl:g,verdict:Re,status:ar(Re,p),tools:p,declarativeFormCount:h.length,consumer:{nativeApi:a.nativeApi,nativeToolCount:a.nativeToolCount,originTrial:x,permissionsPolicy:a.permissionsPolicy,iframeAllow:Qi(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 $r(e){let{url:t,endpoint:n,mode:r="fast",screenshot:o=!0,onTools:s}=e,i=Date.now(),a=new Date().toISOString(),c=await Ye.connect(n);try{let l=await sa(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 ia(e,t){let n=await e.screenshot(Hi,Xe(t,5e3));if(!n||n.byteLength===0||n.byteLength>Gi)return null;let r=e.viewportSize();return{data:n.toString("base64"),mimeType:"image/jpeg",width:r?.width??0,height:r?.height??0}}function aa(e,t,n){if(!e)return wr;try{return yr(e,t,n)}catch{return wr}}function br(e){try{return new URL(e).origin}catch{return null}}function Ve(e){return(e instanceof Error?e.message:String(e)).split(`
|
|
698
|
+
`)[0].slice(0,300)}function Xe(e,t){return Math.max(250,Math.min(t,e-Date.now()))}function Tr(e){return new Promise(t=>setTimeout(t,e))}var Cr=require("child_process"),G=require("fs"),Pr=require("os"),Nt=require("path");var Or=9222;async function Ir(e){if(e)try{return{ok:!0,endpoint:await Ot(e),close:async()=>{},launched:!1}}catch(t){let n=Mt(t);return{ok:!1,message:[`No debuggable Chrome answered at ${e}.`,...n.startsWith("no debuggable Chrome answered")?[]:[n],"",...ca(Or)].join(`
|
|
699
|
+
`)}}try{let t=await ya();return{ok:!0,endpoint:t.endpoint,close:t.close,launched:!0}}catch(t){return{ok:!1,message:Mt(t)}}}function Mr(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 ca(e){return["The audit drives a Chrome you already have; it never downloads one.","Start one with a debugging port and a scratch profile:","",` ${Nr(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 Nr(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 Mt(e){return e instanceof $||e instanceof Error?e.message:String(e)}function la(){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 ua(){for(let e of la())try{if((0,G.statSync)(e).isFile())return e}catch{}return null}var da=["--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 pa(){return process.env.AX_WEBMCP_NO_SANDBOX==="1"}var _r=2e4,ma=3e3,ha=4,ga=150;function fa(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 ya(){let e=ua();if(!e)throw new $(va());let t=(0,G.mkdtempSync)((0,Nt.join)((0,Pr.tmpdir)(),"ax-webmcp-")),n=(0,Cr.spawn)(e,[...da,...pa()?["--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 fa(n,ma),await ba(t)};process.once("SIGINT",r),process.once("SIGTERM",r);try{let s=await wa(t,n);return{endpoint:await Ot(`127.0.0.1:${s}`),close:o}}catch(s){throw await o(),s instanceof $?s:new $(Mt(s))}}async function wa(e,t){let n=(0,Nt.join)(e,"DevToolsActivePort"),r=Date.now()+_r;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 ${_r/1e3}s.`)}async function ba(e){for(let t=0;t<ha;t++){try{if((0,G.rmSync)(e,{recursive:!0,force:!0}),!(0,G.existsSync)(e))return}catch{}await new Promise(n=>setTimeout(n,ga))}try{(0,G.rmSync)(e,{recursive:!0,force:!0})}catch{}}function va(){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:","",` ${Nr(Or)}`].join(`
|
|
702
|
+
`)}var Sa="https://ora.ai",xa=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}},Lr=4*1024*1024,jr=10,Ur=100,Wr=32768,Dr=4096,Fr=512;function Br(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>jr)return`capture covers ${e.pages.length} pages; the limit is ${jr}`;for(let t of e.pages){if(t.tools.length>Ur)return`${t.url} registered ${t.tools.length} tools; the limit is ${Ur} per page`;for(let n of t.tools){if(n.name.length>Fr)return`tool name on ${t.url} is ${n.name.length} characters; the limit is ${Fr}`;if(n.description.length>Dr)return`description for "${n.name}" is ${n.description.length} characters; the limit is ${Dr}`;for(let[r,o]of[["inputSchema",n.inputSchema],["annotations",n.annotations]]){let s=Aa(o);if(s===null)return`${r} for "${n.name}" could not be serialized (a cycle, or a value JSON cannot carry)`;if(s.length>Wr)return`${r} for "${n.name}" serializes to ${s.length} characters; the limit is ${Wr}`}}}return null}function Jr(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 Aa(e){try{return JSON.stringify(e)??"null"}catch{return null}}async function Hr(e,t,n={}){let r=(n.baseUrl??process.env.ORA_API_URL??Sa).replace(/\/+$/,""),o=n.idleMs??xa,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")>Lr)throw s.disarm(),new N(`this capture serializes to ${Math.round(Buffer.byteLength(a,"utf8")/1024)} KB; the ingest limit is ${Lr/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 ka(c);return Ea(c,s,n,i)}async function ka(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: ${Ra(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 Ea(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 Ra(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
|
-
`),F.BELOW_MIN_SCORE;if(l.score===null)return e.json||console.error(`
|
|
601
|
-
ora returned no score, so --min-score cannot be evaluated.`),F.API;if(l.score<n.value)return e.json||console.log(`
|
|
712
|
+
`)}var w=B(D(),1);var Lt=12,Ta=["fail","warning","unmeasured","na","pass"],jt={fail:["\u2716",w.default.red],warning:["\u25B2",w.default.yellow],unmeasured:["?",w.default.magenta],na:["\u2013",w.default.dim],pass:["\u2714",w.default.green]},_a={fail:"Failing",warning:"Warnings",unmeasured:"Not measured",na:"Not applicable",pass:"Passing"},Ca=["shared-experience","task-completion","tool-quality","trust"],Pa={"shared-experience":"Shared experience","task-completion":"Task completion","tool-quality":"Tool quality",trust:"Trust"};function Gr(e,t={}){let n=Z(80,120);return["",...Oa(e,n),"",...Ma(e.availability,n),"",...Na(e,n),"",...ja(e),"",...Wa(e.findings,n,t.showPassing===!0),...Ba(e.simulation,n),"",...Ja(e,n)]}function Oa(e,t){let n=[` ${w.default.bold(O(e.url))}`],r=`${e.toolCount} tool${e.toolCount===1?"":"s"}`,o=[Ia(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=>Kr(s,t))}function Ia(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 Ma(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 Na(e,t){let n=e.score===null?"\u2014":String(e.score),r=[` ${w.default.bold(`${n}/100`)} ${La(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 La(e){return e.grade!==null?w.default.bold(w.default.green(`grade ${e.grade}`)):w.default.dim("grade withheld")}function ja(e){let t=[` ${w.default.bold("Pillars")}`];for(let n of Ca){let r=e.categoryScores[n]??0,o=cr[n],s=e.applicableCategories.includes(n),i=s?Ua(r):w.default.dim("\u2591".repeat(Lt)),a=s?`weight ${o}`:`weight ${o} \xB7 nothing measured`;t.push(` ${Pa[n].padEnd(18)} ${i} ${String(r).padStart(3)}% ${w.default.dim(a)}`)}return t}function Ua(e){let t=Math.round(Math.min(100,Math.max(0,e))/100*Lt);return`${(e>=75?w.default.green:e>=40?w.default.yellow:w.default.red)("\u2588".repeat(t))}${w.default.dim("\u2591".repeat(Lt-t))}`}function Wa(e,t,n){let r=[` ${w.default.bold("Checks")}`];for(let o of Ta){let s=e.filter(i=>i.status===o);if(s.length!==0){if(o==="pass"&&!n){r.push(` ${w.default.dim(`${s.length} passing (--show-passing to list)`)}`);continue}r.push("",` ${w.default.bold(_a[o])} (${s.length})`);for(let i of s)r.push(...Da(i,t))}}return e.length===0&&r.push(` ${w.default.dim("no checks reported")}`),r}function Da(e,t){let[n,r]=jt[e.status],o=Fa(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 Fa(e){return lr[e]?.title??e}function Ba(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?jt.pass:jt.fail,a=o.chosenTool?O(o.chosenTool):w.default.dim("nothing");n.push(` ${i(s)} ${Kr(O(o.intent),t-30)} ${w.default.dim("\u2192")} ${a}`)}return n}function Ja(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 Kr(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 Ha(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 Ga(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 qr(e){let t=Ha(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=Ga(e.minScore);if(n.error)return console.error(n.error),K.USAGE;let r=await Ir(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 $r({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=Br(o);if(i)return R.stop(),console.error(`ora would refuse this capture: ${i}`),K.USAGE;let{capture:a,droppedScreenshot:c}=Jr(o);e.json||R.update("Scoring with ora");let l;try{l=await Hr(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(Ka(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 Gr(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=Mr(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
|
-
`),F.BELOW_MIN_SCORE}return F.OK}function Fa(e){switch(e.type){case"phase":return`Scoring with ora \u2014 ${e.phase}`;case"tool-discovered":return`Scoring with ora \u2014 found ${O(e.tool.name)}`;case"finding":return`Scoring with ora \u2014 ${e.finding.checkId}`;case"simulation-step":return`Scoring with ora \u2014 simulating "${O(e.step.intent)}"`;default:return"Scoring with ora"}}function Gr(){if(typeof process.loadEnvFile!="function")return!1;try{return process.loadEnvFile(),!0}catch{return!1}}var Y="ax",Wa={meta:{name:"audit",description:"Score a site's agent readiness (exit codes: 0 ok, 1 below --min-score, 2 usage, 3 API error)"},args:{url:{type:"positional",description:"URL or domain to audit (e.g. https://docs.example.com)",required:!0},json:{type:"boolean",description:"Print the raw ora audit payload as JSON",default:!1},"min-score":{type:"string",description:"Exit 1 when the score is below this threshold (0-100); the CI gate"},"max-age":{type:"string",description:"Accept a cached result up to this many seconds old (server default 6h)"},force:{type:"boolean",description:"Bypass the cache and rescan (spends the stricter 6/day force budget)",default:!1},tunnel:{type:"string",description:"Open ora's own tunnel to a local target (value: ora); needs ORA_API_KEY with the tunnels:write + tunnels:connect scopes. Also read from ORA_TUNNEL. The result is stored as ephemeral"},"tunnel-cmd":{type:"string",description:"Bring your own tunnel: a command that exposes a local target and prints its public https URL (e.g. 'ngrok http 3000 --log stdout'); also read from ORA_TUNNEL_CMD. The result is stored as ephemeral"},"api-key":{type:"string",description:"ora-issued scan API key that lifts the scan rate limits; also read from ORA_SCAN_API_KEY"},"show-passing":{type:"boolean",description:"List each passing check individually",default:!1},"show-skipped":{type:"boolean",description:"List not-applicable / pending checks too",default:!1}},async run({args:e}){process.exitCode=await Nn({url:e.url,json:!!e.json,showSkipped:!!e["show-skipped"],showPassing:!!e["show-passing"],minScore:e["min-score"],maxAge:e["max-age"],force:!!e.force,tunnelCmd:e["tunnel-cmd"],tunnel:e.tunnel,apiKey:e["api-key"]})}},Ba={meta:{name:"journey",description:"Send a real AI agent at a site and watch it navigate live"},args:{intent:{type:"positional",description:'Goal for the agent (e.g. "Find the API docs and how to auth")',required:!0},domain:{type:"string",description:"Site the agent targets (e.g. stripe.com)"},harness:{type:"string",description:"Agent harness: claude-code, codex, openclaw, hermess, claude-agent, eve, \u2026",default:"claude-code"},model:{type:"string",description:"Model override (harness default when omitted)"},json:{type:"boolean",description:"Output as JSON",default:!1}},async run({args:e}){process.exitCode=await zn({intent:e.intent,domain:e.domain,harness:e.harness,model:e.model,json:!!e.json})}},Ja={meta:{name:"deep-journey",description:"Run a real AI agent at a site on a curated task \u2014 or, with a partner API key, a free-text one \u2014 via ora's public API (exit codes: 0 ok, 1 run failed, 2 usage, 3 API error)"},args:{url:{type:"positional",description:"URL or domain the agent targets (e.g. stripe.com)",required:!0},intent:{type:"string",description:"Curated intent id (see GET /api/journey/intents; server default when omitted)"},agent:{type:"string",description:"Agent id (see GET /api/journey/agents); defaults to cas-haiku (Claude Code \xB7 Haiku 4.5)"},json:{type:"boolean",description:"Print the terminal run detail as JSON",default:!1},task:{type:"string",description:"Free-text task for the agent (needs a partner API key; mutually exclusive with --intent)"},"api-key":{type:"string",description:"ora-issued partner API key: unlocks --task and the 1000/24h keyed allowance; also read from ORA_PARTNER_API_KEY"},"no-stream":{type:"boolean",description:"Hide the live trajectory view and print only the final result",default:!1}},async run({args:e}){process.exitCode=await Kn({url:e.url,intent:e.intent,task:e.task,apiKey:e["api-key"],agent:e.agent,json:!!e.json,noStream:!!e["no-stream"]})}},Ha={meta:{name:"generate-files",description:"Draft a domain's agent discovery files (ard.json, ai-catalog.json, poppy.json) into <out>/.well-known/ (exit codes: 0 ok, 2 usage or files already exist, 3 API error)"},args:{domain:{type:"positional",description:"Domain the files speak for (e.g. example.com)",required:!0},out:{type:"string",description:"Directory your site serves from; files land in <out>/.well-known/ (default: current directory)"},force:{type:"boolean",description:"Overwrite files that already exist",default:!1},json:{type:"boolean",description:"Print ora's payload as JSON and write nothing",default:!1}},async run({args:e}){process.exitCode=await Xn({domain:e.domain,out:e.out,force:!!e.force,json:!!e.json})}},Ga={meta:{name:"skill",description:"List, print, or install ora's agent skills (digest-verified from the registry, never bundled)"},args:{name:{type:"positional",description:"Skill name (omit to list the registry)",required:!1},install:{type:"boolean",description:"Write <dir>/<name>/SKILL.md instead of printing",default:!1},dir:{type:"string",description:"Install directory (default .claude/skills)"},json:{type:"boolean",description:"Print the raw registry index as JSON",default:!1}},async run({args:e}){process.exitCode=await nr({name:e.name,install:!!e.install,dir:e.dir,json:!!e.json})}},Ka={meta:{name:"webmcp-audit",description:"Audit a page's WebMCP tools in a real browser - localhost included, so you can check before you publish (exit codes: 0 ok, 1 below --min-score, 2 usage, 3 API error)"},args:{url:{type:"positional",description:"Page to audit, scheme included (e.g. http://localhost:3000)",required:!0},"chrome-endpoint":{type:"string",description:"Drive a Chrome you started instead of launching one: ws:// URL, http origin, or host:port"},"min-score":{type:"string",description:"Exit 1 when the score is below this threshold (0-100); the CI gate"},"api-key":{type:"string",description:"ora API key that lifts the ingest rate limits; also read from ORA_API_KEY"},json:{type:"boolean",description:"Print the raw ora audit payload as JSON",default:!1},"show-passing":{type:"boolean",description:"List each passing check individually",default:!1}},async run({args:e}){process.exitCode=await Hr({url:e.url,json:!!e.json,showPassing:!!e["show-passing"],minScore:e["min-score"],chromeEndpoint:e["chrome-endpoint"],apiKey:e["api-key"]})}};function qa(){let e=ze.default.green("$"),t=ze.default.dim;return["",` ${ze.default.bold(Y)} ${t(`v${we.version}`)}`,` ${t("Score any site's agent readiness \u2014 and watch real AI agents navigate it")}`,"",` ${t("Commands:")}`,` audit ${t("<url>")} ${t("Score a site's agent readiness")}`,` webmcp-audit ${t("<url>")} ${t("Audit a WebMCP surface in a real browser, localhost included")}`,` deep-journey ${t("<url>")} ${t("Run a real agent at a site on a curated or free-text task")}`,` journey ${t("<intent>")} ${t("Send a real agent at a site and watch it live (workspace)")}`,` skill ${t("[name]")} ${t("List, print, or install ora's agent skills")}`,` generate-files ${t("<domain>")} ${t("Draft ard.json, ai-catalog.json and poppy.json for a domain")}`,"",` ${t("Examples:")}`,` ${e} ${Y} audit https://docs.example.com`,` ${e} ${Y} audit https://docs.example.com --min-score 70 ${t("# CI gate")}`,` ${e} ${Y} audit https://docs.example.com --json`,` ${e} ${Y} audit localhost:3000 --tunnel ora ${t("# audit a local dev server")}`,` ${e} ${Y} webmcp-audit http://localhost:3000`,` ${e} ${Y} deep-journey stripe.com --intent pricing`,` ${e} ${Y} journey "Find the API docs and how to authenticate" --domain stripe.com`,` ${e} ${Y} generate-files example.com --out public`,"",` ${t("audit options:")}`,` --min-score <n> ${t("Exit 1 when the score is below n (0-100); the CI gate")}`,` --max-age <s> ${t("Accept a cached result up to s seconds old (default 6h)")}`,` --force ${t("Bypass the cache and rescan (6/day budget)")}`,` --tunnel ora ${t("Expose a local target through ora's own tunnel (needs ORA_API_KEY: tunnels:write + tunnels:connect)")}`,` --tunnel-cmd <c> ${t("...or through your own tunnel command (e.g. 'ngrok http 3000 --log stdout')")}`,` --api-key <k> ${t("ora-issued scan API key that lifts the rate limits; also read from ORA_SCAN_API_KEY")}`,` --json ${t("Print the raw ora audit payload as JSON")}`,` --show-passing ${t("List each passing check (hidden by default)")}`,` --show-skipped ${t("List skipped checks (hidden by default)")}`,"",` ${t("audit exit codes:")}`,` ${t("0 success \xB7 1 below --min-score \xB7 2 usage error \xB7 3 API unreachable/rate-limited")}`,"",` ${t("webmcp-audit options:")}`,` --chrome-endpoint ${t("<e> Drive a Chrome you started: ws:// URL, http origin, or host:port")}`,` --min-score <n> ${t("Exit 1 when the score is below n (0-100); the CI gate")}`,` --api-key <k> ${t("ora API key that lifts the ingest rate limits; also read from ORA_API_KEY")}`,` --json ${t("Print the raw ora audit payload as JSON")}`,` --show-passing ${t("List each passing check (hidden by default)")}`,` ${t("starts a headless Chrome you already have installed; never downloads one")}`,` ${t("scored by ora, stored nowhere: the result is never published or ranked")}`,"",` ${t("deep-journey options:")}`,` --intent <id> ${t("Curated task id, e.g. pricing, signup, api-docs (server default when omitted)")}`,` --task <text> ${t("Free-text task (needs a partner API key; replaces --intent)")}`,` --api-key <k> ${t("ora partner API key: unlocks --task + 1000 runs/24h; also read from ORA_PARTNER_API_KEY")}`,` --agent <id> ${t("Agent to run (default: cas-haiku \u2014 Claude Code \xB7 Haiku 4.5)")}`,` --no-stream ${t("Hide the live trajectory view and print only the final result")}`,` --json ${t("Print the terminal run detail as JSON")}`,` ${t("no key needed \xB7 public caps: 100 runs/24h per target, 20 runs/24h per IP")}`,"",` ${t("generate-files options:")}`,` --out <dir> ${t("Directory your site serves from; writes <dir>/.well-known/* (default: .)")}`,` --force ${t("Overwrite files that already exist (otherwise nothing is written)")}`,` --json ${t("Print ora's payload as JSON and write nothing")}`,` ${t("drafts from ora's last scan of the domain - review each file before you publish it")}`,"",` ${t("journey options:")}`,` --domain <d> ${t("Site the agent targets (e.g. stripe.com)")}`,` --harness <h> ${t("Agent harness: claude-code (default), codex, openclaw, hermess, claude-agent, eve, \u2026")}`,` --model <m> ${t("Model override (harness default when omitted)")}`,` --json ${t("Output as JSON")}`,` ${t("requires ORA_API_KEY (see .env.example)")}`,""].join(`
|
|
604
|
-
`)}var
|
|
716
|
+
`),K.BELOW_MIN_SCORE}return K.OK}function Ka(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 Yr(){if(typeof process.loadEnvFile!="function")return!1;try{return process.loadEnvFile(),!0}catch{return!1}}var V="ax",qa={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"]})}},Ya={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 Xn({intent:e.intent,domain:e.domain,harness:e.harness,model:e.model,json:!!e.json})}},Va={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 Gn({url:e.url,intent:e.intent,task:e.task,apiKey:e["api-key"],agent:e.agent,json:!!e.json,noStream:!!e["no-stream"]})}},Xa={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 Vn({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 tr({name:e.name,install:!!e.install,dir:e.dir,json:!!e.json})}},Qa={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 qr({url:e.url,json:!!e.json,showPassing:!!e["show-passing"],minScore:e["min-score"],chromeEndpoint:e["chrome-endpoint"],apiKey:e["api-key"]})}};function Za(){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 ec={meta:{name:V,version:we.version,description:"Score any site's agent readiness \u2014 and watch real AI agents navigate it"},subCommands:{audit:qa,"webmcp-audit":Qa,"deep-journey":Va,journey:Ya,skill:za,"generate-files":Xa},setup(){let e=process.argv[2];(!e||e==="--help"||e==="-h")&&(console.log(Za()),process.exit(0))}};Yr();qt(ec);
|