ripplo 0.0.6 → 0.0.7

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/dist/index.js CHANGED
@@ -1,108 +1,108 @@
1
1
  #!/usr/bin/env node
2
- var Pa=Object.defineProperty;var m=(e,t)=>()=>(e&&(t=e(e=0)),t);var xa=(e,t)=>{for(var o in t)Pa(e,o,{get:t[o],enumerable:!0})};function P({locator:e,page:t}){switch(e.by){case"css":return t.locator(e.value);case"testId":return t.getByTestId(e.value);case"role":return t.getByRole(e.role,{exact:e.exact,name:e.name});case"text":return t.getByText(e.value,{exact:e.exact});case"label":return t.getByLabel(e.value,{exact:e.exact});case"placeholder":return t.getByPlaceholder(e.value);case"altText":return t.getByAltText(e.value)}}var ie=m(()=>{"use strict"});function Ee({defs:e}){return e==null?{}:Object.fromEntries(Object.entries(e).map(([t,o])=>[t,Ca({def:o,name:t})]))}function Ca({def:e,name:t}){if(e.type==="env"){let o=process.env[e.key];if(o==null)throw new Error(`Environment variable "${e.key}" not set for variable "${t}"`);return o}return e.default??Ta[e.type]??""}function me({ref:e,variables:t}){if(e.type==="static")return e.value;let o=t[e.name];if(o==null)throw new Error(`Variable "${e.name}" is not defined`);return o}function C({ref:e,variables:t}){let o=String(me({ref:e,variables:t}));return Ia({raw:o,variables:t})}function Ia({raw:e,variables:t}){return e.replaceAll(/\{\{(\w+)\}\}/g,(o,r)=>{let n=t[r];if(n==null)throw new Error(`Template variable "{{${r}}}" is not defined`);return String(n)})}function $t({ref:e,variables:t}){let o=me({ref:e,variables:t});if(typeof o=="number")return o;let r=Number(o);if(Number.isNaN(r))throw new TypeError(`Cannot convert "${String(o)}" to number`);return r}function oe({name:e,store:t,value:o}){return{...t,[e]:o}}var Ta,Q=m(()=>{"use strict";Ta={boolean:!1,number:0,string:""}});async function Zo({node:e,page:t,timeout:o}){await P({locator:e.source,page:t}).dragTo(P({locator:e.target,page:t}),{timeout:o})}async function Xo({node:e,page:t,timeout:o}){await P({locator:e.locator,page:t}).click({button:"right",timeout:o})}function er({node:e,page:t,variables:o}){return t.once("dialog",async r=>{e.action==="accept"?await r.accept(e.promptText??void 0):await r.dismiss()}),{variables:o}}async function tr({node:e,page:t}){let o=e.x??0,r=e.y??0;if(e.locator==null){await t.mouse.wheel(o,r);return}let s=await P({locator:e.locator,page:t}).elementHandle();if(s==null)throw new Error("scroll target element not found");await s.evaluate("([dx, dy]) => this.scrollBy(dx, dy)",[o,r])}async function or({node:e,page:t,variables:o}){if(e.action==="write"){if(e.value==null)throw new Error("clipboard write requires a value");let n=C({ref:e.value,variables:o}),s=JSON.stringify(n);return await t.evaluate(`navigator.clipboard.writeText(${s})`),{variables:o}}if(e.variable==null)throw new Error("clipboard read requires a variable name to store the result");let r=String(await t.evaluate("navigator.clipboard.readText()"));return{variables:oe({name:e.variable,store:o,value:r})}}async function rr({node:e,page:t}){let o=t.context();e.state==="granted"?await o.grantPermissions([e.permission]):await o.clearPermissions()}var nr=m(()=>{"use strict";ie();Q()});async function Et({node:e,page:t,timeout:o,variables:r}){switch(e.type){case"click":case"check":case"uncheck":case"clear":case"dblclick":case"focus":case"hover":case"scrollIntoView":return Na({node:e,page:t,timeout:o,variables:r});case"rightClick":return await Xo({node:e,page:t,timeout:o}),{variables:r};case"goto":{let n=C({ref:e.url,variables:r});return await t.goto(n,{timeout:o,waitUntil:"domcontentloaded"}),{variables:r}}case"fill":{let n=C({ref:e.value,variables:r});return await P({locator:e.locator,page:t}).fill(n,{timeout:o}),{variables:r}}case"select":{let n=C({ref:e.value,variables:r});return await P({locator:e.locator,page:t}).selectOption(n,{timeout:o}),{variables:r}}case"type":{let n=C({ref:e.value,variables:r});return await P({locator:e.locator,page:t}).pressSequentially(n,{timeout:o}),{variables:r}}case"press":return await $a({node:e,page:t,timeout:o}),{variables:r};case"drag":return await Zo({node:e,page:t,timeout:o}),{variables:r};case"upload":return await P({locator:e.locator,page:t}).setInputFiles(e.files,{timeout:o}),{variables:r};case"extractText":{let n=await P({locator:e.locator,page:t}).textContent({timeout:o});if(n==null)throw new Error("extractText: element had no text content");return{variables:oe({name:e.variable,store:r,value:n})}}case"setVariable":{let n=me({ref:e.value,variables:r});return{variables:oe({name:e.variable,store:r,value:n})}}case"fail":throw new Error(e.message);case"waitFor":return await P({locator:e.locator,page:t}).waitFor({state:e.state??"visible",timeout:o}),{variables:r};case"waitForUrl":{let n=C({ref:e.expected,variables:r});return await t.waitForURL(ja({expected:n,operator:e.operator}),{timeout:o}),{variables:r}}case"waitForResponse":{let n=C({ref:e.urlPattern,variables:r});return await t.waitForResponse(s=>s.url().includes(n),{timeout:o}),{variables:r}}case"waitForRequest":{let n=C({ref:e.urlPattern,variables:r});return await t.waitForRequest(s=>s.url().includes(n),{timeout:o}),{variables:r}}case"wait":return await t.waitForTimeout(e.duration),{variables:r};case"screenshot":return await t.screenshot(),{variables:r};case"setViewport":return await t.setViewportSize({height:e.height,width:e.width}),{variables:r};case"handleDialog":return er({node:e,page:t,variables:r});case"scroll":return await tr({node:e,page:t}),{variables:r};case"clipboard":return or({node:e,page:t,variables:r});case"setPermission":return await rr({node:e,page:t}),{variables:r}}}async function Na({node:e,page:t,timeout:o,variables:r}){return await P({locator:e.locator,page:t})[Aa[e.type]]({timeout:o}),{variables:r}}function ja({expected:e,operator:t}){return o=>{let r=o.toString();return t==="equals"?r===e:t==="notEquals"?r!==e:t==="contains"?r.includes(e):t==="startsWith"?r.startsWith(e):t==="endsWith"?r.endsWith(e):new RegExp(e).test(r)}}async function $a({node:e,page:t,timeout:o}){e.locator==null?await t.keyboard.press(e.key):await P({locator:e.locator,page:t}).press(e.key,{timeout:o})}var Aa,Ot=m(()=>{"use strict";nr();ie();Q();Aa={check:"check",clear:"clear",click:"click",dblclick:"dblclick",focus:"focus",hover:"hover",scrollIntoView:"scrollIntoViewIfNeeded",uncheck:"uncheck"}});async function le({page:e,runStartTime:t,targets:o}){let r=e.viewportSize();if(r==null)throw new Error("Page has no viewport set");let[n,s]=await Promise.all([e.screenshot({type:"png"}),Oa(o)]),a=n.toString("base64");return{annotations:s,screenshotBase64:a,snapshotTimestamp:Math.round(performance.now()-t),url:e.url(),viewportHeight:r.height,viewportWidth:r.width}}function Ea(e){return"locator"in e}async function Oa(e){return(await Promise.all(e.map(o=>Ua(o)))).filter(o=>o!=null)}async function Ua(e){if(!Ea(e))return{height:0,label:e.label,type:e.type,width:0,x:0,y:0};let t=await e.locator.boundingBox({timeout:2e3}).catch(()=>null);if(t!=null)return{height:Math.round(t.height),label:e.label,type:e.type,width:Math.round(t.width),x:Math.round(t.x),y:Math.round(t.y)}}function ot({node:e,page:t}){if(e.type==="assertUrl"||e.type==="waitForUrl")return[{label:e.type,type:"urlBar"}];if(e.type==="drag"){let n=P({locator:e.source,page:t}),s=P({locator:e.target,page:t});return[{label:"drag-source",locator:n,type:"action"},{label:"drag-target",locator:s,type:"action"}]}if(!Fa(e))return[];let o=e.type.startsWith("assert")?"assertion":"action",r=P({locator:e.locator,page:t});return[{label:e.type,locator:r,type:o}]}function Fa(e){return"locator"in e&&e.locator!=null}var Oe=m(()=>{"use strict";ie()});import{z as Va}from"zod";function g({description:e,execute:t,name:o,schema:r}){let n=Va.toJSONSchema(r,{target:"draft-2020-12"});return{anthropicTool:{description:e,input_schema:{...n,type:"object"},name:o},name:o,async execute(s,a){let i=r.parse(a);return{...await Promise.resolve(t(s,i)),kind:"action"}}}}async function w(e){let t=e.specNode==null?[]:ot({node:e.specNode,page:e.page}),o=await le({page:e.page,runStartTime:e.runStartTime,targets:t}),r=[...e.assertions],n={annotations:o.annotations,assertions:r,detail:e.detail,duration:Math.round(e.duration),nodeId:`agent-step-${String(e.stepIndex)}`,nodeType:e.nodeType,screenshotBase64:o.screenshotBase64,snapshotTimestamp:o.snapshotTimestamp,status:e.status,stepIndex:e.stepIndex,title:e.title,url:o.url,viewportHeight:o.viewportHeight,viewportWidth:o.viewportWidth},s=r.length>0?r.map(a=>`${a.status}: ${a.description} \u2014 ${a.detail??""}`).join(`
3
- `):`${e.status}: ${e.title}`;return{specNode:e.specNode,stepResult:n,toolOutput:s}}var v=m(()=>{"use strict";Oe()});import{z as sr}from"zod";var Da,ar,ir=m(()=>{"use strict";v();Da=sr.object({selector:sr.string().describe("CSS selector for the checkbox or radio button")}),ar=g({description:"Assert that a checkbox or radio button is checked",name:"assert_checked",schema:Da,execute:async(e,t)=>{let o=performance.now(),r=await e.page.locator(t.selector).isChecked().catch(()=>!1),n=r?"passed":"failed",s=[{description:`Element ${t.selector} is checked`,detail:r?void 0:"Element is not checked",status:n}],i={id:`agent-step-${String(e.stepIndex)}`,locator:{by:"css",value:t.selector},type:"assertChecked"};return w({assertions:s,detail:r?"Element is checked":"Element is not checked",duration:performance.now()-o,nodeType:"assertChecked",page:e.page,runStartTime:e.runStartTime,specNode:i,status:n,stepIndex:e.stepIndex,title:`Assert checked: ${t.selector}`})}})});import{z as be}from"zod";function La({cookie:e,input:t}){return[_a(t.value,e.value),lr("httpOnly",t.httpOnly,e.httpOnly),lr("secure",t.secure,e.secure),qa("sameSite",t.sameSite,e.sameSite)].filter(o=>o!=null)}function _a(e,t){if(e==null)return;let o=t.includes(e);return{description:`Cookie value contains "${e}"`,detail:o?void 0:`Got: "${t}"`,status:o?"passed":"failed"}}function lr(e,t,o){if(t!=null)return{description:`Cookie ${e} is ${String(t)}`,detail:o===t?void 0:`Got: ${String(o)}`,status:o===t?"passed":"failed"}}function qa(e,t,o){if(t!=null)return{description:`Cookie ${e} is ${t}`,detail:o===t?void 0:`Got: ${o}`,status:o===t?"passed":"failed"}}var Wa,cr,dr=m(()=>{"use strict";v();Wa=be.object({httpOnly:be.boolean().optional().describe("Assert httpOnly flag value"),name:be.string().describe("Cookie name to check"),sameSite:be.enum(["Strict","Lax","None"]).optional().describe("Assert sameSite value"),secure:be.boolean().optional().describe("Assert secure flag value"),value:be.string().optional().describe("Expected cookie value (substring match)")}),cr=g({description:"Assert properties of a browser cookie. Check existence, value, and security flags (httpOnly, secure, sameSite).",name:"assert_cookie",schema:Wa,execute:async(e,t)=>{let o=performance.now(),n=(await e.page.context().cookies()).find(p=>p.name===t.name),s=n==null?[{description:`Cookie "${t.name}" exists`,detail:"Cookie not found",status:"failed"}]:[{description:`Cookie "${t.name}" exists`,detail:void 0,status:"passed"},...La({cookie:n,input:t})],a=s.some(p=>p.status==="failed"),i=a?"failed":"passed",c={id:`agent-step-${String(e.stepIndex)}`,name:{type:"static",value:t.name},type:"assertCookie"};return w({assertions:s,detail:a?s.filter(p=>p.status==="failed").map(p=>p.detail).join("; "):"Cookie OK",duration:performance.now()-o,nodeType:"assertCookie",page:e.page,runStartTime:e.runStartTime,specNode:c,status:i,stepIndex:e.stepIndex,title:`Assert cookie: ${t.name}`})}})});import{z as ur}from"zod";var Ba,pr,fr=m(()=>{"use strict";v();Ba=ur.object({selector:ur.string().describe("CSS selector for the element to check focus on")}),pr=g({description:"Assert that an element has keyboard focus. Use for accessibility tab-order testing.",name:"assert_focused",schema:Ba,execute:async(e,t)=>{let o=performance.now(),n=!!await e.page.locator(t.selector).evaluate("(el) => document.activeElement === el").catch(()=>!1),s=n?"passed":"failed",a=[{description:`Element ${t.selector} is focused`,detail:n?void 0:"Element does not have focus",status:s}],l={id:`agent-step-${String(e.stepIndex)}`,locator:{by:"css",value:t.selector},type:"assertFocused"};return w({assertions:a,detail:n?"Element is focused":"Element does not have focus",duration:performance.now()-o,nodeType:"assertFocused",page:e.page,runStartTime:e.runStartTime,specNode:l,status:s,stepIndex:e.stepIndex,title:`Assert focused: ${t.selector}`})}})});import{z as Se}from"zod";function Ga(e,t){if(e!=null)return{description:`Response status equals ${String(e)}`,detail:t===e?void 0:`Got: ${String(t)}`,status:t===e?"passed":"failed"}}async function za(e,t){if(e==null)return;let r=(await t.text()).includes(e);return{description:`Response body contains "${e}"`,detail:r?void 0:"Not found in response body",status:r?"passed":"failed"}}function Ha(e,t,o){if(e==null||t==null)return;let r=o[e.toLowerCase()],n=r!=null&&r.includes(t);return{description:`Response header "${e}" contains "${t}"`,detail:n?void 0:`Got: "${r??"(missing)"}"`,status:n?"passed":"failed"}}var Ma,mr,gr=m(()=>{"use strict";v();Ma=Se.object({bodyContains:Se.string().optional().describe("Assert response body contains this string"),headerName:Se.string().optional().describe("Response header name to check"),headerValue:Se.string().optional().describe("Expected value the header should contain"),status:Se.number().int().optional().describe("Expected HTTP status code"),urlPattern:Se.string().describe("URL substring to match the response against")}),mr=g({description:"Wait for a network response matching the URL pattern and assert on its status, body, or headers. Useful for verifying API calls and security headers (CSP, CORS).",name:"assert_response",schema:Ma,execute:async(e,t)=>{let o=performance.now(),r=await e.page.waitForResponse(c=>c.url().includes(t.urlPattern),{timeout:1e4}),n=[Ga(t.status,r.status()),await za(t.bodyContains,r),Ha(t.headerName,t.headerValue,r.headers())].filter(c=>c!=null),s=n.length===0?[{description:`Response matching "${t.urlPattern}" received`,detail:void 0,status:"passed"}]:n,a=s.some(c=>c.status==="failed"),l={id:`agent-step-${String(e.stepIndex)}`,type:"assertResponse",urlPattern:{type:"static",value:t.urlPattern}};return w({assertions:s,detail:a?s.filter(c=>c.status==="failed").map(c=>c.detail).join("; "):"Response OK",duration:performance.now()-o,nodeType:"assertResponse",page:e.page,runStartTime:e.runStartTime,specNode:l,status:a?"failed":"passed",stepIndex:e.stepIndex,title:`Assert response: ${t.urlPattern}`})}})});import{z as Ut}from"zod";var Ja,hr,yr=m(()=>{"use strict";v();Ja=Ut.object({expected:Ut.string().describe("The expected text content"),selector:Ut.string().describe("CSS selector for the element to check")}),hr=g({description:"Assert that an element's text content matches the expected value",name:"assert_text",schema:Ja,execute:async(e,t)=>{let o=performance.now(),r=await e.page.locator(t.selector).textContent({timeout:5e3}).catch(()=>null),n=r!=null&&r.includes(t.expected),s=n?"passed":"failed",a=[{description:`Text contains "${t.expected}"`,detail:`Actual: "${r??"(not found)"}"`,status:s}],i=`agent-step-${String(e.stepIndex)}`,l={expected:{type:"static",value:t.expected},id:i,locator:{by:"css",value:t.selector},operator:"contains",type:"assertText"};return w({assertions:a,detail:n?`Text matches: "${t.expected}"`:`Expected "${t.expected}", got "${r??"(not found)"}"`,duration:performance.now()-o,nodeType:"assertText",page:e.page,runStartTime:e.runStartTime,specNode:l,status:s,stepIndex:e.stepIndex,title:`Assert text: ${t.selector}`})}})});import{z as Ft}from"zod";function Ka({actual:e,expected:t,operator:o}){return o==="equals"?e===t:o==="contains"?e.includes(t):o==="startsWith"?e.startsWith(t):o==="endsWith"?e.endsWith(t):!1}var Ya,wr,br=m(()=>{"use strict";v();Ya=Ft.object({expected:Ft.string().describe("Expected page title or substring"),operator:Ft.enum(["equals","contains","startsWith","endsWith"]).describe("Comparison operator").default("contains")}),wr=g({description:"Assert that the page title matches an expected value",name:"assert_title",schema:Ya,execute:async(e,t)=>{let o=performance.now(),r=await e.page.title(),n=Ka({actual:r,expected:t.expected,operator:t.operator}),s=n?"passed":"failed",a=[{description:`Title ${t.operator} "${t.expected}"`,detail:n?void 0:`Got: "${r}"`,status:s}],i=`agent-step-${String(e.stepIndex)}`,l={expected:{type:"static",value:t.expected},id:i,operator:t.operator,type:"assertTitle"};return w({assertions:a,detail:n?"Title matches":`Expected title ${t.operator} "${t.expected}", got "${r}"`,duration:performance.now()-o,nodeType:"assertTitle",page:e.page,runStartTime:e.runStartTime,specNode:l,status:s,stepIndex:e.stepIndex,title:`Assert title ${t.operator} "${t.expected}"`})}})});import{z as Sr}from"zod";var Qa,kr,Rr=m(()=>{"use strict";v();Qa=Sr.object({selector:Sr.string().describe("CSS selector for the element to check")}),kr=g({description:"Assert that an element matching the selector is visible on the page",name:"assert_visible",schema:Qa,execute:async(e,t)=>{let o=performance.now(),r=await e.page.locator(t.selector).isVisible().catch(()=>!1),n=r?"passed":"failed",s=[{description:`Element ${t.selector} is visible`,detail:r?"Element is visible":"Element is not visible",status:n}],i={id:`agent-step-${String(e.stepIndex)}`,locator:{by:"css",value:t.selector},type:"assertVisible"};return w({assertions:s,detail:r?"Element is visible":"Element is not visible",duration:performance.now()-o,nodeType:"assertVisible",page:e.page,runStartTime:e.runStartTime,specNode:i,status:n,stepIndex:e.stepIndex,title:`Assert visible: ${t.selector}`})}})});import{z as vr}from"zod";var Za,Pr,xr=m(()=>{"use strict";v();Za=vr.object({selector:vr.string().describe("CSS selector for the checkbox to check")}),Pr=g({description:"Check a checkbox matching the CSS selector",name:"check",schema:Za,execute:async(e,t)=>{let o=performance.now();await e.page.locator(t.selector).check({timeout:5e3});let n={id:`agent-step-${String(e.stepIndex)}`,locator:{by:"css",value:t.selector},type:"check"};return w({assertions:[],detail:`Checked ${t.selector}`,duration:performance.now()-o,nodeType:"check",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Check ${t.selector}`})}})});import{z as Tr}from"zod";var Xa,Cr,Ir=m(()=>{"use strict";v();Xa=Tr.object({selector:Tr.string().describe("CSS selector for the input to clear")}),Cr=g({description:"Clear the contents of an input field",name:"clear",schema:Xa,execute:async(e,t)=>{let o=performance.now();await e.page.locator(t.selector).clear({timeout:5e3});let n={id:`agent-step-${String(e.stepIndex)}`,locator:{by:"css",value:t.selector},type:"clear"};return w({assertions:[],detail:`Cleared ${t.selector}`,duration:performance.now()-o,nodeType:"clear",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Clear ${t.selector}`})}})});import{z as Ar}from"zod";var ei,Nr,jr=m(()=>{"use strict";v();ei=Ar.object({selector:Ar.string().describe("CSS selector for the element to click")}),Nr=g({description:"Click an element matching the CSS selector",name:"click",schema:ei,execute:async(e,t)=>{let o=performance.now();await e.page.locator(t.selector).click({timeout:5e3});let n={id:`agent-step-${String(e.stepIndex)}`,locator:{by:"css",value:t.selector},type:"click"};return w({assertions:[],detail:`Clicked ${t.selector}`,duration:performance.now()-o,nodeType:"click",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Click ${t.selector}`})}})});import{z as Vt}from"zod";var ti,$r,Er=m(()=>{"use strict";v();ti=Vt.object({action:Vt.enum(["read","write"]).describe("Whether to read from or write to the clipboard"),value:Vt.string().optional().describe("Text to write (required for write action)")}),$r=g({description:"Read from or write to the browser clipboard. For write, provide the text value. For read, the clipboard contents are returned.",name:"clipboard",schema:ti,execute:async(e,t)=>{let o=performance.now(),r=`agent-step-${String(e.stepIndex)}`;if(t.action==="write"){if(t.value==null)throw new Error("clipboard write requires a value");let a=JSON.stringify(t.value);await e.page.evaluate(`navigator.clipboard.writeText(${a})`);let i={action:"write",id:r,type:"clipboard",value:{type:"static",value:t.value}};return w({assertions:[],detail:`Wrote to clipboard: "${t.value}"`,duration:performance.now()-o,nodeType:"clipboard",page:e.page,runStartTime:e.runStartTime,specNode:i,status:"passed",stepIndex:e.stepIndex,title:"Clipboard write"})}let n=String(await e.page.evaluate("navigator.clipboard.readText()")),s={action:"read",id:r,type:"clipboard"};return w({assertions:[],detail:`Clipboard contents: "${n}"`,duration:performance.now()-o,nodeType:"clipboard",page:e.page,runStartTime:e.runStartTime,specNode:s,status:"passed",stepIndex:e.stepIndex,title:"Clipboard read"})}})});import{z as rt}from"zod";var Or,Ur,Fr=m(()=>{"use strict";Or=rt.object({summary:rt.string().describe("This is the ONLY output the user sees. If the agent profile specifies an Output format, follow those instructions exactly. Otherwise, provide a summary of your findings."),verdict:rt.enum(["pass","fail"]).describe("Whether the test passed or failed. If the agent profile defines Success Criteria, base this verdict on whether those criteria were met.")}),Ur={anthropicTool:{description:"Call this tool when you have finished your evaluation. If the agent profile defines an Output section, the summary MUST follow those output instructions exactly. Otherwise, summarize your findings.",input_schema:{...rt.toJSONSchema(Or,{target:"draft-2020-12"}),type:"object"},name:"complete_test"},name:"complete_test",execute(e,t){let o=Or.parse(t),r={kind:"verdict",summary:o.summary,toolOutput:`Verdict: ${o.verdict}
4
- ${o.summary}`,verdict:o.verdict};return Promise.resolve(r)}}});import{z as Vr}from"zod";var oi,Dr,Wr=m(()=>{"use strict";v();oi=Vr.object({selector:Vr.string().describe("CSS selector for the element to extract text from")}),Dr=g({description:"Extract the text content of an element matching the CSS selector. Returns the text so you can use it in assertions or decisions.",name:"extract_text",schema:oi,execute:async(e,t)=>{let o=performance.now(),n=await e.page.locator(t.selector).textContent({timeout:5e3})??"",a={id:`agent-step-${String(e.stepIndex)}`,locator:{by:"css",value:t.selector},type:"extractText",variable:"extractedText"};return w({assertions:[],detail:`Extracted text: "${n}"`,duration:performance.now()-o,nodeType:"extractText",page:e.page,runStartTime:e.runStartTime,specNode:a,status:"passed",stepIndex:e.stepIndex,title:`Extract text from ${t.selector}`})}})});import{z as Dt}from"zod";var ri,Lr,_r=m(()=>{"use strict";v();ri=Dt.object({selector:Dt.string().describe("CSS selector for the input element"),value:Dt.string().describe("The text to type into the element")}),Lr=g({description:"Clear and type text into an input element matching the CSS selector",name:"fill",schema:ri,execute:async(e,t)=>{let o=performance.now();await e.page.locator(t.selector).fill(t.value,{timeout:5e3});let n={id:`agent-step-${String(e.stepIndex)}`,locator:{by:"css",value:t.selector},type:"fill",value:{type:"static",value:t.value}};return w({assertions:[],detail:`Filled ${t.selector} with "${t.value}"`,duration:performance.now()-o,nodeType:"fill",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Fill ${t.selector}`})}})});import{z as qr}from"zod";function si(e){let t=e.url.length>0?` (${e.url})`:"";return`[${e.level.toUpperCase()}] ${e.text}${t}`}var ni,Br,Mr=m(()=>{"use strict";v();ni=qr.object({level:qr.string().describe("Filter by log level: 'error', 'warning', 'log', 'info', 'debug', or 'all'").default("all")}),Br=g({description:"Get console log messages from the browser. Optionally filter by level (error, warning, log, info, debug, all).",name:"get_console_logs",schema:ni,execute:(e,t)=>{let o=t.level==="all"?e.monitor.consoleEntries:e.monitor.consoleEntries.filter(n=>n.level===t.level);if(o.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:`No console ${t.level==="all"?"messages":t.level+" messages"} recorded.`};let r=o.map(n=>si(n)).join(`
5
- `);return{specNode:void 0,stepResult:void 0,toolOutput:`${String(o.length)} console messages:
6
- ${r}`}}})});import{z as Gr}from"zod";var Wt,ai,zr,Hr=m(()=>{"use strict";v();Wt=50,ai=Gr.object({urlFilter:Gr.string().describe("Optional regex to filter network entries by URL. Omit to see all.").default("")}),zr=g({description:"Get a summary of network requests/responses. Shows method, URL, status code, and content type. Optionally filter by URL regex.",name:"get_network_log",schema:ai,execute:(e,t)=>{let o=t.urlFilter.length>0?new RegExp(t.urlFilter,"i"):void 0,r=o==null?e.monitor.networkEntries:e.monitor.networkEntries.filter(i=>o.test(i.url));if(r.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:"No network requests recorded."};let n=r.slice(-Wt),s=n.map(i=>{let l=i.statusCode==null?"pending":String(i.statusCode),c=i.responseHeaders["content-type"]??"";return`${i.method} ${l} ${i.url} [${c}]`}).join(`
7
- `),a=r.length>Wt?`
8
- (showing last ${String(Wt)} of ${String(r.length)})`:"";return{specNode:void 0,stepResult:void 0,toolOutput:`${String(n.length)} network requests:${a}
9
- ${s}`}}})});import{z as Jr}from"zod";var ii,Yr,Kr=m(()=>{"use strict";v();ii=Jr.object({urlPattern:Jr.string().describe("Regex pattern to match the request URL")}),Yr=g({description:"Get the full response body for a specific network request matching the URL pattern. Returns the most recent match.",name:"get_network_response",schema:ii,execute:(e,t)=>{let o=new RegExp(t.urlPattern,"i"),r=e.monitor.networkEntries.filter(l=>o.test(l.url));if(r.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:`No network requests matching: ${t.urlPattern}`};let n=r.at(-1);if(n==null)return{specNode:void 0,stepResult:void 0,toolOutput:`No network requests matching: ${t.urlPattern}`};let s=n.statusCode==null?"pending":String(n.statusCode),a=Object.entries(n.responseHeaders).map(([l,c])=>` ${l}: ${c}`).join(`
2
+ var ti=Object.create;var Jt=Object.defineProperty;var ri=Object.getOwnPropertyDescriptor;var oi=Object.getOwnPropertyNames;var ni=Object.getPrototypeOf,si=Object.prototype.hasOwnProperty;var y=(e,t)=>()=>(e&&(t=e(e=0)),t);var mt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ai=(e,t)=>{for(var r in t)Jt(e,r,{get:t[r],enumerable:!0})},ii=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of oi(t))!si.call(e,n)&&n!==r&&Jt(e,n,{get:()=>t[n],enumerable:!(o=ri(t,n))||o.enumerable});return e};var li=(e,t,r)=>(r=e!=null?ti(ni(e)):{},ii(t||!e||!e.__esModule?Jt(r,"default",{value:e,enumerable:!0}):r,e));function T({locator:e,page:t}){switch(e.by){case"css":return t.locator(e.value);case"testId":return t.getByTestId(e.value);case"role":return t.getByRole(e.role,{exact:e.exact,name:e.name});case"text":return t.getByText(e.value,{exact:e.exact});case"label":return t.getByLabel(e.value,{exact:e.exact});case"placeholder":return t.getByPlaceholder(e.value);case"altText":return t.getByAltText(e.value)}}var me=y(()=>{"use strict"});function qe({defs:e}){return e==null?{}:Object.fromEntries(Object.entries(e).map(([t,r])=>[t,di({def:r,name:t})]))}function di({def:e,name:t}){if(e.type==="env"){let r=process.env[e.key];if(r==null)throw new Error(`Environment variable "${e.key}" not set for variable "${t}"`);return r}return e.default??ci[e.type]??""}function ke({ref:e,variables:t}){if(e.type==="static")return e.value;let r=t[e.name];if(r==null)throw new Error(`Variable "${e.name}" is not defined`);return r}function E({ref:e,variables:t}){let r=String(ke({ref:e,variables:t}));return ui({raw:r,variables:t})}function ui({raw:e,variables:t}){return e.replaceAll(/\{\{(\w+)\}\}/g,(r,o)=>{let n=t[o];if(n==null)throw new Error(`Template variable "{{${o}}}" is not defined`);return String(n)})}function Kt({ref:e,variables:t}){let r=ke({ref:e,variables:t});if(typeof r=="number")return r;let o=Number(r);if(Number.isNaN(o))throw new TypeError(`Cannot convert "${String(r)}" to number`);return o}function de({name:e,store:t,value:r}){return{...t,[e]:r}}var ci,se=y(()=>{"use strict";ci={boolean:!1,number:0,string:""}});async function wo({node:e,page:t,timeout:r}){await T({locator:e.source,page:t}).dragTo(T({locator:e.target,page:t}),{timeout:r})}async function bo({node:e,page:t,timeout:r}){await T({locator:e.locator,page:t}).click({button:"right",timeout:r})}function So({node:e,page:t,variables:r}){return t.once("dialog",async o=>{e.action==="accept"?await o.accept(e.promptText??void 0):await o.dismiss()}),{variables:r}}async function ko({node:e,page:t}){let r=e.x??0,o=e.y??0;if(e.locator==null){await t.mouse.wheel(r,o);return}let s=await T({locator:e.locator,page:t}).elementHandle();if(s==null)throw new Error("scroll target element not found");await s.evaluate("([dx, dy]) => this.scrollBy(dx, dy)",[r,o])}async function vo({node:e,page:t,variables:r}){if(e.action==="write"){if(e.value==null)throw new Error("clipboard write requires a value");let n=E({ref:e.value,variables:r}),s=JSON.stringify(n);return await t.evaluate(`navigator.clipboard.writeText(${s})`),{variables:r}}if(e.variable==null)throw new Error("clipboard read requires a variable name to store the result");let o=String(await t.evaluate("navigator.clipboard.readText()"));return{variables:de({name:e.variable,store:r,value:o})}}async function Ro({node:e,page:t}){let r=t.context();e.state==="granted"?await r.grantPermissions([e.permission]):await r.clearPermissions()}var Po=y(()=>{"use strict";me();se()});async function Yt({node:e,page:t,timeout:r,variables:o}){switch(e.type){case"click":case"check":case"uncheck":case"clear":case"dblclick":case"focus":case"hover":case"scrollIntoView":return fi({node:e,page:t,timeout:r,variables:o});case"rightClick":return await bo({node:e,page:t,timeout:r}),{variables:o};case"goto":{let n=E({ref:e.url,variables:o});return await t.goto(n,{timeout:r,waitUntil:"domcontentloaded"}),{variables:o}}case"fill":{let n=E({ref:e.value,variables:o});return await T({locator:e.locator,page:t}).fill(n,{timeout:r}),{variables:o}}case"select":{let n=E({ref:e.value,variables:o});return await T({locator:e.locator,page:t}).selectOption(n,{timeout:r}),{variables:o}}case"type":{let n=E({ref:e.value,variables:o});return await T({locator:e.locator,page:t}).pressSequentially(n,{timeout:r}),{variables:o}}case"press":return await hi({node:e,page:t,timeout:r}),{variables:o};case"drag":return await wo({node:e,page:t,timeout:r}),{variables:o};case"upload":return await T({locator:e.locator,page:t}).setInputFiles(e.files,{timeout:r}),{variables:o};case"extractText":{let n=await T({locator:e.locator,page:t}).textContent({timeout:r});if(n==null)throw new Error("extractText: element had no text content");return{variables:de({name:e.variable,store:o,value:n})}}case"setVariable":{let n=ke({ref:e.value,variables:o});return{variables:de({name:e.variable,store:o,value:n})}}case"fail":throw new Error(e.message);case"waitFor":return await T({locator:e.locator,page:t}).waitFor({state:e.state??"visible",timeout:r}),{variables:o};case"waitForUrl":{let n=E({ref:e.expected,variables:o});return await t.waitForURL(mi({expected:n,operator:e.operator}),{timeout:r}),{variables:o}}case"waitForResponse":{let n=E({ref:e.urlPattern,variables:o});return await t.waitForResponse(s=>s.url().includes(n),{timeout:r}),{variables:o}}case"waitForRequest":{let n=E({ref:e.urlPattern,variables:o});return await t.waitForRequest(s=>s.url().includes(n),{timeout:r}),{variables:o}}case"wait":return await t.waitForTimeout(e.duration),{variables:o};case"screenshot":return await t.screenshot(),{variables:o};case"setViewport":return await t.setViewportSize({height:e.height,width:e.width}),{variables:o};case"handleDialog":return So({node:e,page:t,variables:o});case"scroll":return await ko({node:e,page:t}),{variables:o};case"clipboard":return vo({node:e,page:t,variables:o});case"setPermission":return await Ro({node:e,page:t}),{variables:o}}}async function fi({node:e,page:t,timeout:r,variables:o}){return await T({locator:e.locator,page:t})[pi[e.type]]({timeout:r}),{variables:o}}function mi({expected:e,operator:t}){return r=>{let o=r.toString();return t==="equals"?o===e:t==="notEquals"?o!==e:t==="contains"?o.includes(e):t==="startsWith"?o.startsWith(e):t==="endsWith"?o.endsWith(e):new RegExp(e).test(o)}}async function hi({node:e,page:t,timeout:r}){e.locator==null?await t.keyboard.press(e.key):await T({locator:e.locator,page:t}).press(e.key,{timeout:r})}var pi,Qt=y(()=>{"use strict";Po();me();se();pi={check:"check",clear:"clear",click:"click",dblclick:"dblclick",focus:"focus",hover:"hover",scrollIntoView:"scrollIntoViewIfNeeded",uncheck:"uncheck"}});async function he({page:e,runStartTime:t,targets:r}){let o=e.viewportSize();if(o==null)throw new Error("Page has no viewport set");let[n,s]=await Promise.all([e.screenshot({type:"png"}),yi(r)]),a=n.toString("base64");return{annotations:s,screenshotBase64:a,snapshotTimestamp:Math.round(performance.now()-t),url:e.url(),viewportHeight:o.height,viewportWidth:o.width}}function gi(e){return"locator"in e}async function yi(e){return(await Promise.all(e.map(r=>wi(r)))).filter(r=>r!=null)}async function wi(e){if(!gi(e))return{height:0,label:e.label,type:e.type,width:0,x:0,y:0};let t=await e.locator.boundingBox({timeout:2e3}).catch(()=>null);if(t!=null)return{height:Math.round(t.height),label:e.label,type:e.type,width:Math.round(t.width),x:Math.round(t.x),y:Math.round(t.y)}}function ht({node:e,page:t}){if(e.type==="assertUrl"||e.type==="waitForUrl")return[{label:e.type,type:"urlBar"}];if(e.type==="drag"){let n=T({locator:e.source,page:t}),s=T({locator:e.target,page:t});return[{label:"drag-source",locator:n,type:"action"},{label:"drag-target",locator:s,type:"action"}]}if(!bi(e))return[];let r=e.type.startsWith("assert")?"assertion":"action",o=T({locator:e.locator,page:t});return[{label:e.type,locator:o,type:r}]}function bi(e){return"locator"in e&&e.locator!=null}var Be=y(()=>{"use strict";me()});import{z as Si}from"zod";function w({description:e,execute:t,name:r,schema:o}){let n=Si.toJSONSchema(o,{target:"draft-2020-12"});return{anthropicTool:{description:e,input_schema:{...n,type:"object"},name:r},name:r,async execute(s,a){let i=o.parse(a);return{...await Promise.resolve(t(s,i)),kind:"action"}}}}async function v(e){let t=e.specNode==null?[]:ht({node:e.specNode,page:e.page}),r=await he({page:e.page,runStartTime:e.runStartTime,targets:t}),o=[...e.assertions],n={annotations:r.annotations,assertions:o,detail:e.detail,duration:Math.round(e.duration),nodeId:`agent-step-${String(e.stepIndex)}`,nodeType:e.nodeType,screenshotBase64:r.screenshotBase64,snapshotTimestamp:r.snapshotTimestamp,status:e.status,stepIndex:e.stepIndex,title:e.title,url:r.url,viewportHeight:r.viewportHeight,viewportWidth:r.viewportWidth},s=o.length>0?o.map(a=>`${a.status}: ${a.description} \u2014 ${a.detail??""}`).join(`
3
+ `):`${e.status}: ${e.title}`;return{specNode:e.specNode,stepResult:n,toolOutput:s}}var C=y(()=>{"use strict";Be()});import{z as xo}from"zod";var ki,Co,To=y(()=>{"use strict";C();ki=xo.object({selector:xo.string().describe("CSS selector for the checkbox or radio button")}),Co=w({description:"Assert that a checkbox or radio button is checked",name:"assert_checked",schema:ki,execute:async(e,t)=>{let r=performance.now(),o=await e.page.locator(t.selector).isChecked().catch(()=>!1),n=o?"passed":"failed",s=[{description:`Element ${t.selector} is checked`,detail:o?void 0:"Element is not checked",status:n}],i={id:`agent-step-${String(e.stepIndex)}`,locator:{by:"css",value:t.selector},type:"assertChecked"};return v({assertions:s,detail:o?"Element is checked":"Element is not checked",duration:performance.now()-r,nodeType:"assertChecked",page:e.page,runStartTime:e.runStartTime,specNode:i,status:n,stepIndex:e.stepIndex,title:`Assert checked: ${t.selector}`})}})});import{z as xe}from"zod";function Ri({cookie:e,input:t}){return[Pi(t.value,e.value),Io("httpOnly",t.httpOnly,e.httpOnly),Io("secure",t.secure,e.secure),xi("sameSite",t.sameSite,e.sameSite)].filter(r=>r!=null)}function Pi(e,t){if(e==null)return;let r=t.includes(e);return{description:`Cookie value contains "${e}"`,detail:r?void 0:`Got: "${t}"`,status:r?"passed":"failed"}}function Io(e,t,r){if(t!=null)return{description:`Cookie ${e} is ${String(t)}`,detail:r===t?void 0:`Got: ${String(r)}`,status:r===t?"passed":"failed"}}function xi(e,t,r){if(t!=null)return{description:`Cookie ${e} is ${t}`,detail:r===t?void 0:`Got: ${r}`,status:r===t?"passed":"failed"}}var vi,Ao,No=y(()=>{"use strict";C();vi=xe.object({httpOnly:xe.boolean().optional().describe("Assert httpOnly flag value"),name:xe.string().describe("Cookie name to check"),sameSite:xe.enum(["Strict","Lax","None"]).optional().describe("Assert sameSite value"),secure:xe.boolean().optional().describe("Assert secure flag value"),value:xe.string().optional().describe("Expected cookie value (substring match)")}),Ao=w({description:"Assert properties of a browser cookie. Check existence, value, and security flags (httpOnly, secure, sameSite).",name:"assert_cookie",schema:vi,execute:async(e,t)=>{let r=performance.now(),n=(await e.page.context().cookies()).find(p=>p.name===t.name),s=n==null?[{description:`Cookie "${t.name}" exists`,detail:"Cookie not found",status:"failed"}]:[{description:`Cookie "${t.name}" exists`,detail:void 0,status:"passed"},...Ri({cookie:n,input:t})],a=s.some(p=>p.status==="failed"),i=a?"failed":"passed",c={id:`agent-step-${String(e.stepIndex)}`,name:{type:"static",value:t.name},type:"assertCookie"};return v({assertions:s,detail:a?s.filter(p=>p.status==="failed").map(p=>p.detail).join("; "):"Cookie OK",duration:performance.now()-r,nodeType:"assertCookie",page:e.page,runStartTime:e.runStartTime,specNode:c,status:i,stepIndex:e.stepIndex,title:`Assert cookie: ${t.name}`})}})});import{z as jo}from"zod";var Ci,$o,Eo=y(()=>{"use strict";C();Ci=jo.object({selector:jo.string().describe("CSS selector for the element to check focus on")}),$o=w({description:"Assert that an element has keyboard focus. Use for accessibility tab-order testing.",name:"assert_focused",schema:Ci,execute:async(e,t)=>{let r=performance.now(),n=!!await e.page.locator(t.selector).evaluate("(el) => document.activeElement === el").catch(()=>!1),s=n?"passed":"failed",a=[{description:`Element ${t.selector} is focused`,detail:n?void 0:"Element does not have focus",status:s}],l={id:`agent-step-${String(e.stepIndex)}`,locator:{by:"css",value:t.selector},type:"assertFocused"};return v({assertions:a,detail:n?"Element is focused":"Element does not have focus",duration:performance.now()-r,nodeType:"assertFocused",page:e.page,runStartTime:e.runStartTime,specNode:l,status:s,stepIndex:e.stepIndex,title:`Assert focused: ${t.selector}`})}})});import{z as Ce}from"zod";function Ii(e,t){if(e!=null)return{description:`Response status equals ${String(e)}`,detail:t===e?void 0:`Got: ${String(t)}`,status:t===e?"passed":"failed"}}async function Ai(e,t){if(e==null)return;let o=(await t.text()).includes(e);return{description:`Response body contains "${e}"`,detail:o?void 0:"Not found in response body",status:o?"passed":"failed"}}function Ni(e,t,r){if(e==null||t==null)return;let o=r[e.toLowerCase()],n=o!=null&&o.includes(t);return{description:`Response header "${e}" contains "${t}"`,detail:n?void 0:`Got: "${o??"(missing)"}"`,status:n?"passed":"failed"}}var Ti,Oo,Uo=y(()=>{"use strict";C();Ti=Ce.object({bodyContains:Ce.string().optional().describe("Assert response body contains this string"),headerName:Ce.string().optional().describe("Response header name to check"),headerValue:Ce.string().optional().describe("Expected value the header should contain"),status:Ce.number().int().optional().describe("Expected HTTP status code"),urlPattern:Ce.string().describe("URL substring to match the response against")}),Oo=w({description:"Wait for a network response matching the URL pattern and assert on its status, body, or headers. Useful for verifying API calls and security headers (CSP, CORS).",name:"assert_response",schema:Ti,execute:async(e,t)=>{let r=performance.now(),o=await e.page.waitForResponse(c=>c.url().includes(t.urlPattern),{timeout:1e4}),n=[Ii(t.status,o.status()),await Ai(t.bodyContains,o),Ni(t.headerName,t.headerValue,o.headers())].filter(c=>c!=null),s=n.length===0?[{description:`Response matching "${t.urlPattern}" received`,detail:void 0,status:"passed"}]:n,a=s.some(c=>c.status==="failed"),l={id:`agent-step-${String(e.stepIndex)}`,type:"assertResponse",urlPattern:{type:"static",value:t.urlPattern}};return v({assertions:s,detail:a?s.filter(c=>c.status==="failed").map(c=>c.detail).join("; "):"Response OK",duration:performance.now()-r,nodeType:"assertResponse",page:e.page,runStartTime:e.runStartTime,specNode:l,status:a?"failed":"passed",stepIndex:e.stepIndex,title:`Assert response: ${t.urlPattern}`})}})});import{z as Zt}from"zod";var ji,Fo,Do=y(()=>{"use strict";C();ji=Zt.object({expected:Zt.string().describe("The expected text content"),selector:Zt.string().describe("CSS selector for the element to check")}),Fo=w({description:"Assert that an element's text content matches the expected value",name:"assert_text",schema:ji,execute:async(e,t)=>{let r=performance.now(),o=await e.page.locator(t.selector).textContent({timeout:5e3}).catch(()=>null),n=o!=null&&o.includes(t.expected),s=n?"passed":"failed",a=[{description:`Text contains "${t.expected}"`,detail:`Actual: "${o??"(not found)"}"`,status:s}],i=`agent-step-${String(e.stepIndex)}`,l={expected:{type:"static",value:t.expected},id:i,locator:{by:"css",value:t.selector},operator:"contains",type:"assertText"};return v({assertions:a,detail:n?`Text matches: "${t.expected}"`:`Expected "${t.expected}", got "${o??"(not found)"}"`,duration:performance.now()-r,nodeType:"assertText",page:e.page,runStartTime:e.runStartTime,specNode:l,status:s,stepIndex:e.stepIndex,title:`Assert text: ${t.selector}`})}})});import{z as Xt}from"zod";function Ei({actual:e,expected:t,operator:r}){return r==="equals"?e===t:r==="contains"?e.includes(t):r==="startsWith"?e.startsWith(t):r==="endsWith"?e.endsWith(t):!1}var $i,Vo,_o=y(()=>{"use strict";C();$i=Xt.object({expected:Xt.string().describe("Expected page title or substring"),operator:Xt.enum(["equals","contains","startsWith","endsWith"]).describe("Comparison operator").default("contains")}),Vo=w({description:"Assert that the page title matches an expected value",name:"assert_title",schema:$i,execute:async(e,t)=>{let r=performance.now(),o=await e.page.title(),n=Ei({actual:o,expected:t.expected,operator:t.operator}),s=n?"passed":"failed",a=[{description:`Title ${t.operator} "${t.expected}"`,detail:n?void 0:`Got: "${o}"`,status:s}],i=`agent-step-${String(e.stepIndex)}`,l={expected:{type:"static",value:t.expected},id:i,operator:t.operator,type:"assertTitle"};return v({assertions:a,detail:n?"Title matches":`Expected title ${t.operator} "${t.expected}", got "${o}"`,duration:performance.now()-r,nodeType:"assertTitle",page:e.page,runStartTime:e.runStartTime,specNode:l,status:s,stepIndex:e.stepIndex,title:`Assert title ${t.operator} "${t.expected}"`})}})});import{z as Wo}from"zod";var Oi,Lo,qo=y(()=>{"use strict";C();Oi=Wo.object({selector:Wo.string().describe("CSS selector for the element to check")}),Lo=w({description:"Assert that an element matching the selector is visible on the page",name:"assert_visible",schema:Oi,execute:async(e,t)=>{let r=performance.now(),o=await e.page.locator(t.selector).isVisible().catch(()=>!1),n=o?"passed":"failed",s=[{description:`Element ${t.selector} is visible`,detail:o?"Element is visible":"Element is not visible",status:n}],i={id:`agent-step-${String(e.stepIndex)}`,locator:{by:"css",value:t.selector},type:"assertVisible"};return v({assertions:s,detail:o?"Element is visible":"Element is not visible",duration:performance.now()-r,nodeType:"assertVisible",page:e.page,runStartTime:e.runStartTime,specNode:i,status:n,stepIndex:e.stepIndex,title:`Assert visible: ${t.selector}`})}})});import{z as Bo}from"zod";var Ui,Mo,zo=y(()=>{"use strict";C();Ui=Bo.object({selector:Bo.string().describe("CSS selector for the checkbox to check")}),Mo=w({description:"Check a checkbox matching the CSS selector",name:"check",schema:Ui,execute:async(e,t)=>{let r=performance.now();await e.page.locator(t.selector).check({timeout:5e3});let n={id:`agent-step-${String(e.stepIndex)}`,locator:{by:"css",value:t.selector},type:"check"};return v({assertions:[],detail:`Checked ${t.selector}`,duration:performance.now()-r,nodeType:"check",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Check ${t.selector}`})}})});import{z as Go}from"zod";var Fi,Ho,Jo=y(()=>{"use strict";C();Fi=Go.object({selector:Go.string().describe("CSS selector for the input to clear")}),Ho=w({description:"Clear the contents of an input field",name:"clear",schema:Fi,execute:async(e,t)=>{let r=performance.now();await e.page.locator(t.selector).clear({timeout:5e3});let n={id:`agent-step-${String(e.stepIndex)}`,locator:{by:"css",value:t.selector},type:"clear"};return v({assertions:[],detail:`Cleared ${t.selector}`,duration:performance.now()-r,nodeType:"clear",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Clear ${t.selector}`})}})});import{z as Ko}from"zod";var Di,Yo,Qo=y(()=>{"use strict";C();Di=Ko.object({selector:Ko.string().describe("CSS selector for the element to click")}),Yo=w({description:"Click an element matching the CSS selector",name:"click",schema:Di,execute:async(e,t)=>{let r=performance.now();await e.page.locator(t.selector).click({timeout:5e3});let n={id:`agent-step-${String(e.stepIndex)}`,locator:{by:"css",value:t.selector},type:"click"};return v({assertions:[],detail:`Clicked ${t.selector}`,duration:performance.now()-r,nodeType:"click",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Click ${t.selector}`})}})});import{z as er}from"zod";var Vi,Zo,Xo=y(()=>{"use strict";C();Vi=er.object({action:er.enum(["read","write"]).describe("Whether to read from or write to the clipboard"),value:er.string().optional().describe("Text to write (required for write action)")}),Zo=w({description:"Read from or write to the browser clipboard. For write, provide the text value. For read, the clipboard contents are returned.",name:"clipboard",schema:Vi,execute:async(e,t)=>{let r=performance.now(),o=`agent-step-${String(e.stepIndex)}`;if(t.action==="write"){if(t.value==null)throw new Error("clipboard write requires a value");let a=JSON.stringify(t.value);await e.page.evaluate(`navigator.clipboard.writeText(${a})`);let i={action:"write",id:o,type:"clipboard",value:{type:"static",value:t.value}};return v({assertions:[],detail:`Wrote to clipboard: "${t.value}"`,duration:performance.now()-r,nodeType:"clipboard",page:e.page,runStartTime:e.runStartTime,specNode:i,status:"passed",stepIndex:e.stepIndex,title:"Clipboard write"})}let n=String(await e.page.evaluate("navigator.clipboard.readText()")),s={action:"read",id:o,type:"clipboard"};return v({assertions:[],detail:`Clipboard contents: "${n}"`,duration:performance.now()-r,nodeType:"clipboard",page:e.page,runStartTime:e.runStartTime,specNode:s,status:"passed",stepIndex:e.stepIndex,title:"Clipboard read"})}})});import{z as gt}from"zod";var en,tn,rn=y(()=>{"use strict";en=gt.object({summary:gt.string().describe("This is the ONLY output the user sees. If the agent profile specifies an Output format, follow those instructions exactly. Otherwise, provide a summary of your findings."),verdict:gt.enum(["pass","fail"]).describe("Whether the test passed or failed. If the agent profile defines Success Criteria, base this verdict on whether those criteria were met.")}),tn={anthropicTool:{description:"Call this tool when you have finished your evaluation. If the agent profile defines an Output section, the summary MUST follow those output instructions exactly. Otherwise, summarize your findings.",input_schema:{...gt.toJSONSchema(en,{target:"draft-2020-12"}),type:"object"},name:"complete_test"},name:"complete_test",execute(e,t){let r=en.parse(t),o={kind:"verdict",summary:r.summary,toolOutput:`Verdict: ${r.verdict}
4
+ ${r.summary}`,verdict:r.verdict};return Promise.resolve(o)}}});import{z as on}from"zod";var _i,nn,sn=y(()=>{"use strict";C();_i=on.object({selector:on.string().describe("CSS selector for the element to extract text from")}),nn=w({description:"Extract the text content of an element matching the CSS selector. Returns the text so you can use it in assertions or decisions.",name:"extract_text",schema:_i,execute:async(e,t)=>{let r=performance.now(),n=await e.page.locator(t.selector).textContent({timeout:5e3})??"",a={id:`agent-step-${String(e.stepIndex)}`,locator:{by:"css",value:t.selector},type:"extractText",variable:"extractedText"};return v({assertions:[],detail:`Extracted text: "${n}"`,duration:performance.now()-r,nodeType:"extractText",page:e.page,runStartTime:e.runStartTime,specNode:a,status:"passed",stepIndex:e.stepIndex,title:`Extract text from ${t.selector}`})}})});import{z as tr}from"zod";var Wi,an,ln=y(()=>{"use strict";C();Wi=tr.object({selector:tr.string().describe("CSS selector for the input element"),value:tr.string().describe("The text to type into the element")}),an=w({description:"Clear and type text into an input element matching the CSS selector",name:"fill",schema:Wi,execute:async(e,t)=>{let r=performance.now();await e.page.locator(t.selector).fill(t.value,{timeout:5e3});let n={id:`agent-step-${String(e.stepIndex)}`,locator:{by:"css",value:t.selector},type:"fill",value:{type:"static",value:t.value}};return v({assertions:[],detail:`Filled ${t.selector} with "${t.value}"`,duration:performance.now()-r,nodeType:"fill",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Fill ${t.selector}`})}})});import{z as cn}from"zod";function qi(e){let t=e.url.length>0?` (${e.url})`:"";return`[${e.level.toUpperCase()}] ${e.text}${t}`}var Li,dn,un=y(()=>{"use strict";C();Li=cn.object({level:cn.string().describe("Filter by log level: 'error', 'warning', 'log', 'info', 'debug', or 'all'").default("all")}),dn=w({description:"Get console log messages from the browser. Optionally filter by level (error, warning, log, info, debug, all).",name:"get_console_logs",schema:Li,execute:(e,t)=>{let r=t.level==="all"?e.monitor.consoleEntries:e.monitor.consoleEntries.filter(n=>n.level===t.level);if(r.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:`No console ${t.level==="all"?"messages":t.level+" messages"} recorded.`};let o=r.map(n=>qi(n)).join(`
5
+ `);return{specNode:void 0,stepResult:void 0,toolOutput:`${String(r.length)} console messages:
6
+ ${o}`}}})});import{z as pn}from"zod";var rr,Bi,fn,mn=y(()=>{"use strict";C();rr=50,Bi=pn.object({urlFilter:pn.string().describe("Optional regex to filter network entries by URL. Omit to see all.").default("")}),fn=w({description:"Get a summary of network requests/responses. Shows method, URL, status code, and content type. Optionally filter by URL regex.",name:"get_network_log",schema:Bi,execute:(e,t)=>{let r=t.urlFilter.length>0?new RegExp(t.urlFilter,"i"):void 0,o=r==null?e.monitor.networkEntries:e.monitor.networkEntries.filter(i=>r.test(i.url));if(o.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:"No network requests recorded."};let n=o.slice(-rr),s=n.map(i=>{let l=i.statusCode==null?"pending":String(i.statusCode),c=i.responseHeaders["content-type"]??"";return`${i.method} ${l} ${i.url} [${c}]`}).join(`
7
+ `),a=o.length>rr?`
8
+ (showing last ${String(rr)} of ${String(o.length)})`:"";return{specNode:void 0,stepResult:void 0,toolOutput:`${String(n.length)} network requests:${a}
9
+ ${s}`}}})});import{z as hn}from"zod";var Mi,gn,yn=y(()=>{"use strict";C();Mi=hn.object({urlPattern:hn.string().describe("Regex pattern to match the request URL")}),gn=w({description:"Get the full response body for a specific network request matching the URL pattern. Returns the most recent match.",name:"get_network_response",schema:Mi,execute:(e,t)=>{let r=new RegExp(t.urlPattern,"i"),o=e.monitor.networkEntries.filter(l=>r.test(l.url));if(o.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:`No network requests matching: ${t.urlPattern}`};let n=o.at(-1);if(n==null)return{specNode:void 0,stepResult:void 0,toolOutput:`No network requests matching: ${t.urlPattern}`};let s=n.statusCode==null?"pending":String(n.statusCode),a=Object.entries(n.responseHeaders).map(([l,c])=>` ${l}: ${c}`).join(`
10
10
  `),i=n.responseBody??"(no body captured)";return{specNode:void 0,stepResult:void 0,toolOutput:`${n.method} ${s} ${n.url}
11
11
 
12
12
  Response Headers:
13
13
  ${a}
14
14
 
15
15
  Body:
16
- ${i}`}}})});import{z as Qr}from"zod";var li,Zr,Xr=m(()=>{"use strict";v();li=Qr.object({selector:Qr.string().optional().describe("CSS selector to scope the tree to a subtree (defaults to full page)")}),Zr=g({description:"Get the accessibility tree (ARIA snapshot) of the current page or a specific element. Use this to verify ARIA roles, labels, states, and the semantic structure of the page.",name:"get_accessibility_tree",schema:li,execute:async(e,t)=>{let o=t.selector==null?e.page.locator(":root"):e.page.locator(t.selector);try{return{specNode:void 0,stepResult:void 0,toolOutput:await o.ariaSnapshot()}}catch{return{specNode:void 0,stepResult:void 0,toolOutput:"(unable to capture accessibility tree)"}}}})});import{z as ci}from"zod";var di,en,tn=m(()=>{"use strict";v();di=ci.object({}),en=g({description:"Get a text representation of the current page content for inspection",name:"get_page_content",schema:di,execute:async(e,t)=>{let o=await e.page.locator("body").textContent({timeout:5e3}),r=e.page.url(),n=await e.page.title();return{specNode:void 0,stepResult:void 0,toolOutput:`URL: ${r}
16
+ ${i}`}}})});import{z as wn}from"zod";var zi,bn,Sn=y(()=>{"use strict";C();zi=wn.object({selector:wn.string().optional().describe("CSS selector to scope the tree to a subtree (defaults to full page)")}),bn=w({description:"Get the accessibility tree (ARIA snapshot) of the current page or a specific element. Use this to verify ARIA roles, labels, states, and the semantic structure of the page.",name:"get_accessibility_tree",schema:zi,execute:async(e,t)=>{let r=t.selector==null?e.page.locator(":root"):e.page.locator(t.selector);try{return{specNode:void 0,stepResult:void 0,toolOutput:await r.ariaSnapshot()}}catch{return{specNode:void 0,stepResult:void 0,toolOutput:"(unable to capture accessibility tree)"}}}})});import{z as Gi}from"zod";var Hi,kn,vn=y(()=>{"use strict";C();Hi=Gi.object({}),kn=w({description:"Get a text representation of the current page content for inspection",name:"get_page_content",schema:Hi,execute:async(e,t)=>{let r=await e.page.locator("body").textContent({timeout:5e3}),o=e.page.url(),n=await e.page.title();return{specNode:void 0,stepResult:void 0,toolOutput:`URL: ${o}
17
17
  Title: ${n}
18
18
 
19
- ${o??""}`}}})});import{z as ui}from"zod";var pi,on,rn=m(()=>{"use strict";v();pi=ui.object({}),on=g({description:"Get uncaught JavaScript exceptions (page errors) that have occurred. These are runtime errors thrown in the browser that were not caught by error handlers.",name:"get_page_errors",schema:pi,execute:(e,t)=>{if(e.monitor.pageErrors.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:"No page errors recorded."};let o=e.monitor.pageErrors.map((r,n)=>`--- Error ${String(n+1)} ---
20
- ${r}`).join(`
19
+ ${r??""}`}}})});import{z as Ji}from"zod";var Ki,Rn,Pn=y(()=>{"use strict";C();Ki=Ji.object({}),Rn=w({description:"Get uncaught JavaScript exceptions (page errors) that have occurred. These are runtime errors thrown in the browser that were not caught by error handlers.",name:"get_page_errors",schema:Ki,execute:(e,t)=>{if(e.monitor.pageErrors.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:"No page errors recorded."};let r=e.monitor.pageErrors.map((o,n)=>`--- Error ${String(n+1)} ---
20
+ ${o}`).join(`
21
21
 
22
22
  `);return{specNode:void 0,stepResult:void 0,toolOutput:`${String(e.monitor.pageErrors.length)} page errors:
23
23
 
24
- ${o}`}}})});import{z as nn}from"zod";async function mi(e){let t=await e.context().cookies();if(t.length===0)return`## Cookies
25
- (none)`;let o=t.map(r=>` ${r.name}=${r.value} (domain=${r.domain}, httpOnly=${String(r.httpOnly)}, secure=${String(r.secure)}, sameSite=${r.sameSite})`);return`## Cookies (${String(t.length)})
26
- ${o.join(`
27
- `)}`}async function sn(e,t){let o=await e.evaluate(`JSON.stringify(Object.fromEntries(Object.entries(${t})))`);return`## ${t}
28
- ${String(o)}`}var fi,an,ln=m(()=>{"use strict";v();fi=nn.object({type:nn.enum(["all","cookies","localStorage","sessionStorage"]).describe("Which storage to retrieve").default("all")}),an=g({description:"Get browser storage state: cookies (with httpOnly, secure, sameSite flags), localStorage, and/or sessionStorage. Useful for verifying authentication state, security cookie flags, and stored data.",name:"get_storage",schema:fi,execute:async(e,t)=>({specNode:void 0,stepResult:void 0,toolOutput:[...t.type==="all"||t.type==="cookies"?[await mi(e.page)]:[],...t.type==="all"||t.type==="localStorage"?[await sn(e.page,"localStorage")]:[],...t.type==="all"||t.type==="sessionStorage"?[await sn(e.page,"sessionStorage")]:[]].join(`
24
+ ${r}`}}})});import{z as xn}from"zod";async function Qi(e){let t=await e.context().cookies();if(t.length===0)return`## Cookies
25
+ (none)`;let r=t.map(o=>` ${o.name}=${o.value} (domain=${o.domain}, httpOnly=${String(o.httpOnly)}, secure=${String(o.secure)}, sameSite=${o.sameSite})`);return`## Cookies (${String(t.length)})
26
+ ${r.join(`
27
+ `)}`}async function Cn(e,t){let r=await e.evaluate(`JSON.stringify(Object.fromEntries(Object.entries(${t})))`);return`## ${t}
28
+ ${String(r)}`}var Yi,Tn,In=y(()=>{"use strict";C();Yi=xn.object({type:xn.enum(["all","cookies","localStorage","sessionStorage"]).describe("Which storage to retrieve").default("all")}),Tn=w({description:"Get browser storage state: cookies (with httpOnly, secure, sameSite flags), localStorage, and/or sessionStorage. Useful for verifying authentication state, security cookie flags, and stored data.",name:"get_storage",schema:Yi,execute:async(e,t)=>({specNode:void 0,stepResult:void 0,toolOutput:[...t.type==="all"||t.type==="cookies"?[await Qi(e.page)]:[],...t.type==="all"||t.type==="localStorage"?[await Cn(e.page,"localStorage")]:[],...t.type==="all"||t.type==="sessionStorage"?[await Cn(e.page,"sessionStorage")]:[]].join(`
29
29
 
30
- `)})})});import{z as Lt}from"zod";var gi,cn,dn=m(()=>{"use strict";v();gi=Lt.object({action:Lt.enum(["accept","dismiss"]).describe("Whether to accept or dismiss the dialog"),promptText:Lt.string().optional().describe("Text to enter for prompt dialogs")}),cn=g({description:"Set up a handler for the next browser dialog (alert, confirm, prompt). Call this BEFORE the action that triggers the dialog.",name:"handle_dialog",schema:gi,execute:(e,t)=>{let o=performance.now();e.page.once("dialog",async s=>{t.action==="accept"?await s.accept(t.promptText??void 0):await s.dismiss()});let r=`agent-step-${String(e.stepIndex)}`,n={action:t.action,id:r,type:"handleDialog"};return w({assertions:[],detail:`Dialog handler set: ${t.action}`,duration:performance.now()-o,nodeType:"handleDialog",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Handle dialog: ${t.action}`})}})});import{z as un}from"zod";var hi,pn,fn=m(()=>{"use strict";v();hi=un.object({selector:un.string().describe("CSS selector for the element to hover over")}),pn=g({description:"Hover over an element matching the CSS selector",name:"hover",schema:hi,execute:async(e,t)=>{let o=performance.now();await e.page.locator(t.selector).hover({timeout:5e3});let n={id:`agent-step-${String(e.stepIndex)}`,locator:{by:"css",value:t.selector},type:"hover"};return w({assertions:[],detail:`Hovered over ${t.selector}`,duration:performance.now()-o,nodeType:"hover",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Hover ${t.selector}`})}})});import{z as _t}from"zod";var yi,mn,gn=m(()=>{"use strict";v();yi=_t.object({permission:_t.string().describe("Permission name (e.g. geolocation, notifications, camera, clipboard-read)"),state:_t.enum(["granted","prompt"]).describe("Permission state to set")}),mn=g({description:"Set a browser permission state (geolocation, notifications, camera, etc.)",name:"set_permission",schema:yi,execute:async(e,t)=>{let o=performance.now(),r=e.page.context();t.state==="granted"?await r.grantPermissions([t.permission]):await r.clearPermissions();let s={id:`agent-step-${String(e.stepIndex)}`,permission:t.permission,state:t.state,type:"setPermission"};return w({assertions:[],detail:`Set ${t.permission} to ${t.state}`,duration:performance.now()-o,nodeType:"setPermission",page:e.page,runStartTime:e.runStartTime,specNode:s,status:"passed",stepIndex:e.stepIndex,title:`Set permission: ${t.permission} \u2192 ${t.state}`})}})});import{z as hn}from"zod";var wi,yn,wn=m(()=>{"use strict";v();wi=hn.object({url:hn.string().describe("The URL to navigate to")}),yn=g({description:"Navigate the browser to a URL",name:"navigate",schema:wi,execute:async(e,t)=>{let o=performance.now();await e.page.goto(t.url,{waitUntil:"domcontentloaded"});let n={id:`agent-step-${String(e.stepIndex)}`,type:"goto",url:{type:"static",value:t.url}};return w({assertions:[],detail:`Navigated to ${t.url}`,duration:performance.now()-o,nodeType:"goto",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Navigate to ${t.url}`})}})});import{z as bn}from"zod";var bi,Sn,kn=m(()=>{"use strict";v();bi=bn.object({key:bn.string().describe("Key to press, e.g. 'Enter', 'Tab', 'Escape'")}),Sn=g({description:"Press a keyboard key",name:"press",schema:bi,execute:async(e,t)=>{let o=performance.now();await e.page.keyboard.press(t.key);let n={id:`agent-step-${String(e.stepIndex)}`,key:t.key,type:"press"};return w({assertions:[],detail:`Pressed ${t.key}`,duration:performance.now()-o,nodeType:"press",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Press ${t.key}`})}})});import{z as qt}from"zod";var Si,Rn,vn=m(()=>{"use strict";v();Si=qt.object({height:qt.number().int().positive().describe("Viewport height in pixels"),width:qt.number().int().positive().describe("Viewport width in pixels")}),Rn=g({description:"Resize the browser viewport to the specified dimensions. Use this to test responsive layouts at different screen sizes (e.g. mobile: 375x812, tablet: 768x1024, desktop: 1440x900).",name:"resize_viewport",schema:Si,execute:async(e,t)=>{let o=performance.now();await e.page.setViewportSize({height:t.height,width:t.width});let r=`agent-step-${String(e.stepIndex)}`,n={height:t.height,id:r,type:"setViewport",width:t.width};return w({assertions:[],detail:`Resized viewport to ${String(t.width)}x${String(t.height)}`,duration:performance.now()-o,nodeType:"setViewport",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Resize viewport to ${String(t.width)}x${String(t.height)}`})}})});import{z as Pn}from"zod";var ki,xn,Tn=m(()=>{"use strict";v();ki=Pn.object({selector:Pn.string().describe("CSS selector for the element to right-click")}),xn=g({description:"Right-click an element to open the context menu",name:"right_click",schema:ki,execute:async(e,t)=>{let o=performance.now();await e.page.locator(t.selector).click({button:"right",timeout:5e3});let n={id:`agent-step-${String(e.stepIndex)}`,locator:{by:"css",value:t.selector},type:"rightClick"};return w({assertions:[],detail:`Right-clicked ${t.selector}`,duration:performance.now()-o,nodeType:"rightClick",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Right-click ${t.selector}`})}})});import{z as nt}from"zod";var Ri,Cn,In=m(()=>{"use strict";v();Ri=nt.object({selector:nt.string().optional().describe("CSS selector to scroll within (omit to scroll the page)"),x:nt.number().int().optional().describe("Horizontal scroll offset in pixels").default(0),y:nt.number().int().optional().describe("Vertical scroll offset in pixels").default(0)}),Cn=g({description:"Scroll the page or a specific element by pixel offset. Positive y scrolls down, negative scrolls up.",name:"scroll",schema:Ri,execute:async(e,t)=>{let o=performance.now();if(t.selector==null)await e.page.mouse.wheel(t.x,t.y);else{let a=await e.page.locator(t.selector).elementHandle();if(a==null)throw new Error("Scroll target element not found");await a.evaluate(`(el) => el.scrollBy(${String(t.x)}, ${String(t.y)})`)}let n={id:`agent-step-${String(e.stepIndex)}`,type:"scroll",x:t.x,y:t.y},s=t.selector??"page";return w({assertions:[],detail:`Scrolled ${s} by (${String(t.x)}, ${String(t.y)})`,duration:performance.now()-o,nodeType:"scroll",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Scroll ${s}`})}})});import{z as vi}from"zod";var Pi,An,Nn=m(()=>{"use strict";v();Pi=vi.object({}),An=g({description:"Take a screenshot of the current page",name:"screenshot",schema:Pi,execute:async(e,t)=>{let o=performance.now(),n={id:`agent-step-${String(e.stepIndex)}`,type:"screenshot"};return w({assertions:[],detail:"Screenshot captured",duration:performance.now()-o,nodeType:"screenshot",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:"Screenshot"})}})});import{z as jn}from"zod";function Ti(e){let t=e.url.length>0?` (${e.url})`:"";return`[${e.level.toUpperCase()}] ${e.text}${t}`}var xi,$n,En=m(()=>{"use strict";v();xi=jn.object({pattern:jn.string().describe("Regex pattern to search console log messages")}),$n=g({description:"Search console log messages for a regex pattern. Returns matching entries.",name:"search_console",schema:xi,execute:(e,t)=>{let o=new RegExp(t.pattern,"i"),r=e.monitor.consoleEntries.filter(s=>o.test(s.text));if(r.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:`No console messages matching: ${t.pattern}`};let n=r.map(s=>Ti(s)).join(`
31
- `);return{specNode:void 0,stepResult:void 0,toolOutput:`${String(r.length)} matching console messages:
32
- ${n}`}}})});import{z as On}from"zod";var Ci,Un,Fn=m(()=>{"use strict";v();Ci=On.object({pattern:On.string().describe("Regex pattern to search across network request URLs and response bodies")}),Un=g({description:"Search network requests and response bodies for a regex pattern. Useful for finding API calls, tokens, or specific data in responses.",name:"search_network",schema:Ci,execute:(e,t)=>{let o=new RegExp(t.pattern,"i"),r=e.monitor.networkEntries.filter(s=>o.test(s.url)||s.responseBody!=null&&o.test(s.responseBody));if(r.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:`No network entries matching: ${t.pattern}`};let n=r.map(s=>{let a=s.statusCode==null?"pending":String(s.statusCode),i=o.test(s.url)?" [URL match]":"",l=s.responseBody!=null&&o.test(s.responseBody)?" [body match]":"";return`${s.method} ${a} ${s.url}${i}${l}`}).join(`
33
- `);return{specNode:void 0,stepResult:void 0,toolOutput:`${String(r.length)} matching network entries:
34
- ${n}`}}})});import{z as Vn}from"zod";function ji({contextLines:e,lines:t,maxResults:o,pattern:r}){let n=new RegExp(r,"i"),s=[];return t.forEach((a,i)=>{if(s.length>=o||!n.test(a))return;let l=Math.max(0,i-e),c=Math.min(t.length-1,i+e),p=t.slice(l,c+1).map((f,h)=>{let y=l+h+1;return`${l+h===i?">":" "} ${String(y)}: ${f}`}).join(`
35
- `);s.push(p)}),s}var Ii,Ai,Ni,Dn,Wn=m(()=>{"use strict";v();Ii=20,Ai=2,Ni=Vn.object({pattern:Vn.string().describe("Regex pattern to search for in the page HTML")}),Dn=g({description:"Search the current page's full HTML/DOM for a regex pattern. Returns matching lines with context. Useful for finding elements, attributes, text content, or hidden data without reading the entire page.",name:"search_page",schema:Ni,execute:async(e,t)=>{let r=(await e.page.content()).split(`
36
- `),n=ji({contextLines:Ai,lines:r,maxResults:Ii,pattern:t.pattern});return n.length===0?{specNode:void 0,stepResult:void 0,toolOutput:`No matches found for pattern: ${t.pattern}`}:{specNode:void 0,stepResult:void 0,toolOutput:n.join(`
30
+ `)})})});import{z as or}from"zod";var Zi,An,Nn=y(()=>{"use strict";C();Zi=or.object({action:or.enum(["accept","dismiss"]).describe("Whether to accept or dismiss the dialog"),promptText:or.string().optional().describe("Text to enter for prompt dialogs")}),An=w({description:"Set up a handler for the next browser dialog (alert, confirm, prompt). Call this BEFORE the action that triggers the dialog.",name:"handle_dialog",schema:Zi,execute:(e,t)=>{let r=performance.now();e.page.once("dialog",async s=>{t.action==="accept"?await s.accept(t.promptText??void 0):await s.dismiss()});let o=`agent-step-${String(e.stepIndex)}`,n={action:t.action,id:o,type:"handleDialog"};return v({assertions:[],detail:`Dialog handler set: ${t.action}`,duration:performance.now()-r,nodeType:"handleDialog",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Handle dialog: ${t.action}`})}})});import{z as jn}from"zod";var Xi,$n,En=y(()=>{"use strict";C();Xi=jn.object({selector:jn.string().describe("CSS selector for the element to hover over")}),$n=w({description:"Hover over an element matching the CSS selector",name:"hover",schema:Xi,execute:async(e,t)=>{let r=performance.now();await e.page.locator(t.selector).hover({timeout:5e3});let n={id:`agent-step-${String(e.stepIndex)}`,locator:{by:"css",value:t.selector},type:"hover"};return v({assertions:[],detail:`Hovered over ${t.selector}`,duration:performance.now()-r,nodeType:"hover",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Hover ${t.selector}`})}})});import{z as nr}from"zod";var el,On,Un=y(()=>{"use strict";C();el=nr.object({permission:nr.string().describe("Permission name (e.g. geolocation, notifications, camera, clipboard-read)"),state:nr.enum(["granted","prompt"]).describe("Permission state to set")}),On=w({description:"Set a browser permission state (geolocation, notifications, camera, etc.)",name:"set_permission",schema:el,execute:async(e,t)=>{let r=performance.now(),o=e.page.context();t.state==="granted"?await o.grantPermissions([t.permission]):await o.clearPermissions();let s={id:`agent-step-${String(e.stepIndex)}`,permission:t.permission,state:t.state,type:"setPermission"};return v({assertions:[],detail:`Set ${t.permission} to ${t.state}`,duration:performance.now()-r,nodeType:"setPermission",page:e.page,runStartTime:e.runStartTime,specNode:s,status:"passed",stepIndex:e.stepIndex,title:`Set permission: ${t.permission} \u2192 ${t.state}`})}})});import{z as Fn}from"zod";var tl,Dn,Vn=y(()=>{"use strict";C();tl=Fn.object({url:Fn.string().describe("The URL to navigate to")}),Dn=w({description:"Navigate the browser to a URL",name:"navigate",schema:tl,execute:async(e,t)=>{let r=performance.now();await e.page.goto(t.url,{waitUntil:"domcontentloaded"});let n={id:`agent-step-${String(e.stepIndex)}`,type:"goto",url:{type:"static",value:t.url}};return v({assertions:[],detail:`Navigated to ${t.url}`,duration:performance.now()-r,nodeType:"goto",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Navigate to ${t.url}`})}})});import{z as _n}from"zod";var rl,Wn,Ln=y(()=>{"use strict";C();rl=_n.object({key:_n.string().describe("Key to press, e.g. 'Enter', 'Tab', 'Escape'")}),Wn=w({description:"Press a keyboard key",name:"press",schema:rl,execute:async(e,t)=>{let r=performance.now();await e.page.keyboard.press(t.key);let n={id:`agent-step-${String(e.stepIndex)}`,key:t.key,type:"press"};return v({assertions:[],detail:`Pressed ${t.key}`,duration:performance.now()-r,nodeType:"press",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Press ${t.key}`})}})});import{z as sr}from"zod";var ol,qn,Bn=y(()=>{"use strict";C();ol=sr.object({height:sr.number().int().positive().describe("Viewport height in pixels"),width:sr.number().int().positive().describe("Viewport width in pixels")}),qn=w({description:"Resize the browser viewport to the specified dimensions. Use this to test responsive layouts at different screen sizes (e.g. mobile: 375x812, tablet: 768x1024, desktop: 1440x900).",name:"resize_viewport",schema:ol,execute:async(e,t)=>{let r=performance.now();await e.page.setViewportSize({height:t.height,width:t.width});let o=`agent-step-${String(e.stepIndex)}`,n={height:t.height,id:o,type:"setViewport",width:t.width};return v({assertions:[],detail:`Resized viewport to ${String(t.width)}x${String(t.height)}`,duration:performance.now()-r,nodeType:"setViewport",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Resize viewport to ${String(t.width)}x${String(t.height)}`})}})});import{z as Mn}from"zod";var nl,zn,Gn=y(()=>{"use strict";C();nl=Mn.object({selector:Mn.string().describe("CSS selector for the element to right-click")}),zn=w({description:"Right-click an element to open the context menu",name:"right_click",schema:nl,execute:async(e,t)=>{let r=performance.now();await e.page.locator(t.selector).click({button:"right",timeout:5e3});let n={id:`agent-step-${String(e.stepIndex)}`,locator:{by:"css",value:t.selector},type:"rightClick"};return v({assertions:[],detail:`Right-clicked ${t.selector}`,duration:performance.now()-r,nodeType:"rightClick",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Right-click ${t.selector}`})}})});import{z as yt}from"zod";var sl,Hn,Jn=y(()=>{"use strict";C();sl=yt.object({selector:yt.string().optional().describe("CSS selector to scroll within (omit to scroll the page)"),x:yt.number().int().optional().describe("Horizontal scroll offset in pixels").default(0),y:yt.number().int().optional().describe("Vertical scroll offset in pixels").default(0)}),Hn=w({description:"Scroll the page or a specific element by pixel offset. Positive y scrolls down, negative scrolls up.",name:"scroll",schema:sl,execute:async(e,t)=>{let r=performance.now();if(t.selector==null)await e.page.mouse.wheel(t.x,t.y);else{let a=await e.page.locator(t.selector).elementHandle();if(a==null)throw new Error("Scroll target element not found");await a.evaluate(`(el) => el.scrollBy(${String(t.x)}, ${String(t.y)})`)}let n={id:`agent-step-${String(e.stepIndex)}`,type:"scroll",x:t.x,y:t.y},s=t.selector??"page";return v({assertions:[],detail:`Scrolled ${s} by (${String(t.x)}, ${String(t.y)})`,duration:performance.now()-r,nodeType:"scroll",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Scroll ${s}`})}})});import{z as al}from"zod";var il,Kn,Yn=y(()=>{"use strict";C();il=al.object({}),Kn=w({description:"Take a screenshot of the current page",name:"screenshot",schema:il,execute:async(e,t)=>{let r=performance.now(),n={id:`agent-step-${String(e.stepIndex)}`,type:"screenshot"};return v({assertions:[],detail:"Screenshot captured",duration:performance.now()-r,nodeType:"screenshot",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:"Screenshot"})}})});import{z as Qn}from"zod";function cl(e){let t=e.url.length>0?` (${e.url})`:"";return`[${e.level.toUpperCase()}] ${e.text}${t}`}var ll,Zn,Xn=y(()=>{"use strict";C();ll=Qn.object({pattern:Qn.string().describe("Regex pattern to search console log messages")}),Zn=w({description:"Search console log messages for a regex pattern. Returns matching entries.",name:"search_console",schema:ll,execute:(e,t)=>{let r=new RegExp(t.pattern,"i"),o=e.monitor.consoleEntries.filter(s=>r.test(s.text));if(o.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:`No console messages matching: ${t.pattern}`};let n=o.map(s=>cl(s)).join(`
31
+ `);return{specNode:void 0,stepResult:void 0,toolOutput:`${String(o.length)} matching console messages:
32
+ ${n}`}}})});import{z as es}from"zod";var dl,ts,rs=y(()=>{"use strict";C();dl=es.object({pattern:es.string().describe("Regex pattern to search across network request URLs and response bodies")}),ts=w({description:"Search network requests and response bodies for a regex pattern. Useful for finding API calls, tokens, or specific data in responses.",name:"search_network",schema:dl,execute:(e,t)=>{let r=new RegExp(t.pattern,"i"),o=e.monitor.networkEntries.filter(s=>r.test(s.url)||s.responseBody!=null&&r.test(s.responseBody));if(o.length===0)return{specNode:void 0,stepResult:void 0,toolOutput:`No network entries matching: ${t.pattern}`};let n=o.map(s=>{let a=s.statusCode==null?"pending":String(s.statusCode),i=r.test(s.url)?" [URL match]":"",l=s.responseBody!=null&&r.test(s.responseBody)?" [body match]":"";return`${s.method} ${a} ${s.url}${i}${l}`}).join(`
33
+ `);return{specNode:void 0,stepResult:void 0,toolOutput:`${String(o.length)} matching network entries:
34
+ ${n}`}}})});import{z as os}from"zod";function ml({contextLines:e,lines:t,maxResults:r,pattern:o}){let n=new RegExp(o,"i"),s=[];return t.forEach((a,i)=>{if(s.length>=r||!n.test(a))return;let l=Math.max(0,i-e),c=Math.min(t.length-1,i+e),p=t.slice(l,c+1).map((f,u)=>{let h=l+u+1;return`${l+u===i?">":" "} ${String(h)}: ${f}`}).join(`
35
+ `);s.push(p)}),s}var ul,pl,fl,ns,ss=y(()=>{"use strict";C();ul=20,pl=2,fl=os.object({pattern:os.string().describe("Regex pattern to search for in the page HTML")}),ns=w({description:"Search the current page's full HTML/DOM for a regex pattern. Returns matching lines with context. Useful for finding elements, attributes, text content, or hidden data without reading the entire page.",name:"search_page",schema:fl,execute:async(e,t)=>{let o=(await e.page.content()).split(`
36
+ `),n=ml({contextLines:pl,lines:o,maxResults:ul,pattern:t.pattern});return n.length===0?{specNode:void 0,stepResult:void 0,toolOutput:`No matches found for pattern: ${t.pattern}`}:{specNode:void 0,stepResult:void 0,toolOutput:n.join(`
37
37
  ---
38
- `)}}})});import{z as Bt}from"zod";var $i,Ln,_n=m(()=>{"use strict";v();$i=Bt.object({selector:Bt.string().describe("CSS selector for the select element"),value:Bt.string().describe("The option value to select")}),Ln=g({description:"Select an option from a dropdown/select element",name:"select",schema:$i,execute:async(e,t)=>{let o=performance.now();await e.page.locator(t.selector).selectOption(t.value,{timeout:5e3});let n={id:`agent-step-${String(e.stepIndex)}`,locator:{by:"css",value:t.selector},type:"select",value:{type:"static",value:t.value}};return w({assertions:[],detail:`Selected "${t.value}" in ${t.selector}`,duration:performance.now()-o,nodeType:"select",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Select ${t.value}`})}})});import{z as qn}from"zod";var Ei,Bn,Mn=m(()=>{"use strict";v();Ei=qn.object({selector:qn.string().describe("CSS selector for the checkbox to uncheck")}),Bn=g({description:"Uncheck a checkbox matching the CSS selector",name:"uncheck",schema:Ei,execute:async(e,t)=>{let o=performance.now();await e.page.locator(t.selector).uncheck({timeout:5e3});let n={id:`agent-step-${String(e.stepIndex)}`,locator:{by:"css",value:t.selector},type:"uncheck"};return w({assertions:[],detail:`Unchecked ${t.selector}`,duration:performance.now()-o,nodeType:"uncheck",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Uncheck ${t.selector}`})}})});import{z as Gn}from"zod";var Oi,zn,Hn=m(()=>{"use strict";v();Oi=Gn.object({ms:Gn.number().describe("Milliseconds to wait")}),zn=g({description:"Wait for a specified duration in milliseconds",name:"wait",schema:Oi,execute:async(e,t)=>{let o=performance.now();await e.page.waitForTimeout(t.ms);let r=`agent-step-${String(e.stepIndex)}`,n={duration:t.ms,id:r,type:"wait"};return w({assertions:[],detail:`Waited ${String(t.ms)}ms`,duration:performance.now()-o,nodeType:"wait",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Wait ${String(t.ms)}ms`})}})});import{z as Mt}from"zod";var Ui,Jn,Yn=m(()=>{"use strict";v();Ui=Mt.object({selector:Mt.string().describe("CSS selector for the element to wait for"),state:Mt.enum(["visible","hidden","attached","detached"]).default("visible").describe("The state to wait for (default: visible)")}),Jn=g({description:"Wait for an element matching the CSS selector to reach the specified state. More reliable than a blind wait \u2014 use this to wait for elements to appear, disappear, or attach/detach from the DOM.",name:"wait_for",schema:Ui,execute:async(e,t)=>{let o=performance.now();await e.page.locator(t.selector).waitFor({state:t.state,timeout:15e3});let n={id:`agent-step-${String(e.stepIndex)}`,locator:{by:"css",value:t.selector},state:t.state,type:"waitFor"};return w({assertions:[],detail:`Waited for ${t.selector} to be ${t.state}`,duration:performance.now()-o,nodeType:"waitFor",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Wait for ${t.selector} to be ${t.state}`})}})});function Ue(e){let t=[],o=[],r=[],n=new Map;function s(f){t.push({level:f.type(),text:f.text(),timestamp:Date.now(),url:f.location().url})}function a(f){let h=new st(f);n.set(f,h),o.push(h)}function i(f){let h=n.get(f.request());h!=null&&(n.delete(f.request()),h.applyResponse(f))}function l(f){r.push(`${f.message}
39
- ${f.stack??""}`)}function c(f){let h=f.failure(),y=new st(f);y.responseBody=`(request failed: ${h?.errorText??"unknown"})`,o.push(y)}e.on("console",s),e.on("request",a),e.on("response",i),e.on("pageerror",l),e.on("requestfailed",c);function p(){e.off("console",s),e.off("request",a),e.off("response",i),e.off("pageerror",l),e.off("requestfailed",c)}return{consoleEntries:t,detach:p,networkEntries:o,pageErrors:r}}var st,Gt=m(()=>{"use strict";st=class{method;requestHeaders;requestPostData;timestamp;url;responseBody=void 0;responseHeaders={};statusCode=void 0;constructor(t){this.method=t.method(),this.requestHeaders=t.headers(),this.requestPostData=t.postData()??void 0,this.timestamp=Date.now(),this.url=t.url()}applyResponse(t){this.statusCode=t.status(),this.responseHeaders=t.headers(),t.text().then(o=>{this.responseBody=o.length>1e5?`${o.slice(0,1e5)}... (truncated)`:o}).catch(()=>{this.responseBody="(unable to read body)"})}}});async function Qn({input:e,monitor:t,name:o,page:r,runStartTime:n,stepIndex:s}){let a=Fi.get(o);if(a==null)throw new Error(`Unknown agent tool: ${o}`);return a.execute({monitor:t,page:r,runStartTime:n,stepIndex:s},e)}var zt,Fi,Ht,Kn,Zn=m(()=>{"use strict";ir();dr();fr();gr();yr();br();Rr();xr();Ir();jr();Er();Fr();Wr();_r();Mr();Hr();Kr();Xr();tn();rn();ln();dn();fn();gn();wn();kn();vn();Tn();In();Nn();En();Fn();Wn();_n();Mn();Hn();Yn();Gt();zt=[yn,Nr,Lr,Sn,Pr,Bn,Ln,pn,zn,Jn,An,en,Dn,Cr,xn,Cn,cn,$r,mn,kr,hr,wr,ar,pr,cr,mr,Br,zr,Yr,on,Zr,an,$n,Un,Rn,Dr,Ur],Fi=new Map(zt.map(e=>[e.name,e])),Ht=zt.map(e=>e.anthropicTool),Kn=zt.map(e=>`- **${e.name}**: ${e.anthropicTool.description??""}`).join(`
40
- `)});import Vi from"pino";function E(e){return u.fatal(e),process.exit(1)}var u,D=m(()=>{"use strict";u=Vi({transport:{options:{ignore:"pid,hostname"},target:"pino-pretty"}})});import Di from"@anthropic-ai/sdk";async function Fe({baseUrl:e,executedPreconditions:t,extraVariables:o,onStep:r,page:n,runId:s,serverUrl:a,spec:i,systemPrompt:l,token:c,workflowContext:p}){let f=new Di({apiKey:"ripplo",baseURL:`${a}/api/proxy/anthropic`,defaultHeaders:{Authorization:`Bearer ${c}`,"x-run-id":s}}),h=performance.now(),y=Ue(n);await zi({baseUrl:e,page:n});let x=qi({extraVariables:o,spec:i}),R=Bi({baseUrl:e,executedPreconditions:t,spec:i,systemPrompt:l,variables:x,workflowContext:p}),$=Mi({baseUrl:e,spec:i,variables:x}),j=[{content:Gi({page:n,startUrl:$}),role:"user"}],ae=[],we=[],K={findings:"",stepIndex:0,verdict:void 0};K=await Li({client:f,messages:j,monitor:y,onStep:r,page:n,runStartTime:h,specNodes:we,state:K,steps:ae,system:R}),K.verdict==null&&(K=await _i({client:f,messages:j,monitor:y,onStep:r,page:n,runStartTime:h,specNodes:we,state:K,steps:ae,system:R}));let jt=Ji(we);return{findings:K.findings,generatedSpec:jt,monitor:y,steps:ae,verdict:K.verdict??"fail"}}function es({result:e,state:t}){return{findings:e.newFindings.length>0?e.newFindings:t.findings,stepIndex:e.nextStepIndex,verdict:e.verdict??t.verdict}}async function Li({client:e,messages:t,monitor:o,onStep:r,page:n,runStartTime:s,specNodes:a,state:i,steps:l,system:c}){let p=i;for(let f=0;f<Wi;f++){u.info("Agent iteration %d",f+1);let h=await e.messages.create({max_tokens:Xn,messages:t,model:"server-controlled",system:c,tools:Ht}),y=await ts({messages:t,monitor:o,onStep:r,page:n,response:h,runStartTime:s,specNodes:a,stepIndex:p.stepIndex,steps:l});if(p=es({result:y,state:p}),!y.continueLoop)break}return p}async function _i({client:e,messages:t,monitor:o,onStep:r,page:n,runStartTime:s,specNodes:a,state:i,steps:l,system:c}){u.warn("Agent exited without calling complete_test \u2014 forcing completion"),t.push({content:"You must call the complete_test tool now with your verdict and summary. Do not perform any more actions \u2014 just call complete_test.",role:"user"});let p=await e.messages.create({max_tokens:Xn,messages:t,model:"server-controlled",system:c,tool_choice:{name:"complete_test",type:"tool"},tools:Ht}),f=await ts({messages:t,monitor:o,onStep:r,page:n,response:p,runStartTime:s,specNodes:a,stepIndex:i.stepIndex,steps:l});return es({result:f,state:i})}function qi({extraVariables:e,spec:t}){return{...Ee({defs:t?.variables}),...e}}function Bi({baseUrl:e,executedPreconditions:t,spec:o,systemPrompt:r,variables:n,workflowContext:s}){let a=s==null?"":[`
38
+ `)}}})});import{z as ar}from"zod";var hl,as,is=y(()=>{"use strict";C();hl=ar.object({selector:ar.string().describe("CSS selector for the select element"),value:ar.string().describe("The option value to select")}),as=w({description:"Select an option from a dropdown/select element",name:"select",schema:hl,execute:async(e,t)=>{let r=performance.now();await e.page.locator(t.selector).selectOption(t.value,{timeout:5e3});let n={id:`agent-step-${String(e.stepIndex)}`,locator:{by:"css",value:t.selector},type:"select",value:{type:"static",value:t.value}};return v({assertions:[],detail:`Selected "${t.value}" in ${t.selector}`,duration:performance.now()-r,nodeType:"select",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Select ${t.value}`})}})});import{z as ls}from"zod";var gl,cs,ds=y(()=>{"use strict";C();gl=ls.object({selector:ls.string().describe("CSS selector for the checkbox to uncheck")}),cs=w({description:"Uncheck a checkbox matching the CSS selector",name:"uncheck",schema:gl,execute:async(e,t)=>{let r=performance.now();await e.page.locator(t.selector).uncheck({timeout:5e3});let n={id:`agent-step-${String(e.stepIndex)}`,locator:{by:"css",value:t.selector},type:"uncheck"};return v({assertions:[],detail:`Unchecked ${t.selector}`,duration:performance.now()-r,nodeType:"uncheck",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Uncheck ${t.selector}`})}})});import{z as us}from"zod";var yl,ps,fs=y(()=>{"use strict";C();yl=us.object({ms:us.number().describe("Milliseconds to wait")}),ps=w({description:"Wait for a specified duration in milliseconds",name:"wait",schema:yl,execute:async(e,t)=>{let r=performance.now();await e.page.waitForTimeout(t.ms);let o=`agent-step-${String(e.stepIndex)}`,n={duration:t.ms,id:o,type:"wait"};return v({assertions:[],detail:`Waited ${String(t.ms)}ms`,duration:performance.now()-r,nodeType:"wait",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Wait ${String(t.ms)}ms`})}})});import{z as ir}from"zod";var wl,ms,hs=y(()=>{"use strict";C();wl=ir.object({selector:ir.string().describe("CSS selector for the element to wait for"),state:ir.enum(["visible","hidden","attached","detached"]).default("visible").describe("The state to wait for (default: visible)")}),ms=w({description:"Wait for an element matching the CSS selector to reach the specified state. More reliable than a blind wait \u2014 use this to wait for elements to appear, disappear, or attach/detach from the DOM.",name:"wait_for",schema:wl,execute:async(e,t)=>{let r=performance.now();await e.page.locator(t.selector).waitFor({state:t.state,timeout:15e3});let n={id:`agent-step-${String(e.stepIndex)}`,locator:{by:"css",value:t.selector},state:t.state,type:"waitFor"};return v({assertions:[],detail:`Waited for ${t.selector} to be ${t.state}`,duration:performance.now()-r,nodeType:"waitFor",page:e.page,runStartTime:e.runStartTime,specNode:n,status:"passed",stepIndex:e.stepIndex,title:`Wait for ${t.selector} to be ${t.state}`})}})});function Me(e){let t=[],r=[],o=[],n=new Map;function s(f){t.push({level:f.type(),text:f.text(),timestamp:Date.now(),url:f.location().url})}function a(f){let u=new wt(f);n.set(f,u),r.push(u)}function i(f){let u=n.get(f.request());u!=null&&(n.delete(f.request()),u.applyResponse(f))}function l(f){o.push(`${f.message}
39
+ ${f.stack??""}`)}function c(f){let u=f.failure(),h=new wt(f);h.responseBody=`(request failed: ${u?.errorText??"unknown"})`,r.push(h)}e.on("console",s),e.on("request",a),e.on("response",i),e.on("pageerror",l),e.on("requestfailed",c);function p(){e.off("console",s),e.off("request",a),e.off("response",i),e.off("pageerror",l),e.off("requestfailed",c)}return{consoleEntries:t,detach:p,networkEntries:r,pageErrors:o}}var wt,lr=y(()=>{"use strict";wt=class{method;requestHeaders;requestPostData;timestamp;url;responseBody=void 0;responseHeaders={};statusCode=void 0;constructor(t){this.method=t.method(),this.requestHeaders=t.headers(),this.requestPostData=t.postData()??void 0,this.timestamp=Date.now(),this.url=t.url()}applyResponse(t){this.statusCode=t.status(),this.responseHeaders=t.headers(),t.text().then(r=>{this.responseBody=r.length>1e5?`${r.slice(0,1e5)}... (truncated)`:r}).catch(()=>{this.responseBody="(unable to read body)"})}}});async function ys({input:e,monitor:t,name:r,page:o,runStartTime:n,stepIndex:s}){let a=bl.get(r);if(a==null)throw new Error(`Unknown agent tool: ${r}`);return a.execute({monitor:t,page:o,runStartTime:n,stepIndex:s},e)}var cr,bl,dr,gs,ws=y(()=>{"use strict";To();No();Eo();Uo();Do();_o();qo();zo();Jo();Qo();Xo();rn();sn();ln();un();mn();yn();Sn();vn();Pn();In();Nn();En();Un();Vn();Ln();Bn();Gn();Jn();Yn();Xn();rs();ss();is();ds();fs();hs();lr();cr=[Dn,Yo,an,Wn,Mo,cs,as,$n,ps,ms,Kn,kn,ns,Ho,zn,Hn,An,Zo,On,Lo,Fo,Vo,Co,$o,Ao,Oo,dn,fn,gn,Rn,bn,Tn,Zn,ts,qn,nn,tn],bl=new Map(cr.map(e=>[e.name,e])),dr=cr.map(e=>e.anthropicTool),gs=cr.map(e=>`- **${e.name}**: ${e.anthropicTool.description??""}`).join(`
40
+ `)});import Sl from"pino";function W(e){return m.fatal(e),process.exit(1)}var m,H=y(()=>{"use strict";m=Sl({transport:{options:{ignore:"pid,hostname"},target:"pino-pretty"}})});import kl from"@anthropic-ai/sdk";async function ze({baseUrl:e,executedPreconditions:t,extraVariables:r,onStep:o,page:n,runId:s,serverUrl:a,spec:i,systemPrompt:l,token:c,workflowContext:p}){let f=new kl({apiKey:"ripplo",baseURL:`${a}/api/proxy/anthropic`,defaultHeaders:{Authorization:`Bearer ${c}`,"x-run-id":s}}),u=performance.now(),h=Me(n);await Al({baseUrl:e,page:n});let g=xl({extraVariables:r,spec:i}),b=Cl({baseUrl:e,executedPreconditions:t,spec:i,systemPrompt:l,variables:g,workflowContext:p}),P=Tl({baseUrl:e,spec:i,variables:g}),S=[{content:Il({page:n,startUrl:P}),role:"user"}],N=[],j=[],I={findings:"",stepIndex:0,verdict:void 0};I=await Rl({client:f,messages:S,monitor:h,onStep:o,page:n,runStartTime:u,specNodes:j,state:I,steps:N,system:b}),I.verdict==null&&(I=await Pl({client:f,messages:S,monitor:h,onStep:o,page:n,runStartTime:u,specNodes:j,state:I,steps:N,system:b}));let G=jl(j);return{findings:I.findings,generatedSpec:G,monitor:h,steps:N,verdict:I.verdict??"fail"}}function Ss({result:e,state:t}){return{findings:e.newFindings.length>0?e.newFindings:t.findings,stepIndex:e.nextStepIndex,verdict:e.verdict??t.verdict}}async function Rl({client:e,messages:t,monitor:r,onStep:o,page:n,runStartTime:s,specNodes:a,state:i,steps:l,system:c}){let p=i;for(let f=0;f<vl;f++){m.info("Agent iteration %d",f+1);let u=await e.messages.create({max_tokens:bs,messages:t,model:"server-controlled",system:c,tools:dr}),h=await ks({messages:t,monitor:r,onStep:o,page:n,response:u,runStartTime:s,specNodes:a,stepIndex:p.stepIndex,steps:l});if(p=Ss({result:h,state:p}),!h.continueLoop)break}return p}async function Pl({client:e,messages:t,monitor:r,onStep:o,page:n,runStartTime:s,specNodes:a,state:i,steps:l,system:c}){m.warn("Agent exited without calling complete_test \u2014 forcing completion"),t.push({content:"You must call the complete_test tool now with your verdict and summary. Do not perform any more actions \u2014 just call complete_test.",role:"user"});let p=await e.messages.create({max_tokens:bs,messages:t,model:"server-controlled",system:c,tool_choice:{name:"complete_test",type:"tool"},tools:dr}),f=await ks({messages:t,monitor:r,onStep:o,page:n,response:p,runStartTime:s,specNodes:a,stepIndex:i.stepIndex,steps:l});return Ss({result:f,state:i})}function xl({extraVariables:e,spec:t}){return{...qe({defs:t?.variables}),...e}}function Cl({baseUrl:e,executedPreconditions:t,spec:r,systemPrompt:o,variables:n,workflowContext:s}){let a=s==null?"":[`
41
41
 
42
42
  ## Workflow Under Test`,`**Name:** ${s.name}`,`**Description:** ${s.description}`,`**Expected Outcome:** ${s.expectedOutcome}`,`
43
43
  Focus your testing ONLY on this specific workflow. Do not test unrelated parts of the application.`].join(`
44
- `),i=o==null?"":`
44
+ `),i=r==null?"":`
45
45
 
46
46
  Reference workflow spec (the steps a user would follow):
47
47
  \`\`\`json
48
- ${JSON.stringify(o,null,2)}
49
- \`\`\``,l=t.map(y=>`- ${y}`).join(`
48
+ ${JSON.stringify(r,null,2)}
49
+ \`\`\``,l=t.map(h=>`- ${h}`).join(`
50
50
  `),c=t.length===0?"":`
51
51
 
52
52
  ## Setup Already Completed
53
53
  The following setup steps have already been run before your session started:
54
54
  ${l}
55
55
 
56
- Do not repeat any of these steps.`,p=Object.entries(n),f=p.map(([y,x])=>`- **${y}:** ${String(x)}`).join(`
57
- `),h=p.length===0?"":`
56
+ Do not repeat any of these steps.`,p=Object.entries(n),f=p.map(([h,g])=>`- **${h}:** ${String(g)}`).join(`
57
+ `),u=p.length===0?"":`
58
58
 
59
59
  ## Resolved Variables
60
60
  ${f}`;return[`You are testing the application at: ${e}`,"Use the provided tools to navigate, interact with, and assert things about the page.","Use get_page_content to inspect the page when you need to understand what's on screen.","Follow the workflow steps to complete the task.",`
61
- ## Available Tools`,Kn,a,c,i,h,`
62
- ## Agent Profile (HIGHEST PRIORITY \u2014 these instructions override any defaults above)`,r].join(`
63
- `)}function Mi({baseUrl:e,spec:t,variables:o}){if(t==null)return e;let r=t.nodes[t.entryNode];if(r==null||r.type!=="goto"||r.url.type!=="static")return e;let s=r.url.value.replaceAll(/\{\{(\w+)\}\}/g,(a,i)=>{let l=o[i];return l==null?`{{${i}}}`:String(l)});return s.startsWith("http")?s:`${e}${s.startsWith("/")?"":"/"}${s}`}function Gi({page:e,startUrl:t}){let o=e.url();return o!=="about:blank"&&o.length>0?`You are already on the page at ${o}. Begin testing from this page \u2014 do not navigate away unless the workflow requires it.`:`Navigate to ${t} and begin testing.`}async function zi({baseUrl:e,page:t}){let o=new URL(e).origin;await t.route("**/*",r=>{let n=r.request();return n.isNavigationRequest()&&new URL(n.url()).origin!==o?(u.warn("Blocked navigation to off-origin URL: %s",n.url()),r.abort("blockedbyclient")):r.continue()})}async function ts({messages:e,monitor:t,onStep:o,page:r,response:n,runStartTime:s,specNodes:a,stepIndex:i,steps:l}){let c=n.content.filter($=>$.type==="text").map($=>$.text),p=n.content.filter($=>$.type==="tool_use");if(p.length===0)return{continueLoop:!1,newFindings:c.join(`
64
- `),nextStepIndex:i,verdict:void 0};let f=[],h=i,y,x;for(let $ of p){let S=await Hi({block:$,monitor:t,onStep:o,page:r,runStartTime:s,specNodes:a,stepIndex:h,steps:l});f.push(S.toolResult),h=S.nextStepIndex,S.verdict!=null&&(y=S.verdict,x=S.summary)}e.push({content:n.content,role:"assistant"},{content:f,role:"user"});let R=x??c.join(`
65
- `);return{continueLoop:y==null&&n.stop_reason==="tool_use",newFindings:R,nextStepIndex:h,verdict:y}}async function Hi({block:e,monitor:t,onStep:o,page:r,runStartTime:n,specNodes:s,stepIndex:a,steps:i}){try{let l=await Qn({input:e.input,monitor:t,name:e.name,page:r,runStartTime:n,stepIndex:a}),c={content:l.toolOutput,tool_use_id:e.id,type:"tool_result"};return l.kind==="verdict"?(u.info(" [%d] %s \u2014 verdict: %s",a,e.name,l.verdict),{nextStepIndex:a,summary:l.summary,toolResult:c,verdict:l.verdict}):(l.specNode!=null&&s.push(l.specNode),l.stepResult!=null?(i.push(l.stepResult),o?.(l.stepResult),u.info(" [%d] %s \u2014 %s",a,e.name,l.stepResult.status),{nextStepIndex:a+1,summary:void 0,toolResult:c,verdict:void 0}):(u.info(" [%d] %s \u2014 info",a,e.name),{nextStepIndex:a,summary:void 0,toolResult:c,verdict:void 0}))}catch(l){let c=l instanceof Error?l.message:"Unknown error";u.error(" [%d] %s \u2014 error: %s",a,e.name,c);let p=await le({page:r,runStartTime:n,targets:[]}),f={annotations:p.annotations,assertions:[],detail:`Error: ${c}`,duration:0,nodeId:`agent-step-${String(a)}`,nodeType:"click",screenshotBase64:p.screenshotBase64,snapshotTimestamp:p.snapshotTimestamp,status:"failed",stepIndex:a,title:`${e.name} (error)`,url:p.url,viewportHeight:p.viewportHeight,viewportWidth:p.viewportWidth};return i.push(f),o?.(f),{nextStepIndex:a+1,summary:void 0,toolResult:{content:`Error: ${c}`,is_error:!0,tool_use_id:e.id,type:"tool_result"},verdict:void 0}}}function Ji(e){if(e.length===0)return{entryNode:"",nodes:{},version:2};let t={};e.forEach((r,n)=>{let s=e[n+1],a=s==null?r:{...r,next:s.id};t[r.id]=a});let o=e[0];if(o==null)throw new Error("Expected at least one spec node after length check");return{entryNode:o.id,nodes:t,version:2}}var Wi,Xn,Jt=m(()=>{"use strict";Zn();D();Oe();Q();Wi=50,Xn=16384});function Ve({description:e,output:t,successCriteria:o}){let r=[`## Agent Identity
66
- ${e}`];t!=null&&t.length>0&&r.push(`## Output
67
- ${t}`),o!=null&&o.length>0&&r.push(`## Success Criteria
68
- ${o}`);let n=["## Completing Your Evaluation",'When you finish your evaluation, you MUST call the `complete_test` tool with your verdict ("pass" or "fail") and a `summary` string.',Yi({hasSuccessCriteria:o!=null&&o.length>0}),Ki({hasOutput:t!=null&&t.length>0})];return r.push(n.join(`
69
- `)),r.join(`
61
+ ## Available Tools`,gs,a,c,i,u,`
62
+ ## Agent Profile (HIGHEST PRIORITY \u2014 these instructions override any defaults above)`,o].join(`
63
+ `)}function Tl({baseUrl:e,spec:t,variables:r}){if(t==null)return e;let o=t.nodes[t.entryNode];if(o==null||o.type!=="goto"||o.url.type!=="static")return e;let s=o.url.value.replaceAll(/\{\{(\w+)\}\}/g,(a,i)=>{let l=r[i];return l==null?`{{${i}}}`:String(l)});return s.startsWith("http")?s:`${e}${s.startsWith("/")?"":"/"}${s}`}function Il({page:e,startUrl:t}){let r=e.url();return r!=="about:blank"&&r.length>0?`You are already on the page at ${r}. Begin testing from this page \u2014 do not navigate away unless the workflow requires it.`:`Navigate to ${t} and begin testing.`}async function Al({baseUrl:e,page:t}){let r=new URL(e).origin;await t.route("**/*",o=>{let n=o.request();return n.isNavigationRequest()&&new URL(n.url()).origin!==r?(m.warn("Blocked navigation to off-origin URL: %s",n.url()),o.abort("blockedbyclient")):o.continue()})}async function ks({messages:e,monitor:t,onStep:r,page:o,response:n,runStartTime:s,specNodes:a,stepIndex:i,steps:l}){let c=n.content.filter(P=>P.type==="text").map(P=>P.text),p=n.content.filter(P=>P.type==="tool_use");if(p.length===0)return{continueLoop:!1,newFindings:c.join(`
64
+ `),nextStepIndex:i,verdict:void 0};let f=[],u=i,h,g;for(let P of p){let k=await Nl({block:P,monitor:t,onStep:r,page:o,runStartTime:s,specNodes:a,stepIndex:u,steps:l});f.push(k.toolResult),u=k.nextStepIndex,k.verdict!=null&&(h=k.verdict,g=k.summary)}e.push({content:n.content,role:"assistant"},{content:f,role:"user"});let b=g??c.join(`
65
+ `);return{continueLoop:h==null&&n.stop_reason==="tool_use",newFindings:b,nextStepIndex:u,verdict:h}}async function Nl({block:e,monitor:t,onStep:r,page:o,runStartTime:n,specNodes:s,stepIndex:a,steps:i}){try{let l=await ys({input:e.input,monitor:t,name:e.name,page:o,runStartTime:n,stepIndex:a}),c={content:l.toolOutput,tool_use_id:e.id,type:"tool_result"};return l.kind==="verdict"?(m.info(" [%d] %s \u2014 verdict: %s",a,e.name,l.verdict),{nextStepIndex:a,summary:l.summary,toolResult:c,verdict:l.verdict}):(l.specNode!=null&&s.push(l.specNode),l.stepResult!=null?(i.push(l.stepResult),r?.(l.stepResult),m.info(" [%d] %s \u2014 %s",a,e.name,l.stepResult.status),{nextStepIndex:a+1,summary:void 0,toolResult:c,verdict:void 0}):(m.info(" [%d] %s \u2014 info",a,e.name),{nextStepIndex:a,summary:void 0,toolResult:c,verdict:void 0}))}catch(l){let c=l instanceof Error?l.message:"Unknown error";m.error(" [%d] %s \u2014 error: %s",a,e.name,c);let p=await he({page:o,runStartTime:n,targets:[]}),f={annotations:p.annotations,assertions:[],detail:`Error: ${c}`,duration:0,nodeId:`agent-step-${String(a)}`,nodeType:"click",screenshotBase64:p.screenshotBase64,snapshotTimestamp:p.snapshotTimestamp,status:"failed",stepIndex:a,title:`${e.name} (error)`,url:p.url,viewportHeight:p.viewportHeight,viewportWidth:p.viewportWidth};return i.push(f),r?.(f),{nextStepIndex:a+1,summary:void 0,toolResult:{content:`Error: ${c}`,is_error:!0,tool_use_id:e.id,type:"tool_result"},verdict:void 0}}}function jl(e){if(e.length===0)return{entryNode:"",nodes:{},version:2};let t={};e.forEach((o,n)=>{let s=e[n+1],a=s==null?o:{...o,next:s.id};t[o.id]=a});let r=e[0];if(r==null)throw new Error("Expected at least one spec node after length check");return{entryNode:r.id,nodes:t,version:2}}var vl,bs,ur=y(()=>{"use strict";ws();H();Be();se();vl=50,bs=16384});function Ge({description:e,output:t,successCriteria:r}){let o=[`## Agent Identity
66
+ ${e}`];t!=null&&t.length>0&&o.push(`## Output
67
+ ${t}`),r!=null&&r.length>0&&o.push(`## Success Criteria
68
+ ${r}`);let n=["## Completing Your Evaluation",'When you finish your evaluation, you MUST call the `complete_test` tool with your verdict ("pass" or "fail") and a `summary` string.',$l({hasSuccessCriteria:r!=null&&r.length>0}),El({hasOutput:t!=null&&t.length>0})];return o.push(n.join(`
69
+ `)),o.join(`
70
70
 
71
- `)}function Yi({hasSuccessCriteria:e}){return e?"Base your verdict strictly on the Success Criteria defined above. A test passes ONLY if all success criteria are met, and fails if any criterion is not met. Individual step failures during exploration do not necessarily mean the test failed, but the success criteria are the ultimate authority for your verdict.":"Base your verdict on whether the workflow worked correctly. Individual step failures during exploration do not necessarily mean the test failed."}function Ki({hasOutput:e}){return e?'The `summary` parameter is the ONLY output the user will see. You MUST use the `summary` field for EXACTLY the output described in the "Output" section above \u2014 nothing else. Do not describe what you did, do not list steps, do not add a test summary. The `summary` must contain ONLY what the Output section asks for, word for word if it specifies exact text.':"Include a brief summary of what you found in the `summary` parameter."}var Yt=m(()=>{"use strict"});import{execFileSync as Qi}from"child_process";import{createRequire as Zi}from"module";import os from"fs";import rs from"path";import{chromium as Kt}from"playwright";async function re({headed:e}){u.info("Browser executable: %s",Kt.executablePath());try{return await Kt.launch({headless:!e})}catch(t){throw Xi(t)?new Error(`Playwright browsers are not installed. Run:
71
+ `)}function $l({hasSuccessCriteria:e}){return e?"Base your verdict strictly on the Success Criteria defined above. A test passes ONLY if all success criteria are met, and fails if any criterion is not met. Individual step failures during exploration do not necessarily mean the test failed, but the success criteria are the ultimate authority for your verdict.":"Base your verdict on whether the workflow worked correctly. Individual step failures during exploration do not necessarily mean the test failed."}function El({hasOutput:e}){return e?'The `summary` parameter is the ONLY output the user will see. You MUST use the `summary` field for EXACTLY the output described in the "Output" section above \u2014 nothing else. Do not describe what you did, do not list steps, do not add a test summary. The `summary` must contain ONLY what the Output section asks for, word for word if it specifies exact text.':"Include a brief summary of what you found in the `summary` parameter."}var pr=y(()=>{"use strict"});import{execFileSync as Ol}from"child_process";import{createRequire as Ul}from"module";import vs from"fs";import Rs from"path";import{chromium as fr}from"playwright";async function ue({headed:e}){m.info("Browser executable: %s",fr.executablePath());try{return await fr.launch({headless:!e})}catch(t){throw Fl(t)?new Error(`Playwright browsers are not installed. Run:
72
72
 
73
73
  npx playwright install chromium
74
- `):t}}function Qt(){let e=Kt.executablePath();if(os.existsSync(e))return;u.info("Chromium not found. Installing via Playwright...");let t=Zi(import.meta.url),o=rs.dirname(t.resolve("playwright/package.json")),r=rs.join(o,"cli.js");if(Qi(process.execPath,[r,"install","chromium"],{stdio:"inherit"}),!os.existsSync(e))throw new Error(`Playwright browser installation failed. Try running manually:
74
+ `):t}}function mr(){let e=fr.executablePath();if(vs.existsSync(e))return;m.info("Chromium not found. Installing via Playwright...");let t=Ul(import.meta.url),r=Rs.dirname(t.resolve("playwright/package.json")),o=Rs.join(r,"cli.js");if(Ol(process.execPath,[o,"install","chromium"],{stdio:"inherit"}),!vs.existsSync(e))throw new Error(`Playwright browser installation failed. Try running manually:
75
75
 
76
76
  npx playwright install chromium
77
- `);u.info("\u2713 Chromium installed")}function Xi(e){return e instanceof Error?e.message.includes("Executable doesn't exist"):!1}var at=m(()=>{"use strict";D()});import{mkdir as Zt,writeFile as H}from"fs/promises";import W from"path";async function it({context:e,page:t,runId:o,stepIndex:r,stepResult:n}){try{let s=W.join(process.cwd(),".ripplo","debug",o,"steps",String(r));await Zt(s,{recursive:!0});let a={annotations:n.annotations,assertions:n.assertions,detail:n.detail,duration:n.duration,nodeId:n.nodeId,nodeType:n.nodeType,snapshotTimestamp:n.snapshotTimestamp,status:n.status,stepIndex:n.stepIndex,title:n.title,url:n.url,viewportHeight:n.viewportHeight,viewportWidth:n.viewportWidth};await Promise.all([H(W.join(s,"info.json"),JSON.stringify(a,null,2)),H(W.join(s,"screenshot.png"),Buffer.from(n.screenshotBase64,"base64")),el({context:e,page:t,stepDir:s})])}catch(s){let a=s instanceof Error?s.message:String(s);u.warn("Failed to write step debug data for step %d: %s",r,a)}}async function el({context:e,page:t,stepDir:o}){let[r,n,s]=await Promise.all([t.content().catch(()=>"(unable to capture DOM)"),tl(t),ol({context:e,page:t})]);await Promise.all([H(W.join(o,"dom.html"),r),H(W.join(o,"accessibility-tree.txt"),n),H(W.join(o,"storage.json"),JSON.stringify(s,null,2))])}async function tl(e){try{return await e.locator(":root").ariaSnapshot()}catch{return"(unable to capture accessibility tree)"}}async function ol({context:e,page:t}){let[o,r]=await Promise.all([t.evaluate(()=>({localStorage:Object.fromEntries(Array.from({length:localStorage.length},(n,s)=>{let a=localStorage.key(s);return a==null?void 0:[a,localStorage.getItem(a)??""]}).filter(n=>n!=null)),sessionStorage:Object.fromEntries(Array.from({length:sessionStorage.length},(n,s)=>{let a=sessionStorage.key(s);return a==null?void 0:[a,sessionStorage.getItem(a)??""]}).filter(n=>n!=null))})).catch(()=>({localStorage:{},sessionStorage:{}})),e.cookies().catch(()=>[])]);return{cookies:r,localStorage:o.localStorage,sessionStorage:o.sessionStorage}}async function lt({monitor:e,runId:t,steps:o,summary:r}){try{let n=W.join(process.cwd(),".ripplo","debug",t);await Zt(n,{recursive:!0}),await Promise.all([H(W.join(n,"summary.txt"),rl({steps:o,summary:r})),H(W.join(n,"console.log"),nl(e.consoleEntries)),H(W.join(n,"network.jsonl"),sl(e.networkEntries)),H(W.join(n,"page-errors.log"),e.pageErrors.join(`
77
+ `);m.info("\u2713 Chromium installed")}function Fl(e){return e instanceof Error?e.message.includes("Executable doesn't exist"):!1}var bt=y(()=>{"use strict";H()});import{mkdir as hr,writeFile as re}from"fs/promises";import J from"path";async function St({context:e,page:t,runId:r,stepIndex:o,stepResult:n}){try{let s=J.join(process.cwd(),".ripplo","debug",r,"steps",String(o));await hr(s,{recursive:!0});let a={annotations:n.annotations,assertions:n.assertions,detail:n.detail,duration:n.duration,nodeId:n.nodeId,nodeType:n.nodeType,snapshotTimestamp:n.snapshotTimestamp,status:n.status,stepIndex:n.stepIndex,title:n.title,url:n.url,viewportHeight:n.viewportHeight,viewportWidth:n.viewportWidth};await Promise.all([re(J.join(s,"info.json"),JSON.stringify(a,null,2)),re(J.join(s,"screenshot.png"),Buffer.from(n.screenshotBase64,"base64")),Dl({context:e,page:t,stepDir:s})])}catch(s){let a=s instanceof Error?s.message:String(s);m.warn("Failed to write step debug data for step %d: %s",o,a)}}async function Dl({context:e,page:t,stepDir:r}){let[o,n,s]=await Promise.all([t.content().catch(()=>"(unable to capture DOM)"),Vl(t),_l({context:e,page:t})]);await Promise.all([re(J.join(r,"dom.html"),o),re(J.join(r,"accessibility-tree.txt"),n),re(J.join(r,"storage.json"),JSON.stringify(s,null,2))])}async function Vl(e){try{return await e.locator(":root").ariaSnapshot()}catch{return"(unable to capture accessibility tree)"}}async function _l({context:e,page:t}){let[r,o]=await Promise.all([t.evaluate(()=>({localStorage:Object.fromEntries(Array.from({length:localStorage.length},(n,s)=>{let a=localStorage.key(s);return a==null?void 0:[a,localStorage.getItem(a)??""]}).filter(n=>n!=null)),sessionStorage:Object.fromEntries(Array.from({length:sessionStorage.length},(n,s)=>{let a=sessionStorage.key(s);return a==null?void 0:[a,sessionStorage.getItem(a)??""]}).filter(n=>n!=null))})).catch(()=>({localStorage:{},sessionStorage:{}})),e.cookies().catch(()=>[])]);return{cookies:o,localStorage:r.localStorage,sessionStorage:r.sessionStorage}}async function kt({monitor:e,runId:t,steps:r,summary:o}){try{let n=J.join(process.cwd(),".ripplo","debug",t);await hr(n,{recursive:!0}),await Promise.all([re(J.join(n,"summary.txt"),Wl({steps:r,summary:o})),re(J.join(n,"console.log"),Ll(e.consoleEntries)),re(J.join(n,"network.jsonl"),ql(e.networkEntries)),re(J.join(n,"page-errors.log"),e.pageErrors.join(`
78
78
  ---
79
- `))]),u.info("Debug artifacts written to .ripplo/debug/%s/",t)}catch(n){let s=n instanceof Error?n.message:String(n);u.warn("Failed to write run debug summary: %s",s)}}function rl({steps:e,summary:t}){return[`Run ID: ${t.runId}`,`Workflow: ${t.workflowName}`,`Status: ${t.status}`,`Duration: ${String(t.duration)}ms`,`Passed: ${String(t.passCount)}`,`Failed: ${String(t.failCount)}`,"","Steps:",...e.map(r=>` [${String(r.stepIndex)}] ${r.status==="passed"?"\u2713":"\u2717"} ${r.title} (${String(r.duration)}ms) \u2014 ${r.detail??"ok"}`)].join(`
80
- `)}function nl(e){return e.map(t=>`[${new Date(t.timestamp).toISOString()}] [${t.level.toUpperCase()}] (${t.url}) ${t.text}`).join(`
81
- `)}function sl(e){return e.map(t=>JSON.stringify(t)).join(`
82
- `)}async function ns({error:e,runId:t,stack:o,workflowName:r}){try{let n=W.join(process.cwd(),".ripplo","debug",t);await Zt(n,{recursive:!0});let s=o==null?e:`${e}
79
+ `))]),m.info("Debug artifacts written to .ripplo/debug/%s/",t)}catch(n){let s=n instanceof Error?n.message:String(n);m.warn("Failed to write run debug summary: %s",s)}}function Wl({steps:e,summary:t}){return[`Run ID: ${t.runId}`,`Workflow: ${t.workflowName}`,`Status: ${t.status}`,`Duration: ${String(t.duration)}ms`,`Passed: ${String(t.passCount)}`,`Failed: ${String(t.failCount)}`,"","Steps:",...e.map(o=>` [${String(o.stepIndex)}] ${o.status==="passed"?"\u2713":"\u2717"} ${o.title} (${String(o.duration)}ms) \u2014 ${o.detail??"ok"}`)].join(`
80
+ `)}function Ll(e){return e.map(t=>`[${new Date(t.timestamp).toISOString()}] [${t.level.toUpperCase()}] (${t.url}) ${t.text}`).join(`
81
+ `)}function ql(e){return e.map(t=>JSON.stringify(t)).join(`
82
+ `)}async function Ps({error:e,runId:t,stack:r,workflowName:o}){try{let n=J.join(process.cwd(),".ripplo","debug",t);await hr(n,{recursive:!0});let s=r==null?e:`${e}
83
83
 
84
- ${o}`,a=[`Run ID: ${t}`,`Workflow: ${r}`,"Status: failed","",`Error: ${e}`,"",o==null?"":`Stack trace:
85
- ${o}`].join(`
86
- `);await Promise.all([H(W.join(n,"error.txt"),s),H(W.join(n,"summary.txt"),a)]),u.info("Debug error artifacts written to .ripplo/debug/%s/",t)}catch(n){let s=n instanceof Error?n.message:String(n);u.warn("Failed to write error debug artifacts: %s",s)}}var ct=m(()=>{"use strict";D()});async function Xt({baseUrl:e,cookies:t,executedPreconditions:o,extraVariables:r,headed:n,navigateTo:s,runId:a,serverUrl:i,spec:l,streaming:c,systemPrompt:p,token:f,workflowContext:h}){let y=await re({headed:n}),x=await y.newContext({baseURL:e});t.length>0&&(await x.addCookies([...t]),u.info("Injected %d cookies from preconditions",t.length));let R=await x.newPage();s!=null&&(u.info("Navigating to precondition start page: %s",s),await R.goto(s,{waitUntil:"domcontentloaded"}));try{let S=function(te){c.enqueueStep(te),it({context:x,page:R,runId:a,stepIndex:te.stepIndex,stepResult:te})};var $=S;let j=await Fe({baseUrl:e,executedPreconditions:o,extraVariables:r,onStep:S,page:R,runId:a,serverUrl:i,spec:l,systemPrompt:p,token:f,workflowContext:h}),ae=j.verdict==="pass"?"passed":"failed";await c.complete({statusOverride:ae,steps:j.steps,summary:j.findings});let we=j.steps.filter(te=>te.status==="passed").length,K=j.steps.filter(te=>te.status==="failed").length,jt={duration:j.steps.reduce((te,va)=>te+va.duration,0),failCount:K,passCount:we,runId:a,status:ae,workflowName:h.name};await lt({monitor:j.monitor,runId:a,steps:j.steps,summary:jt}),u.info("Agent test complete: %d passed, %d failed",we,K),u.info(`
84
+ ${r}`,a=[`Run ID: ${t}`,`Workflow: ${o}`,"Status: failed","",`Error: ${e}`,"",r==null?"":`Stack trace:
85
+ ${r}`].join(`
86
+ `);await Promise.all([re(J.join(n,"error.txt"),s),re(J.join(n,"summary.txt"),a)]),m.info("Debug error artifacts written to .ripplo/debug/%s/",t)}catch(n){let s=n instanceof Error?n.message:String(n);m.warn("Failed to write error debug artifacts: %s",s)}}var vt=y(()=>{"use strict";H()});async function gr({baseUrl:e,cookies:t,executedPreconditions:r,extraVariables:o,headed:n,navigateTo:s,runId:a,serverUrl:i,spec:l,streaming:c,systemPrompt:p,token:f,workflowContext:u}){let h=await ue({headed:n}),g=await h.newContext({baseURL:e});t.length>0&&(await g.addCookies([...t]),m.info("Injected %d cookies from preconditions",t.length));let b=await g.newPage();s!=null&&(m.info("Navigating to precondition start page: %s",s),await b.goto(s,{waitUntil:"domcontentloaded"}));try{let k=function(A){c.enqueueStep(A),St({context:g,page:b,runId:a,stepIndex:A.stepIndex,stepResult:A})};var P=k;let S=await ze({baseUrl:e,executedPreconditions:r,extraVariables:o,onStep:k,page:b,runId:a,serverUrl:i,spec:l,systemPrompt:p,token:f,workflowContext:u}),N=S.verdict==="pass"?"passed":"failed";await c.complete({statusOverride:N,steps:S.steps,summary:S.findings});let j=S.steps.filter(A=>A.status==="passed").length,I=S.steps.filter(A=>A.status==="failed").length,G={duration:S.steps.reduce((A,V)=>A+V.duration,0),failCount:I,passCount:j,runId:a,status:N,workflowName:u.name};await kt({monitor:S.monitor,runId:a,steps:S.steps,summary:G}),m.info("Agent test complete: %d passed, %d failed",j,I),m.info(`
87
87
  === Agent Summary ===
88
- %s`,j.findings)}finally{await y.close()}}var eo=m(()=>{"use strict";at();Jt();ct();D()});async function to({expected:e,locator:t,operator:o,timeout:r}){let n=await t.textContent({timeout:r});return Z({actual:n??"",expected:e,label:"Text",operator:o})}function oo({expected:e,operator:t,url:o}){return Z({actual:o,expected:e,label:"URL",operator:t})}async function ro({expected:e,locator:t,operator:o}){let r=await t.count();return dt({actual:r,expected:e,label:"Count",operator:o})}async function no({expected:e,locator:t,operator:o,timeout:r}){let n=await t.inputValue({timeout:r});return Z({actual:n,expected:e,label:"Value",operator:o})}async function De({locator:e,timeout:t}){try{return await e.waitFor({state:"visible",timeout:t}),{description:"Element is visible",detail:void 0,status:"passed"}}catch{return{description:"Element is visible",detail:"Element not visible",status:"failed"}}}async function We({locator:e,timeout:t}){try{return await e.waitFor({state:"hidden",timeout:t}),{description:"Element is not visible",detail:void 0,status:"passed"}}catch{return{description:"Element is not visible",detail:"Element still visible",status:"failed"}}}async function as({attribute:e,expected:t,locator:o,operator:r,timeout:n}){let s=await o.getAttribute(e,{timeout:n});return Z({actual:s??"",expected:t,label:`Attribute "${e}"`,operator:r})}async function is({locator:e,timeout:t}){try{return await e.waitFor({state:"visible",timeout:t}),await e.isEnabled()?{description:"Element is enabled",detail:void 0,status:"passed"}:{description:"Element is enabled",detail:"Element is disabled",status:"failed"}}catch{return{description:"Element is enabled",detail:"Element not found",status:"failed"}}}async function ls({locator:e,timeout:t}){try{return await e.waitFor({state:"visible",timeout:t}),await e.isDisabled()?{description:"Element is disabled",detail:void 0,status:"passed"}:{description:"Element is disabled",detail:"Element is enabled",status:"failed"}}catch{return{description:"Element is disabled",detail:"Element not found",status:"failed"}}}function cs({expected:e,operator:t,title:o}){return Z({actual:o,expected:e,label:"Title",operator:t})}async function ds({locator:e,timeout:t}){try{return await e.waitFor({state:"visible",timeout:t}),await e.isChecked()?{description:"Element is checked",detail:void 0,status:"passed"}:{description:"Element is checked",detail:"Element is not checked",status:"failed"}}catch{return{description:"Element is checked",detail:"Element not found",status:"failed"}}}async function us({locator:e,timeout:t}){try{return await e.waitFor({state:"visible",timeout:t}),await e.isChecked()?{description:"Element is not checked",detail:"Element is checked",status:"failed"}:{description:"Element is not checked",detail:void 0,status:"passed"}}catch{return{description:"Element is not checked",detail:"Element not found",status:"failed"}}}async function ps({locator:e,timeout:t}){try{return await e.waitFor({state:"visible",timeout:t}),!await e.evaluate("(el) => document.activeElement === el")?{description:"Element is focused",detail:"Element is not focused",status:"failed"}:{description:"Element is focused",detail:void 0,status:"passed"}}catch{return{description:"Element is focused",detail:"Element not found",status:"failed"}}}function fs({cookies:e,expected:t}){let o=e.find(n=>n.name===t.name);if(o==null)return{description:`Cookie "${t.name}" exists`,detail:"Cookie not found",status:"failed"};let r=al({cookie:o,expected:t});return r.length>0?{description:`Cookie "${t.name}"`,detail:r.join("; "),status:"failed"}:{description:`Cookie "${t.name}"`,detail:void 0,status:"passed"}}function al({cookie:e,expected:t}){return[il({cookie:e,expected:t}),ss("httpOnly",t.httpOnly,e.httpOnly),ss("secure",t.secure,e.secure),ll(t.sameSite,e.sameSite)].filter(o=>o!=null)}function il({cookie:e,expected:t}){if(t.value==null||t.operator==null)return;let o=Z({actual:e.value,expected:t.value,label:"Value",operator:t.operator});return o.status==="failed"?o.detail??"value mismatch":void 0}function ss(e,t,o){if(!(t==null||o===t))return`${e}: expected ${String(t)}, got ${String(o)}`}function ll(e,t){if(!(e==null||t===e))return`sameSite: expected ${e}, got ${t}`}async function ms({bodyContains:e,headerContains:t,page:o,status:r,timeout:n,urlPattern:s}){let a=await o.waitForResponse(l=>l.url().includes(s),{timeout:n}),i=[cl(r,a.status()),await dl(e,a),ul(t,a.headers())].filter(l=>l!=null);return i.length===0?[{description:"Response matching "+JSON.stringify(s)+" received",detail:void 0,status:"passed"}]:i}function cl(e,t){if(e!=null)return{description:`Response status equals ${String(e)}`,detail:t===e?void 0:`Got: ${String(t)}`,status:t===e?"passed":"failed"}}async function dl(e,t){if(e==null)return;let r=(await t.text()).includes(e);return{description:`Response body contains "${e}"`,detail:r?void 0:"Not found in response body",status:r?"passed":"failed"}}function ul(e,t){if(e==null)return;let o=t[e.name.toLowerCase()],r=o!=null&&o.includes(e.value);return{description:`Response header "${e.name}" contains "${e.value}"`,detail:r?void 0:`Got: "${o??"(missing)"}"`,status:r?"passed":"failed"}}function Z(e){let t=`${e.label} ${e.operator} "${e.expected}"`,o=pl(e),r=o?void 0:`Got: "${e.actual}"`;return{description:t,detail:r,status:o?"passed":"failed"}}function pl({actual:e,expected:t,operator:o}){return o==="equals"?e===t:o==="notEquals"?e!==t:o==="contains"?e.includes(t):o==="startsWith"?e.startsWith(t):o==="endsWith"?e.endsWith(t):new RegExp(t).test(e)}function dt(e){let t=`${e.label} ${e.operator} ${String(e.expected)}`,o=fl(e),r=o?void 0:`Got: ${String(e.actual)}`;return{description:t,detail:r,status:o?"passed":"failed"}}function fl({actual:e,expected:t,operator:o}){return o==="equals"?e===t:o==="notEquals"?e!==t:o==="greaterThan"?e>t:o==="greaterThanOrEqual"?e>=t:o==="lessThan"?e<t:e<=t}var Le=m(()=>{"use strict"});import{print as ml}from"graphql";async function T(e){let t=ml(e.document),o=JSON.stringify({query:t,variables:e.variables}),r=`${e.config.ripploServerUrl}/graphql`,n;try{n=await fetch(r,{body:o,headers:{Authorization:`Bearer ${e.config.token}`,"Content-Type":"application/json"},method:"POST"})}catch(a){let i=a instanceof Error?a.message:String(a);throw new Error(`Failed to connect to Ripplo server at ${e.config.ripploServerUrl}. Make sure \`ripplo dev\` is running and your internet connection is active. Details: ${i}`)}let s=await n.json();if(!gl(s))throw new Error("Invalid GraphQL response");if(hl(s))throw new Error(s.errors.map(a=>a.message).join(", "));if(s.data==null)throw new Error("No data returned from server");return s.data}function gl(e){return typeof e=="object"&&e!=null&&("data"in e||"errors"in e)}function hl(e){return Array.isArray(e.errors)&&e.errors.length>0}var _e=m(()=>{"use strict"});import{readdir as yl,rm as wl,stat as bl}from"fs/promises";import sh from"os";import ys from"path";import{graphql as Sl}from"gql.tada";async function qe({maxRuns:e}){try{let o=(await yl(gs,{withFileTypes:!0})).filter(c=>c.isDirectory()),r=Date.now(),n=await Promise.all(o.map(async c=>{let p=ys.join(gs,c.name),f=await bl(p);return{dirPath:p,mtime:f.mtimeMs}})),s=n.filter(c=>r-c.mtime>hs),i=n.filter(c=>r-c.mtime<=hs).toSorted((c,p)=>p.mtime-c.mtime).slice(e),l=[...s,...i];if(l.length===0)return;await Promise.allSettled(l.map(c=>wl(c.dirPath,{force:!0,recursive:!0}))),u.info("Pruned %d old debug run(s)",l.length)}catch{u.warn("Debug run pruning failed, ignoring")}}var gs,hs,dh,ws=m(()=>{"use strict";_e();D();gs=ys.join(process.cwd(),".ripplo","debug"),hs=360*60*1e3,dh=Sl(`
88
+ %s`,S.findings)}finally{await h.close()}}var yr=y(()=>{"use strict";bt();ur();vt();H()});async function wr({expected:e,locator:t,operator:r,timeout:o}){let n=await t.textContent({timeout:o});return ae({actual:n??"",expected:e,label:"Text",operator:r})}function br({expected:e,operator:t,url:r}){return ae({actual:r,expected:e,label:"URL",operator:t})}async function Sr({expected:e,locator:t,operator:r}){let o=await t.count();return Rt({actual:o,expected:e,label:"Count",operator:r})}async function kr({expected:e,locator:t,operator:r,timeout:o}){let n=await t.inputValue({timeout:o});return ae({actual:n,expected:e,label:"Value",operator:r})}async function He({locator:e,timeout:t}){try{return await e.waitFor({state:"visible",timeout:t}),{description:"Element is visible",detail:void 0,status:"passed"}}catch{return{description:"Element is visible",detail:"Element not visible",status:"failed"}}}async function Je({locator:e,timeout:t}){try{return await e.waitFor({state:"hidden",timeout:t}),{description:"Element is not visible",detail:void 0,status:"passed"}}catch{return{description:"Element is not visible",detail:"Element still visible",status:"failed"}}}async function Cs({attribute:e,expected:t,locator:r,operator:o,timeout:n}){let s=await r.getAttribute(e,{timeout:n});return ae({actual:s??"",expected:t,label:`Attribute "${e}"`,operator:o})}async function Ts({locator:e,timeout:t}){try{return await e.waitFor({state:"visible",timeout:t}),await e.isEnabled()?{description:"Element is enabled",detail:void 0,status:"passed"}:{description:"Element is enabled",detail:"Element is disabled",status:"failed"}}catch{return{description:"Element is enabled",detail:"Element not found",status:"failed"}}}async function Is({locator:e,timeout:t}){try{return await e.waitFor({state:"visible",timeout:t}),await e.isDisabled()?{description:"Element is disabled",detail:void 0,status:"passed"}:{description:"Element is disabled",detail:"Element is enabled",status:"failed"}}catch{return{description:"Element is disabled",detail:"Element not found",status:"failed"}}}function As({expected:e,operator:t,title:r}){return ae({actual:r,expected:e,label:"Title",operator:t})}async function Ns({locator:e,timeout:t}){try{return await e.waitFor({state:"visible",timeout:t}),await e.isChecked()?{description:"Element is checked",detail:void 0,status:"passed"}:{description:"Element is checked",detail:"Element is not checked",status:"failed"}}catch{return{description:"Element is checked",detail:"Element not found",status:"failed"}}}async function js({locator:e,timeout:t}){try{return await e.waitFor({state:"visible",timeout:t}),await e.isChecked()?{description:"Element is not checked",detail:"Element is checked",status:"failed"}:{description:"Element is not checked",detail:void 0,status:"passed"}}catch{return{description:"Element is not checked",detail:"Element not found",status:"failed"}}}async function $s({locator:e,timeout:t}){try{return await e.waitFor({state:"visible",timeout:t}),!await e.evaluate("(el) => document.activeElement === el")?{description:"Element is focused",detail:"Element is not focused",status:"failed"}:{description:"Element is focused",detail:void 0,status:"passed"}}catch{return{description:"Element is focused",detail:"Element not found",status:"failed"}}}function Es({cookies:e,expected:t}){let r=e.find(n=>n.name===t.name);if(r==null)return{description:`Cookie "${t.name}" exists`,detail:"Cookie not found",status:"failed"};let o=Bl({cookie:r,expected:t});return o.length>0?{description:`Cookie "${t.name}"`,detail:o.join("; "),status:"failed"}:{description:`Cookie "${t.name}"`,detail:void 0,status:"passed"}}function Bl({cookie:e,expected:t}){return[Ml({cookie:e,expected:t}),xs("httpOnly",t.httpOnly,e.httpOnly),xs("secure",t.secure,e.secure),zl(t.sameSite,e.sameSite)].filter(r=>r!=null)}function Ml({cookie:e,expected:t}){if(t.value==null||t.operator==null)return;let r=ae({actual:e.value,expected:t.value,label:"Value",operator:t.operator});return r.status==="failed"?r.detail??"value mismatch":void 0}function xs(e,t,r){if(!(t==null||r===t))return`${e}: expected ${String(t)}, got ${String(r)}`}function zl(e,t){if(!(e==null||t===e))return`sameSite: expected ${e}, got ${t}`}async function Os({bodyContains:e,headerContains:t,page:r,status:o,timeout:n,urlPattern:s}){let a=await r.waitForResponse(l=>l.url().includes(s),{timeout:n}),i=[Gl(o,a.status()),await Hl(e,a),Jl(t,a.headers())].filter(l=>l!=null);return i.length===0?[{description:"Response matching "+JSON.stringify(s)+" received",detail:void 0,status:"passed"}]:i}function Gl(e,t){if(e!=null)return{description:`Response status equals ${String(e)}`,detail:t===e?void 0:`Got: ${String(t)}`,status:t===e?"passed":"failed"}}async function Hl(e,t){if(e==null)return;let o=(await t.text()).includes(e);return{description:`Response body contains "${e}"`,detail:o?void 0:"Not found in response body",status:o?"passed":"failed"}}function Jl(e,t){if(e==null)return;let r=t[e.name.toLowerCase()],o=r!=null&&r.includes(e.value);return{description:`Response header "${e.name}" contains "${e.value}"`,detail:o?void 0:`Got: "${r??"(missing)"}"`,status:o?"passed":"failed"}}function ae(e){let t=`${e.label} ${e.operator} "${e.expected}"`,r=Kl(e),o=r?void 0:`Got: "${e.actual}"`;return{description:t,detail:o,status:r?"passed":"failed"}}function Kl({actual:e,expected:t,operator:r}){return r==="equals"?e===t:r==="notEquals"?e!==t:r==="contains"?e.includes(t):r==="startsWith"?e.startsWith(t):r==="endsWith"?e.endsWith(t):new RegExp(t).test(e)}function Rt(e){let t=`${e.label} ${e.operator} ${String(e.expected)}`,r=Yl(e),o=r?void 0:`Got: ${String(e.actual)}`;return{description:t,detail:o,status:r?"passed":"failed"}}function Yl({actual:e,expected:t,operator:r}){return r==="equals"?e===t:r==="notEquals"?e!==t:r==="greaterThan"?e>t:r==="greaterThanOrEqual"?e>=t:r==="lessThan"?e<t:e<=t}var Ke=y(()=>{"use strict"});import{print as Ql}from"graphql";async function $(e){let t=Ql(e.document),r=JSON.stringify({query:t,variables:e.variables}),o=`${e.config.ripploServerUrl}/graphql`,n;try{n=await fetch(o,{body:r,headers:{Authorization:`Bearer ${e.config.token}`,"Content-Type":"application/json"},method:"POST"})}catch(a){let i=a instanceof Error?a.message:String(a);throw new Error(`Failed to connect to Ripplo server at ${e.config.ripploServerUrl}. Make sure \`ripplo dev\` is running and your internet connection is active. Details: ${i}`)}let s=await n.json();if(!Zl(s))throw new Error("Invalid GraphQL response");if(Xl(s))throw new Error(s.errors.map(a=>a.message).join(", "));if(s.data==null)throw new Error("No data returned from server");return s.data}function Zl(e){return typeof e=="object"&&e!=null&&("data"in e||"errors"in e)}function Xl(e){return Array.isArray(e.errors)&&e.errors.length>0}var Ye=y(()=>{"use strict"});import{readdir as ec,rm as tc,stat as rc}from"fs/promises";import Zg from"os";import Ds from"path";import{graphql as oc}from"gql.tada";async function Qe({maxRuns:e}){try{let r=(await ec(Us,{withFileTypes:!0})).filter(c=>c.isDirectory()),o=Date.now(),n=await Promise.all(r.map(async c=>{let p=Ds.join(Us,c.name),f=await rc(p);return{dirPath:p,mtime:f.mtimeMs}})),s=n.filter(c=>o-c.mtime>Fs),i=n.filter(c=>o-c.mtime<=Fs).toSorted((c,p)=>p.mtime-c.mtime).slice(e),l=[...s,...i];if(l.length===0)return;await Promise.allSettled(l.map(c=>tc(c.dirPath,{force:!0,recursive:!0}))),m.info("Pruned %d old debug run(s)",l.length)}catch{m.warn("Debug run pruning failed, ignoring")}}var Us,Fs,oy,Vs=y(()=>{"use strict";Ye();H();Us=Ds.join(process.cwd(),".ripplo","debug"),Fs=360*60*1e3,oy=oc(`
89
89
  mutation RevokeCurrentCliToken {
90
90
  revokeCurrentCliToken
91
91
  }
92
- `)});async function so({baseUrl:e}){try{await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(kl)})}catch(t){let o=t instanceof Error?t.message:String(t);throw u.debug("Base URL reachability check failed: %s",o),new Error([`Could not reach your dev server at ${e}.`,"","Troubleshooting:",` 1. Make sure your app is running at ${e}`," 2. Check the `baseUrl` in `.ripplo/settings.json` \u2014 is the port correct?"," 3. If your app runs on a different port, update `baseUrl` in `.ripplo/settings.json`"].join(`
93
- `))}}var kl,ao=m(()=>{"use strict";D();kl=5e3});async function io({condition:e,page:t,timeout:o,variables:r}){switch(e.type){case"elementVisible":return(await De({locator:P({locator:e.locator,page:t}),timeout:o})).status==="passed";case"elementNotVisible":return(await We({locator:P({locator:e.locator,page:t}),timeout:o})).status==="passed";case"urlMatch":{let n=C({ref:e.expected,variables:r});return Z({actual:t.url(),expected:n,label:"URL",operator:e.operator}).status==="passed"}case"textMatch":{let s=await P({locator:e.locator,page:t}).textContent({timeout:o}),a=C({ref:e.expected,variables:r});return Z({actual:s??"",expected:a,label:"Text",operator:e.operator}).status==="passed"}case"variableCompare":{let n=r[e.variable];if(n==null)throw new Error(`Variable "${e.variable}" is not defined`);let s=typeof n=="number"?n:Number(n),a=me({ref:e.expected,variables:r}),i=typeof a=="number"?a:Number(a);return dt({actual:s,expected:i,label:e.variable,operator:e.operator}).status==="passed"}}}var lo=m(()=>{"use strict";Le();ie();Q()});import ke from"fs";import co from"path";import{z as ce}from"zod";function bs(e){if(!ke.existsSync(e))return null;let t=ke.readFileSync(e,"utf8");return JSON.parse(t)}function _(){let e=bs(Ss),t=bs(ks);if(e==null||t==null)return null;let o=Pl.safeParse({...e,...t});return o.success?o.data:null}function ne(e){ke.existsSync(ut)||ke.mkdirSync(ut,{recursive:!0});let{ripploServerUrl:t,token:o,...r}=e;ke.writeFileSync(Ss,JSON.stringify(r,null,2)+`
94
- `),ke.writeFileSync(ks,JSON.stringify({ripploServerUrl:t,token:o},null,2)+`
95
- `)}var Rl,vl,Pl,ut,Ss,ks,Rs=m(()=>{"use strict";Rl=ce.object({baseUrl:ce.string().optional(),cloudBaseUrl:ce.string(),preconditionApiPath:ce.string().optional(),projectId:ce.string()}),vl=ce.object({ripploServerUrl:ce.string(),token:ce.string()}),Pl=Rl.extend(vl.shape),ut=co.join(process.cwd(),".ripplo"),Ss=co.join(ut,"settings.json"),ks=co.join(ut,"settings.local.json")});async function uo({executeSequence:e,failFast:t,node:o,page:r,spec:n,startIndex:s,timeout:a,variables:i}){let c=await io({condition:o.condition,page:r,timeout:a,variables:i})?o.consequent:o.alternate??[];return c.length===0?{steps:[],variables:i}:e({failFast:t,nodeIds:c,page:r,spec:n,startIndex:s,timeout:a,variables:i})}async function po({executeSequence:e,failFast:t,node:o,page:r,spec:n,startIndex:s,timeout:a,variables:i}){let l=[],c=i;for(let p=0;p<o.times;p++){o.iteratorVar!=null&&(c=oe({name:o.iteratorVar,store:c,value:p}));let f=await e({failFast:t,nodeIds:o.body,page:r,spec:n,startIndex:s+l.length,timeout:a,variables:c});if(l.push(...f.steps),c=f.variables,t&&f.steps.some(h=>h.status==="failed"))break}return{steps:l,variables:c}}async function fo({executeSequence:e,failFast:t,node:o,page:r,spec:n,startIndex:s,timeout:a,variables:i}){let l=Tl({collection:o.collection,variables:i}),c=[],p=i;for(let f of l){p=oe({name:o.iteratorVar,store:p,value:xl(f)});let h=await e({failFast:t,nodeIds:o.body,page:r,spec:n,startIndex:s+c.length,timeout:a,variables:p});if(c.push(...h.steps),p=h.variables,t&&h.steps.some(y=>y.status==="failed"))break}return{steps:c,variables:p}}function xl(e){return typeof e=="object"&&e!=null?JSON.stringify(e):e==null?"":String(e)}function Tl({collection:e,variables:t}){if(Array.isArray(e))return e;let o=t[e.name];if(o==null)throw new Error(`Variable "${e.name}" is not defined`);return Cl(o)}function Cl(e){if(typeof e!="string")return[e];try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}async function mo({executeSequence:e,failFast:t,node:o,page:r,spec:n,startIndex:s,timeout:a,variables:i}){let l=await Promise.all(o.branches.map(f=>e({failFast:t,nodeIds:f,page:r,spec:n,startIndex:s,timeout:a,variables:i}))),c=l.flatMap(f=>f.steps),p=Il({base:i,results:l});return{steps:c,variables:p}}function Il({base:e,results:t}){let o=e;return t.forEach(r=>{o={...o,...r.variables}}),o}async function go({executeSequence:e,failFast:t,node:o,page:r,spec:n,startIndex:s,timeout:a,variables:i}){let l=[],c=i;try{let p=await e({failFast:t,nodeIds:o.body,page:r,spec:n,startIndex:s,timeout:a,variables:c});if(l.push(...p.steps),c=p.variables,p.steps.some(h=>h.status==="failed")&&o.catch!=null){let h=await e({failFast:t,nodeIds:o.catch,page:r,spec:n,startIndex:s+l.length,timeout:a,variables:c});l.push(...h.steps),c=h.variables}}catch{if(o.catch!=null){let p=await e({failFast:t,nodeIds:o.catch,page:r,spec:n,startIndex:s+l.length,timeout:a,variables:c});l.push(...p.steps),c=p.variables}}finally{if(o.finally!=null){let p=await e({failFast:t,nodeIds:o.finally,page:r,spec:n,startIndex:s+l.length,timeout:a,variables:c});l.push(...p.steps),c=p.variables}}return{steps:l,variables:c}}async function ho({executeSequence:e,failFast:t,node:o,page:r,spec:n,startIndex:s,timeout:a,variables:i}){return e({failFast:t,nodeIds:o.nodes,page:r,spec:n,startIndex:s,timeout:a,variables:i})}var yo=m(()=>{"use strict";lo();Q()});import{z as I}from"zod";var Al,Nl,jl,$l,El,Ol,Ul,k,pt=m(()=>{"use strict";Al=I.object({by:I.literal("css"),value:I.string().min(1)}),Nl=I.object({by:I.literal("testId"),value:I.string().min(1)}),jl=I.object({by:I.literal("role"),exact:I.boolean().optional(),name:I.string().optional(),role:I.string().min(1)}),$l=I.object({by:I.literal("text"),exact:I.boolean().optional(),value:I.string().min(1)}),El=I.object({by:I.literal("label"),exact:I.boolean().optional(),value:I.string().min(1)}),Ol=I.object({by:I.literal("placeholder"),value:I.string().min(1)}),Ul=I.object({by:I.literal("altText"),value:I.string().min(1)}),k=I.discriminatedUnion("by",[Al,Nl,jl,$l,El,Ol,Ul])});import{z as vs}from"zod";var V,de,ft=m(()=>{"use strict";V=vs.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),de=vs.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"])});import{z as O}from"zod";var Fl,wo,ge,A,Re,mt=m(()=>{"use strict";Fl=O.object({type:O.literal("static"),value:O.union([O.string(),O.number(),O.boolean()])}),wo=O.object({name:O.string().min(1),type:O.literal("variable")}),ge=O.discriminatedUnion("type",[Fl,wo]),A=O.discriminatedUnion("type",[O.object({type:O.literal("static"),value:O.string()}),wo]),Re=O.discriminatedUnion("type",[O.object({type:O.literal("static"),value:O.number().int().nonnegative()}),wo])});import{z as G}from"zod";var ve,bo=m(()=>{"use strict";pt();ft();mt();ve=G.discriminatedUnion("type",[G.object({locator:k,type:G.literal("elementVisible")}),G.object({locator:k,type:G.literal("elementNotVisible")}),G.object({expected:A,operator:V,type:G.literal("urlMatch")}),G.object({expected:A,locator:k,operator:V,type:G.literal("textMatch")}),G.object({expected:ge,operator:de,type:G.literal("variableCompare"),variable:G.string().min(1)})])});import{z as q}from"zod";var Be,So=m(()=>{"use strict";Be=q.discriminatedUnion("type",[q.object({default:q.string().optional(),type:q.literal("string")}),q.object({default:q.number().optional(),type:q.literal("number")}),q.object({default:q.boolean().optional(),type:q.literal("boolean")}),q.object({key:q.string().min(1),type:q.literal("env")})])});import{z as d}from"zod";var Vl,se,b,Dl,Wl,Ll,_l,ql,Bl,Ml,Gl,zl,Hl,Jl,Yl,Kl,Ql,Zl,Xl,ec,tc,oc,rc,nc,sc,ac,ic,lc,cc,dc,uc,pc,fc,mc,gc,hc,yc,wc,bc,Sc,kc,Rc,vc,Pc,xc,Tc,Cc,Ic,Ac,Nc,jc,$c,Ec,Oc,ko,Ps,Pe,Ro=m(()=>{"use strict";bo();pt();ft();mt();So();bo();pt();ft();mt();So();Vl=d.string().min(1),se=d.array(Vl).min(1),b={comment:d.string().optional(),id:d.string().min(1),label:d.string().optional(),next:d.string().optional(),timeout:d.number().int().positive().optional()},Dl=d.object({...b,type:d.literal("goto"),url:A}),Wl=d.object({...b,locator:k,type:d.literal("click")}),Ll=d.object({...b,locator:k,type:d.literal("fill"),value:A}),_l=d.object({...b,locator:k,type:d.literal("select"),value:A}),ql=d.object({...b,locator:k,type:d.literal("hover")}),Bl=d.object({...b,key:d.string().min(1),locator:k.optional(),type:d.literal("press")}),Ml=d.object({...b,locator:k,type:d.literal("check")}),Gl=d.object({...b,locator:k,type:d.literal("uncheck")}),zl=d.object({...b,type:d.literal("screenshot")}),Hl=d.object({...b,height:d.number().int().positive(),type:d.literal("setViewport"),width:d.number().int().positive()}),Jl=d.object({...b,duration:d.number().int().positive(),type:d.literal("wait")}),Yl=d.object({...b,message:d.string().min(1),type:d.literal("fail")}),Kl=d.object({...b,type:d.literal("setVariable"),value:ge,variable:d.string().min(1)}),Ql=d.object({...b,locator:k,type:d.literal("extractText"),variable:d.string().min(1)}),Zl=d.object({...b,files:d.array(d.string()).min(1),locator:k,type:d.literal("upload")}),Xl=d.object({...b,locator:k,type:d.literal("dblclick")}),ec=d.object({...b,source:k,target:k,type:d.literal("drag")}),tc=d.object({...b,locator:k,type:d.literal("scrollIntoView")}),oc=d.object({...b,locator:k,type:d.literal("type"),value:A}),rc=d.object({...b,locator:k,type:d.literal("focus")}),nc=d.object({...b,locator:k,type:d.literal("clear")}),sc=d.object({...b,locator:k,type:d.literal("rightClick")}),ac=d.object({...b,action:d.enum(["accept","dismiss"]),promptText:d.string().optional(),type:d.literal("handleDialog")}),ic=d.object({...b,locator:k.optional(),type:d.literal("scroll"),x:d.number().int().optional(),y:d.number().int().optional()}),lc=d.object({...b,action:d.enum(["read","write"]),type:d.literal("clipboard"),value:A.optional(),variable:d.string().min(1).optional()}),cc=d.object({...b,permission:d.string().min(1),state:d.enum(["granted","prompt"]),type:d.literal("setPermission")}),dc=d.object({...b,locator:k,state:d.enum(["visible","hidden","attached","detached"]).optional(),type:d.literal("waitFor")}),uc=d.object({...b,expected:A,operator:V,type:d.literal("waitForUrl")}),pc=d.object({...b,type:d.literal("waitForResponse"),urlPattern:A}),fc=d.object({...b,type:d.literal("waitForRequest"),urlPattern:A}),mc=d.object({...b,locator:k,type:d.literal("assertVisible")}),gc=d.object({...b,locator:k,type:d.literal("assertNotVisible")}),hc=d.object({...b,expected:A,locator:k,operator:V,type:d.literal("assertText")}),yc=d.object({...b,expected:A,operator:V,type:d.literal("assertUrl")}),wc=d.object({...b,expected:Re,locator:k,operator:de,type:d.literal("assertCount")}),bc=d.object({...b,expected:A,locator:k,operator:V,type:d.literal("assertValue")}),Sc=d.object({...b,attribute:d.string().min(1),expected:A,locator:k,operator:V,type:d.literal("assertAttribute")}),kc=d.object({...b,locator:k,type:d.literal("assertEnabled")}),Rc=d.object({...b,locator:k,type:d.literal("assertDisabled")}),vc=d.object({...b,expected:A,operator:V,type:d.literal("assertTitle")}),Pc=d.object({...b,locator:k,type:d.literal("assertChecked")}),xc=d.object({...b,locator:k,type:d.literal("assertNotChecked")}),Tc=d.object({...b,locator:k,type:d.literal("assertFocused")}),Cc=d.object({...b,httpOnly:d.boolean().optional(),name:A,operator:V.optional(),sameSite:d.enum(["Strict","Lax","None"]).optional(),secure:d.boolean().optional(),type:d.literal("assertCookie"),value:A.optional()}),Ic=d.object({...b,bodyContains:A.optional(),headerContains:d.object({name:d.string().min(1),value:A}).optional(),status:d.number().int().positive().optional(),type:d.literal("assertResponse"),urlPattern:A}),Ac=d.object({...b,alternate:se.optional(),condition:ve,consequent:se,type:d.literal("if")}),Nc=d.object({...b,body:se,iteratorVar:d.string().min(1).optional(),times:d.number().int().positive(),type:d.literal("loop")}),jc=d.object({...b,body:se,collection:d.union([d.array(d.record(d.string(),d.unknown())).min(1),d.object({name:d.string().min(1),type:d.literal("variable")})]),iteratorVar:d.string().min(1),type:d.literal("forEach")}),$c=d.object({...b,branches:d.array(se).min(2),type:d.literal("parallel")}),Ec=d.object({...b,body:se,catch:se.optional(),finally:se.optional(),type:d.literal("try")}).refine(e=>e.catch!=null||e.finally!=null,{message:"try node must have at least one of 'catch' or 'finally'"}),Oc=d.object({...b,nodes:se,type:d.literal("group")}),ko=d.discriminatedUnion("type",[Dl,Wl,Ll,_l,ql,Bl,Ml,Gl,dc,uc,pc,fc,mc,gc,hc,yc,wc,bc,Sc,kc,Rc,zl,Hl,Jl,Yl,Kl,Ql,Zl,Xl,ec,tc,oc,rc,nc,sc,ac,ic,lc,cc,vc,Pc,xc,Tc,Cc,Ic,Ac,Nc,jc,$c,Oc]),Ps=d.union([ko,Ec]),Pe=d.object({entryNode:d.string().min(1),nodes:d.record(d.string(),Ps),variables:d.record(d.string(),Be).optional(),version:d.literal(2)})});function ue(e){let t=Pe.safeParse(e);return t.success?{data:t.data,success:!0}:{errors:t.error.issues.map(o=>({message:o.message,path:o.path.join(".")})),success:!1}}var xs=m(()=>{"use strict";Ro()});var he=m(()=>{"use strict";Ro();xs()});async function Ts({node:e,page:t,timeout:o,variables:r}){switch(e.type){case"assertTitle":{let n=C({ref:e.expected,variables:r});return[cs({expected:n,operator:e.operator,title:await t.title()})]}case"assertChecked":return[await ds({locator:P({locator:e.locator,page:t}),timeout:o})];case"assertNotChecked":return[await us({locator:P({locator:e.locator,page:t}),timeout:o})];case"assertFocused":return[await ps({locator:P({locator:e.locator,page:t}),timeout:o})];case"assertCookie":return Uc({node:e,page:t,variables:r});case"assertResponse":return Fc({node:e,page:t,timeout:o,variables:r})}}async function Uc({node:e,page:t,variables:o}){let r=C({ref:e.name,variables:o}),n=e.value==null?void 0:C({ref:e.value,variables:o}),s=await t.context().cookies();return[fs({cookies:s,expected:{httpOnly:e.httpOnly,name:r,operator:e.operator,sameSite:e.sameSite,secure:e.secure,value:n}})]}async function Fc({node:e,page:t,timeout:o,variables:r}){let n=C({ref:e.urlPattern,variables:r}),s=e.bodyContains==null?void 0:C({ref:e.bodyContains,variables:r}),a=e.headerContains==null?void 0:{name:e.headerContains.name,value:C({ref:e.headerContains.value,variables:r})};return ms({bodyContains:s,headerContains:a,page:t,status:e.status,timeout:o,urlPattern:n})}var Cs=m(()=>{"use strict";Le();ie();Q()});async function L({fn:e,label:t}){let o=performance.now(),r=await e();return u.info("%s: %dms",t,Math.round(performance.now()-o)),r}var gt=m(()=>{"use strict";D()});async function vo({failFast:e,onStep:t,page:o,spec:r,variables:n}){let s=performance.now();return Wc({currentId:r.entryNode,failFast:e,onStep:t,page:o,runStartTime:s,spec:r,startIndex:0,variables:n})}function Dc({onStep:e,steps:t,target:o}){t.forEach(r=>{o.push(r),e?.(r)})}async function Wc({currentId:e,failFast:t,onStep:o,page:r,runStartTime:n,spec:s,startIndex:a,variables:i}){let l=[],c=i,p=e;for(;p!=null;){let f=s.nodes[p];if(f==null)throw new Error(`Node "${p}" not found in spec`);let h=p,y=f.label??`${f.type} (${p})`;u.info("Executing node: %s [%s]",y,f.type);let x=await Is({failFast:t,node:f,nodeId:h,page:r,runStartTime:n,spec:s,startIndex:a+l.length,variables:c});if(Dc({onStep:o,steps:x.steps,target:l}),c=x.variables,t&&x.steps.some(R=>R.status==="failed"))break;p=f.next}return{steps:l,variables:c}}async function Is({failFast:e,node:t,nodeId:o,page:r,runStartTime:n,spec:s,startIndex:a,variables:i}){let l=performance.now(),c=t.label??`${t.type} (${t.id})`,p=t.timeout??Vc;if(Lc(t))return _c({failFast:e,node:t,page:r,spec:s,startIndex:a,timeout:p,variables:i});let f=ot({node:t,page:r});try{let h=await Gc({node:t,page:r,timeout:p,variables:i}),y=Math.round(performance.now()-l),x=h.assertions.some(S=>S.status==="failed"),R=await L({label:`Snapshot [${c}]`,fn:()=>le({page:r,runStartTime:n,targets:f})});return{steps:[{annotations:R.annotations,assertions:h.assertions,detail:void 0,duration:y,nodeId:o,nodeType:t.type,screenshotBase64:R.screenshotBase64,snapshotTimestamp:R.snapshotTimestamp,status:x?"failed":"passed",stepIndex:a,title:c,url:R.url,viewportHeight:R.viewportHeight,viewportWidth:R.viewportWidth}],variables:h.variables}}catch(h){let y=Math.round(performance.now()-l),x=h instanceof Error?h.message:String(h),R=await L({label:`Snapshot [${c}] (error)`,fn:()=>le({page:r,runStartTime:n,targets:f})});return{steps:[{annotations:R.annotations,assertions:[],detail:x,duration:y,nodeId:o,nodeType:t.type,screenshotBase64:R.screenshotBase64,snapshotTimestamp:R.snapshotTimestamp,status:"failed",stepIndex:a,title:c,url:R.url,viewportHeight:R.viewportHeight,viewportWidth:R.viewportWidth}],variables:i}}}function Lc(e){return["if","loop","forEach","parallel","try","group"].includes(e.type)}async function _c({failFast:e,node:t,page:o,spec:r,startIndex:n,timeout:s,variables:a}){let i={executeSequence:Mc,failFast:e,page:o,spec:r,startIndex:n,timeout:s,variables:a};switch(t.type){case"if":return uo({...i,node:t});case"loop":return po({...i,node:t});case"forEach":return fo({...i,node:t});case"parallel":return mo({...i,node:t});case"try":return go({...i,node:t});case"group":return ho({...i,node:t})}}function qc(e){return e.some(t=>t.status==="failed")}function Bc({nodeId:e,spec:t,timeout:o}){let r=t.nodes[e];if(r==null)throw new Error(`Node "${e}" not found in spec`);return r.timeout==null?{...r,timeout:o}:r}async function Mc({failFast:e,nodeIds:t,page:o,spec:r,startIndex:n,timeout:s,variables:a}){let i=[],l=a;for(let c of t){let p=Bc({nodeId:c,spec:r,timeout:s}),f=await Is({failFast:e,node:p,nodeId:c,page:o,runStartTime:0,spec:r,startIndex:n+i.length,variables:l});if(i.push(...f.steps),l=f.variables,e&&qc(f.steps))break}return{steps:i,variables:l}}async function Gc({node:e,page:t,timeout:o,variables:r}){if(zc(e)){let s=await Et({node:e,page:t,timeout:o,variables:r});return{assertions:[],variables:s.variables}}return{assertions:await Hc({node:e,page:t,timeout:o,variables:r}),variables:r}}function zc(e){return["goto","click","dblclick","fill","select","hover","press","check","uncheck","clear","rightClick","handleDialog","scroll","clipboard","setPermission","waitFor","waitForUrl","waitForResponse","waitForRequest","screenshot","setViewport","wait","fail","setVariable","extractText","upload","drag","scrollIntoView","type","focus"].includes(e.type)}async function Hc({node:e,page:t,timeout:o,variables:r}){let n=e;switch(n.type){case"assertVisible":return[await De({locator:P({locator:n.locator,page:t}),timeout:o})];case"assertNotVisible":return[await We({locator:P({locator:n.locator,page:t}),timeout:o})];case"assertText":{let s=C({ref:n.expected,variables:r});return[await to({expected:s,locator:P({locator:n.locator,page:t}),operator:n.operator,timeout:o})]}case"assertUrl":{let s=C({ref:n.expected,variables:r});return[oo({expected:s,operator:n.operator,url:t.url()})]}case"assertCount":{let s=$t({ref:n.expected,variables:r});return[await ro({expected:s,locator:P({locator:n.locator,page:t}),operator:n.operator})]}case"assertValue":{let s=C({ref:n.expected,variables:r});return[await no({expected:s,locator:P({locator:n.locator,page:t}),operator:n.operator,timeout:o})]}case"assertAttribute":{let s=C({ref:n.expected,variables:r});return[await as({attribute:n.attribute,expected:s,locator:P({locator:n.locator,page:t}),operator:n.operator,timeout:o})]}case"assertEnabled":return[await is({locator:P({locator:n.locator,page:t}),timeout:o})];case"assertDisabled":return[await ls({locator:P({locator:n.locator,page:t}),timeout:o})];case"assertTitle":case"assertChecked":case"assertNotChecked":case"assertFocused":case"assertCookie":case"assertResponse":return Ts({node:n,page:t,timeout:o,variables:r})}}var Vc,Po=m(()=>{"use strict";Ot();Le();Cs();yo();ie();D();gt();Oe();Q();Vc=5e3});async function Me({baseUrl:e,browser:t,cookies:o,extraVariables:r,navigateTo:n,onStep:s,runId:a,spec:i}){let l=await t.newContext({baseURL:e});u.info("Browser context created"),o.length>0&&await l.addCookies(o);let c=await l.newPage();u.info("Page created");let p=Ue(c);n!=null&&(u.info("Navigating to: %s",n),await c.goto(n,{waitUntil:"domcontentloaded"}),u.info("Navigation complete"));function f(S){s?.(S),it({context:l,page:c,runId:a,stepIndex:S.stepIndex,stepResult:S})}let h={...Ee({defs:i.variables}),...r};u.info("Starting graph execution (entry: %s)",i.entryNode);let y=await vo({failFast:!0,onStep:f,page:c,spec:i,variables:h}),x=y.steps.filter(S=>S.status==="passed").length,R=y.steps.filter(S=>S.status==="failed").length,$={duration:y.steps.reduce((S,j)=>S+j.duration,0),failCount:R,passCount:x,runId:a,status:R>0?"failed":"passed",workflowName:""};return await lt({monitor:p,runId:a,steps:y.steps,summary:$}),await l.close(),y.steps}var xo=m(()=>{"use strict";Gt();ct();Po();D();Q()});import{z as ht}from"zod";var To,Co=m(()=>{"use strict";To=ht.object({from:ht.string().min(1).describe("Key of the source state in the states record"),to:ht.string().min(1).describe("Key of the target state in the states record"),workflow:ht.string().min(1).describe("Filename (without .json) of the workflow in .ripplo/workflows/ that executes this edge")}).describe("A directed edge between two states, executed by a workflow")});import{z as N}from"zod";var As,yt,wt,Ns,js,xe,Io=m(()=>{"use strict";As=N.object({precondition:N.string().min(1).describe("Name of the precondition to check or execute, e.g. 'auth:admin'")}).describe("Request payload sent by Ripplo to both the check and execute endpoints"),yt=N.object({satisfied:N.boolean().describe("Whether the precondition is already satisfied. If true, execution is skipped.")}).describe("Response from POST {preconditionApiUrl}/check"),wt=N.object({data:N.record(N.string(),N.string()).optional().describe("Key-value data returned by the precondition. Values are injected as variables that can be interpolated into route patterns ({{key}}) and workflow spec variable references. For example, a data:project precondition should return { projectId: 'clx...' } so the route /projects/{{projectId}}/settings resolves correctly."),error:N.string().optional().describe("Human-readable error message if success is false"),navigateTo:N.string().optional().describe("URL to navigate the browser to after this precondition executes. Use this to set the starting page for the test \u2014 e.g. an auth token URL or the page the workflow begins on. If multiple preconditions return navigateTo, only the last one is used."),success:N.boolean().describe("Whether the precondition was successfully satisfied")}).describe("Response from PUT {preconditionApiUrl}/execute. Set-Cookie headers are automatically captured and injected into the browser context. The data field provides values for route param interpolation and workflow variables."),Ns=N.object({preconditions:N.array(N.string().min(1)).describe("Names of all preconditions that were executed during this run")}).describe("Request payload sent after a run completes. Fire-and-forget \u2014 errors are logged but don't fail the run."),js=N.object({error:N.string().optional().describe("Human-readable error message if success is false"),success:N.boolean().describe("Whether teardown completed successfully")}).describe("Response from PUT {preconditionApiUrl}/teardown"),xe=N.object({depends:N.array(N.string().min(1)).optional().describe("Names of other preconditions that must be satisfied first. Resolved via topological sort; cycles are rejected at validation time."),description:N.string().min(1).describe("Human-readable description of what this precondition ensures"),returns:N.array(N.string().min(1)).optional().describe("Keys that the execute response's data field will contain. e.g. ['projectId', 'workflowId']. These are used for route param interpolation ({{projectId}}) and workflow variables. Declared here so generated types are strongly typed per precondition.")}).describe("A named precondition declared at the graph level. States reference these by name.")});import{z as bt}from"zod";var Ao,No=m(()=>{"use strict";Ao=bt.object({preconditions:bt.array(bt.string().min(1)).describe("Ordered list of precondition names to satisfy before entering this state"),route:bt.string().min(1).describe("URL pattern with {{placeholders}} for dynamic segments, e.g. '/projects/{{projectId}}/settings'")}).describe("A distinct application state \u2014 a unique combination of location, auth context, and data conditions")});import{z as pe}from"zod";var Ge,jo=m(()=>{"use strict";Co();Io();No();Ge=pe.object({edges:pe.array(To).describe("Directed edges between states, each executed by a workflow"),preconditions:pe.record(pe.string(),xe).describe("Named preconditions keyed by name (e.g. 'auth:admin', 'data:three-projects'). States reference these by name."),resetPrecondition:pe.string().optional().describe("Name of a precondition to run before every state setup as a global clean slate"),states:pe.record(pe.string(),Ao).describe("States keyed by stable ID (kebab-case)"),version:pe.literal(3).describe("Schema version, always 3")}).describe("Ripplo State Graph v3 \u2014 models application states, edges, and executable preconditions")});var $s=m(()=>{"use strict";jo()});var Te=m(()=>{"use strict";Co();jo();Io();No();$s()});import{parseSetCookie as Kc}from"set-cookie-parser";import{z as Es}from"zod";async function ze({apiUrl:e,cookies:t,executed:o}){if(o.length!==0)try{let r=await fetch(`${e}/teardown`,{body:JSON.stringify({preconditions:o}),headers:{"Content-Type":"application/json",...$o({cookies:t})},method:"PUT"});r.ok||u.error("Teardown returned %s",String(r.status))}catch{u.error("Teardown request failed")}}function Qc({preconditionNames:e,preconditions:t}){let o=[],r=new Set;function n(s){if(r.has(s))return;r.add(s);let a=t[s];a?.depends!=null&&a.depends.forEach(i=>{n(i)}),o.push(s)}return e.forEach(s=>{n(s)}),o}async function Zc({apiUrl:e,cookies:t,name:o}){let r=await fetch(`${e}/check`,{body:JSON.stringify({precondition:o}),headers:{"Content-Type":"application/json",...$o({cookies:t})},method:"POST"});if(!r.ok)return!1;let n=await r.json(),s=yt.safeParse(n);if(!s.success)throw new Error(`Check response for "${o}" has invalid shape: ${s.error.message}`);return s.data.satisfied}async function Xc({apiUrl:e,cookies:t,name:o}){let r=await fetch(`${e}/execute`,{body:JSON.stringify({precondition:o}),headers:{"Content-Type":"application/json",...$o({cookies:t})},method:"PUT"});if(!r.ok)throw new Error(`Execute for "${o}" returned ${String(r.status)}`);let n=await r.json(),s=wt.safeParse(n);if(!s.success)throw new Error(`Execute response for "${o}" has invalid shape: ${s.error.message}`);if(!s.data.success){let i=s.data.error??"no error detail";throw new Error(`Precondition "${o}" failed to execute: ${i}`)}return{cookies:ed({domain:new URL(e).hostname,res:r}),data:s.data.data??{},navigateTo:s.data.navigateTo}}function $o({cookies:e}){return e.length===0?{}:{Cookie:e.map(o=>`${o.name}=${o.value}`).join("; ")}}function ed({domain:e,res:t}){let o=t.headers.getSetCookie();return Kc(o,{decodeValues:!1}).map(n=>td({cookie:n,domain:e}))}function td({cookie:e,domain:t}){let o={domain:e.domain??t,httpOnly:e.httpOnly??!1,name:e.name,path:e.path??"/",secure:e.secure??!1,value:e.value};return e.sameSite!=null&&(o.sameSite=rd({raw:e.sameSite})),e.expires!=null?o.expires=Math.floor(e.expires.getTime()/1e3):e.maxAge!=null&&(o.expires=Math.floor(Date.now()/1e3)+e.maxAge),o}function rd({raw:e}){return od[e.toLowerCase()]??"Lax"}async function ye({baseUrl:e,project:t,workflowSlug:o}){let r={apiUrl:void 0,cookies:[],data:{},executed:[],navigateTo:void 0},n=t.stateGraph;if(n==null)return r;let s=(n.edges??[]).find(p=>p.workflowSlug===o);if(s?.sourceState==null)return r;let a=ad({baseUrl:e,preconditionApiPath:t.preconditionApiPath}),i=s.sourceState.preconditions;if(i.length===0)return{...r,apiUrl:a};if(a==null)return r;let l=nd.safeParse(n.preconditions);if(!l.success)return{...r,apiUrl:a};let c=await sd({apiUrl:a,preconditionNames:i,preconditions:l.data});return{apiUrl:a,cookies:c.cookies,data:c.data,executed:c.executed,navigateTo:c.navigateTo}}async function sd({apiUrl:e,preconditionNames:t,preconditions:o}){let r=Qc({preconditionNames:t,preconditions:o}),n=[],s={},a=[],i,l=Promise.resolve();return r.forEach(c=>{l=l.then(async()=>{if(await Zc({apiUrl:e,cookies:n,name:c}))return;let f=await Xc({apiUrl:e,cookies:n,name:c});n.push(...f.cookies),Object.entries(f.data).forEach(([h,y])=>{s[h]=y}),a.push(c),f.navigateTo!=null&&(i=f.navigateTo)})}),await l,{cookies:n,data:s,executed:a,navigateTo:i}}function ad({baseUrl:e,preconditionApiPath:t}){if(t.length!==0)return t.startsWith("http://")||t.startsWith("https://")?t:`${e}${t}`}var od,nd,Eo=m(()=>{"use strict";Te();Te();D();od={lax:"Lax",none:"None",strict:"Strict"};nd=Es.record(Es.string(),xe)});import{graphql as Oo}from"gql.tada";async function He({agentProfileId:e,config:t,runId:o}){let r=await T({config:t,document:ld,variables:{agentProfileId:e??null,platform:"chromium",runId:o}});if(r.startRun==null)throw new Error("Failed to start run");let n=r.startRun.id,s=Promise.resolve();function a(l){s=s.then(()=>id({config:t,runResultId:n,steps:[l]})).catch(c=>{let p=c instanceof Error?c.message:"Unknown error";u.error("Failed to submit step %d: %s",l.stepIndex,p)})}async function i({statusOverride:l,steps:c,summary:p}){await s;let f=c.filter(R=>R.status==="passed").length,h=c.filter(R=>R.status==="failed").length,y=c.reduce((R,$)=>R+$.duration,0),x=l??(h>0?"failed":"passed");await T({config:t,document:dd,variables:{duration:y,failCount:h,passCount:f,runResultId:n,status:x,summary:p??null,warnCount:0}})}return{complete:i,enqueueStep:a,runResultId:n}}async function id({config:e,runResultId:t,steps:o}){let r=o.map(n=>({annotations:n.annotations.map(s=>({height:s.height,label:s.label,type:s.type,width:s.width,x:s.x,y:s.y})),assertions:n.assertions.map(s=>({description:s.description,detail:s.detail,status:s.status})),detail:n.detail,duration:n.duration,nodeType:n.nodeType,screenshotBase64:n.screenshotBase64,snapshotTimestamp:n.snapshotTimestamp,status:n.status,stepIndex:n.stepIndex,title:n.title,url:n.url,viewportHeight:n.viewportHeight,viewportWidth:n.viewportWidth}));await T({config:e,document:cd,variables:{runResultId:t,steps:r}})}var ld,cd,dd,Uo=m(()=>{"use strict";_e();D();ld=Oo(`
92
+ `)});async function vr({baseUrl:e}){try{await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(nc)})}catch(t){let r=t instanceof Error?t.message:String(t);throw m.debug("Base URL reachability check failed: %s",r),new Error([`Could not reach your dev server at ${e}.`,"","Troubleshooting:",` 1. Make sure your app is running at ${e}`," 2. Check the `baseUrl` in `.ripplo/settings.json` \u2014 is the port correct?"," 3. If your app runs on a different port, update `baseUrl` in `.ripplo/settings.json`"].join(`
93
+ `))}}var nc,Rr=y(()=>{"use strict";H();nc=5e3});async function Pr({condition:e,page:t,timeout:r,variables:o}){switch(e.type){case"elementVisible":return(await He({locator:T({locator:e.locator,page:t}),timeout:r})).status==="passed";case"elementNotVisible":return(await Je({locator:T({locator:e.locator,page:t}),timeout:r})).status==="passed";case"urlMatch":{let n=E({ref:e.expected,variables:o});return ae({actual:t.url(),expected:n,label:"URL",operator:e.operator}).status==="passed"}case"textMatch":{let s=await T({locator:e.locator,page:t}).textContent({timeout:r}),a=E({ref:e.expected,variables:o});return ae({actual:s??"",expected:a,label:"Text",operator:e.operator}).status==="passed"}case"variableCompare":{let n=o[e.variable];if(n==null)throw new Error(`Variable "${e.variable}" is not defined`);let s=typeof n=="number"?n:Number(n),a=ke({ref:e.expected,variables:o}),i=typeof a=="number"?a:Number(a);return Rt({actual:s,expected:i,label:e.variable,operator:e.operator}).status==="passed"}}}var xr=y(()=>{"use strict";Ke();me();se()});import Te from"fs";import Cr from"path";import{z as pe}from"zod";function _s(e){if(!Te.existsSync(e))return null;let t=Te.readFileSync(e,"utf8");return JSON.parse(t)}function M(){let e=_s(Ws),t=_s(Ls);if(e==null||t==null)return null;let r=ic.safeParse({...e,...t});return r.success?r.data:null}function ie(e){Te.existsSync(Pt)||Te.mkdirSync(Pt,{recursive:!0});let{ripploServerUrl:t,token:r,webhookSecret:o,...n}=e;Te.writeFileSync(Ws,JSON.stringify(n,null,2)+`
94
+ `),Te.writeFileSync(Ls,JSON.stringify({ripploServerUrl:t,token:r,webhookSecret:o},null,2)+`
95
+ `)}var sc,ac,ic,Pt,Ws,Ls,qs=y(()=>{"use strict";sc=pe.object({baseUrl:pe.string().optional(),cloudBaseUrl:pe.string(),preconditionApiPath:pe.string().optional(),projectId:pe.string()}),ac=pe.object({ripploServerUrl:pe.string(),token:pe.string(),webhookSecret:pe.string()}),ic=sc.extend(ac.shape),Pt=Cr.join(process.cwd(),".ripplo"),Ws=Cr.join(Pt,"settings.json"),Ls=Cr.join(Pt,"settings.local.json")});async function Tr({executeSequence:e,failFast:t,node:r,page:o,spec:n,startIndex:s,timeout:a,variables:i}){let c=await Pr({condition:r.condition,page:o,timeout:a,variables:i})?r.consequent:r.alternate??[];return c.length===0?{steps:[],variables:i}:e({failFast:t,nodeIds:c,page:o,spec:n,startIndex:s,timeout:a,variables:i})}async function Ir({executeSequence:e,failFast:t,node:r,page:o,spec:n,startIndex:s,timeout:a,variables:i}){let l=[],c=i;for(let p=0;p<r.times;p++){r.iteratorVar!=null&&(c=de({name:r.iteratorVar,store:c,value:p}));let f=await e({failFast:t,nodeIds:r.body,page:o,spec:n,startIndex:s+l.length,timeout:a,variables:c});if(l.push(...f.steps),c=f.variables,t&&f.steps.some(u=>u.status==="failed"))break}return{steps:l,variables:c}}async function Ar({executeSequence:e,failFast:t,node:r,page:o,spec:n,startIndex:s,timeout:a,variables:i}){let l=cc({collection:r.collection,variables:i}),c=[],p=i;for(let f of l){p=de({name:r.iteratorVar,store:p,value:lc(f)});let u=await e({failFast:t,nodeIds:r.body,page:o,spec:n,startIndex:s+c.length,timeout:a,variables:p});if(c.push(...u.steps),p=u.variables,t&&u.steps.some(h=>h.status==="failed"))break}return{steps:c,variables:p}}function lc(e){return typeof e=="object"&&e!=null?JSON.stringify(e):e==null?"":String(e)}function cc({collection:e,variables:t}){if(Array.isArray(e))return e;let r=t[e.name];if(r==null)throw new Error(`Variable "${e.name}" is not defined`);return dc(r)}function dc(e){if(typeof e!="string")return[e];try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}async function Nr({executeSequence:e,failFast:t,node:r,page:o,spec:n,startIndex:s,timeout:a,variables:i}){let l=await Promise.all(r.branches.map(f=>e({failFast:t,nodeIds:f,page:o,spec:n,startIndex:s,timeout:a,variables:i}))),c=l.flatMap(f=>f.steps),p=uc({base:i,results:l});return{steps:c,variables:p}}function uc({base:e,results:t}){let r=e;return t.forEach(o=>{r={...r,...o.variables}}),r}async function jr({executeSequence:e,failFast:t,node:r,page:o,spec:n,startIndex:s,timeout:a,variables:i}){let l=[],c=i;try{let p=await e({failFast:t,nodeIds:r.body,page:o,spec:n,startIndex:s,timeout:a,variables:c});if(l.push(...p.steps),c=p.variables,p.steps.some(u=>u.status==="failed")&&r.catch!=null){let u=await e({failFast:t,nodeIds:r.catch,page:o,spec:n,startIndex:s+l.length,timeout:a,variables:c});l.push(...u.steps),c=u.variables}}catch{if(r.catch!=null){let p=await e({failFast:t,nodeIds:r.catch,page:o,spec:n,startIndex:s+l.length,timeout:a,variables:c});l.push(...p.steps),c=p.variables}}finally{if(r.finally!=null){let p=await e({failFast:t,nodeIds:r.finally,page:o,spec:n,startIndex:s+l.length,timeout:a,variables:c});l.push(...p.steps),c=p.variables}}return{steps:l,variables:c}}async function $r({executeSequence:e,failFast:t,node:r,page:o,spec:n,startIndex:s,timeout:a,variables:i}){return e({failFast:t,nodeIds:r.nodes,page:o,spec:n,startIndex:s,timeout:a,variables:i})}var Er=y(()=>{"use strict";xr();se()});import{z as O}from"zod";var pc,fc,mc,hc,gc,yc,wc,x,xt=y(()=>{"use strict";pc=O.object({by:O.literal("css"),value:O.string().min(1)}),fc=O.object({by:O.literal("testId"),value:O.string().min(1)}),mc=O.object({by:O.literal("role"),exact:O.boolean().optional(),name:O.string().optional(),role:O.string().min(1)}),hc=O.object({by:O.literal("text"),exact:O.boolean().optional(),value:O.string().min(1)}),gc=O.object({by:O.literal("label"),exact:O.boolean().optional(),value:O.string().min(1)}),yc=O.object({by:O.literal("placeholder"),value:O.string().min(1)}),wc=O.object({by:O.literal("altText"),value:O.string().min(1)}),x=O.discriminatedUnion("by",[pc,fc,mc,hc,gc,yc,wc])});import{z as Bs}from"zod";var z,ge,Ct=y(()=>{"use strict";z=Bs.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),ge=Bs.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"])});import{z as L}from"zod";var bc,Or,ve,U,Ie,Tt=y(()=>{"use strict";bc=L.object({type:L.literal("static"),value:L.union([L.string(),L.number(),L.boolean()])}),Or=L.object({name:L.string().min(1),type:L.literal("variable")}),ve=L.discriminatedUnion("type",[bc,Or]),U=L.discriminatedUnion("type",[L.object({type:L.literal("static"),value:L.string()}),Or]),Ie=L.discriminatedUnion("type",[L.object({type:L.literal("static"),value:L.number().int().nonnegative()}),Or])});import{z as ee}from"zod";var Ae,Ur=y(()=>{"use strict";xt();Ct();Tt();Ae=ee.discriminatedUnion("type",[ee.object({locator:x,type:ee.literal("elementVisible")}),ee.object({locator:x,type:ee.literal("elementNotVisible")}),ee.object({expected:U,operator:z,type:ee.literal("urlMatch")}),ee.object({expected:U,locator:x,operator:z,type:ee.literal("textMatch")}),ee.object({expected:ve,operator:ge,type:ee.literal("variableCompare"),variable:ee.string().min(1)})])});import{z as Y}from"zod";var Ze,Fr=y(()=>{"use strict";Ze=Y.discriminatedUnion("type",[Y.object({default:Y.string().optional(),type:Y.literal("string")}),Y.object({default:Y.number().optional(),type:Y.literal("number")}),Y.object({default:Y.boolean().optional(),type:Y.literal("boolean")}),Y.object({key:Y.string().min(1),type:Y.literal("env")})])});import{z as d}from"zod";var Sc,fe,R,kc,vc,Rc,Pc,xc,Cc,Tc,Ic,Ac,Nc,jc,$c,Ec,Oc,Uc,Fc,Dc,Vc,_c,Wc,Lc,qc,Bc,Mc,zc,Gc,Hc,Jc,Kc,Yc,Qc,Zc,Xc,ed,td,rd,od,nd,sd,ad,id,ld,cd,dd,ud,pd,fd,md,hd,gd,yd,Dr,Ms,Ne,Vr=y(()=>{"use strict";Ur();xt();Ct();Tt();Fr();Ur();xt();Ct();Tt();Fr();Sc=d.string().min(1),fe=d.array(Sc).min(1),R={comment:d.string().optional(),id:d.string().min(1),label:d.string().optional(),next:d.string().optional(),timeout:d.number().int().positive().optional()},kc=d.object({...R,type:d.literal("goto"),url:U}),vc=d.object({...R,locator:x,type:d.literal("click")}),Rc=d.object({...R,locator:x,type:d.literal("fill"),value:U}),Pc=d.object({...R,locator:x,type:d.literal("select"),value:U}),xc=d.object({...R,locator:x,type:d.literal("hover")}),Cc=d.object({...R,key:d.string().min(1),locator:x.optional(),type:d.literal("press")}),Tc=d.object({...R,locator:x,type:d.literal("check")}),Ic=d.object({...R,locator:x,type:d.literal("uncheck")}),Ac=d.object({...R,type:d.literal("screenshot")}),Nc=d.object({...R,height:d.number().int().positive(),type:d.literal("setViewport"),width:d.number().int().positive()}),jc=d.object({...R,duration:d.number().int().positive(),type:d.literal("wait")}),$c=d.object({...R,message:d.string().min(1),type:d.literal("fail")}),Ec=d.object({...R,type:d.literal("setVariable"),value:ve,variable:d.string().min(1)}),Oc=d.object({...R,locator:x,type:d.literal("extractText"),variable:d.string().min(1)}),Uc=d.object({...R,files:d.array(d.string()).min(1),locator:x,type:d.literal("upload")}),Fc=d.object({...R,locator:x,type:d.literal("dblclick")}),Dc=d.object({...R,source:x,target:x,type:d.literal("drag")}),Vc=d.object({...R,locator:x,type:d.literal("scrollIntoView")}),_c=d.object({...R,locator:x,type:d.literal("type"),value:U}),Wc=d.object({...R,locator:x,type:d.literal("focus")}),Lc=d.object({...R,locator:x,type:d.literal("clear")}),qc=d.object({...R,locator:x,type:d.literal("rightClick")}),Bc=d.object({...R,action:d.enum(["accept","dismiss"]),promptText:d.string().optional(),type:d.literal("handleDialog")}),Mc=d.object({...R,locator:x.optional(),type:d.literal("scroll"),x:d.number().int().optional(),y:d.number().int().optional()}),zc=d.object({...R,action:d.enum(["read","write"]),type:d.literal("clipboard"),value:U.optional(),variable:d.string().min(1).optional()}),Gc=d.object({...R,permission:d.string().min(1),state:d.enum(["granted","prompt"]),type:d.literal("setPermission")}),Hc=d.object({...R,locator:x,state:d.enum(["visible","hidden","attached","detached"]).optional(),type:d.literal("waitFor")}),Jc=d.object({...R,expected:U,operator:z,type:d.literal("waitForUrl")}),Kc=d.object({...R,type:d.literal("waitForResponse"),urlPattern:U}),Yc=d.object({...R,type:d.literal("waitForRequest"),urlPattern:U}),Qc=d.object({...R,locator:x,type:d.literal("assertVisible")}),Zc=d.object({...R,locator:x,type:d.literal("assertNotVisible")}),Xc=d.object({...R,expected:U,locator:x,operator:z,type:d.literal("assertText")}),ed=d.object({...R,expected:U,operator:z,type:d.literal("assertUrl")}),td=d.object({...R,expected:Ie,locator:x,operator:ge,type:d.literal("assertCount")}),rd=d.object({...R,expected:U,locator:x,operator:z,type:d.literal("assertValue")}),od=d.object({...R,attribute:d.string().min(1),expected:U,locator:x,operator:z,type:d.literal("assertAttribute")}),nd=d.object({...R,locator:x,type:d.literal("assertEnabled")}),sd=d.object({...R,locator:x,type:d.literal("assertDisabled")}),ad=d.object({...R,expected:U,operator:z,type:d.literal("assertTitle")}),id=d.object({...R,locator:x,type:d.literal("assertChecked")}),ld=d.object({...R,locator:x,type:d.literal("assertNotChecked")}),cd=d.object({...R,locator:x,type:d.literal("assertFocused")}),dd=d.object({...R,httpOnly:d.boolean().optional(),name:U,operator:z.optional(),sameSite:d.enum(["Strict","Lax","None"]).optional(),secure:d.boolean().optional(),type:d.literal("assertCookie"),value:U.optional()}),ud=d.object({...R,bodyContains:U.optional(),headerContains:d.object({name:d.string().min(1),value:U}).optional(),status:d.number().int().positive().optional(),type:d.literal("assertResponse"),urlPattern:U}),pd=d.object({...R,alternate:fe.optional(),condition:Ae,consequent:fe,type:d.literal("if")}),fd=d.object({...R,body:fe,iteratorVar:d.string().min(1).optional(),times:d.number().int().positive(),type:d.literal("loop")}),md=d.object({...R,body:fe,collection:d.union([d.array(d.record(d.string(),d.unknown())).min(1),d.object({name:d.string().min(1),type:d.literal("variable")})]),iteratorVar:d.string().min(1),type:d.literal("forEach")}),hd=d.object({...R,branches:d.array(fe).min(2),type:d.literal("parallel")}),gd=d.object({...R,body:fe,catch:fe.optional(),finally:fe.optional(),type:d.literal("try")}).refine(e=>e.catch!=null||e.finally!=null,{message:"try node must have at least one of 'catch' or 'finally'"}),yd=d.object({...R,nodes:fe,type:d.literal("group")}),Dr=d.discriminatedUnion("type",[kc,vc,Rc,Pc,xc,Cc,Tc,Ic,Hc,Jc,Kc,Yc,Qc,Zc,Xc,ed,td,rd,od,nd,sd,Ac,Nc,jc,$c,Ec,Oc,Uc,Fc,Dc,Vc,_c,Wc,Lc,qc,Bc,Mc,zc,Gc,ad,id,ld,cd,dd,ud,pd,fd,md,hd,yd]),Ms=d.union([Dr,gd]),Ne=d.object({entryNode:d.string().min(1),nodes:d.record(d.string(),Ms),variables:d.record(d.string(),Ze).optional(),version:d.literal(2)})});function ye(e){let t=Ne.safeParse(e);return t.success?{data:t.data,success:!0}:{errors:t.error.issues.map(r=>({message:r.message,path:r.path.join(".")})),success:!1}}var zs=y(()=>{"use strict";Vr()});var Re=y(()=>{"use strict";Vr();zs()});async function Gs({node:e,page:t,timeout:r,variables:o}){switch(e.type){case"assertTitle":{let n=E({ref:e.expected,variables:o});return[As({expected:n,operator:e.operator,title:await t.title()})]}case"assertChecked":return[await Ns({locator:T({locator:e.locator,page:t}),timeout:r})];case"assertNotChecked":return[await js({locator:T({locator:e.locator,page:t}),timeout:r})];case"assertFocused":return[await $s({locator:T({locator:e.locator,page:t}),timeout:r})];case"assertCookie":return wd({node:e,page:t,variables:o});case"assertResponse":return bd({node:e,page:t,timeout:r,variables:o})}}async function wd({node:e,page:t,variables:r}){let o=E({ref:e.name,variables:r}),n=e.value==null?void 0:E({ref:e.value,variables:r}),s=await t.context().cookies();return[Es({cookies:s,expected:{httpOnly:e.httpOnly,name:o,operator:e.operator,sameSite:e.sameSite,secure:e.secure,value:n}})]}async function bd({node:e,page:t,timeout:r,variables:o}){let n=E({ref:e.urlPattern,variables:o}),s=e.bodyContains==null?void 0:E({ref:e.bodyContains,variables:o}),a=e.headerContains==null?void 0:{name:e.headerContains.name,value:E({ref:e.headerContains.value,variables:o})};return Os({bodyContains:s,headerContains:a,page:t,status:e.status,timeout:r,urlPattern:n})}var Hs=y(()=>{"use strict";Ke();me();se()});async function K({fn:e,label:t}){let r=performance.now(),o=await e();return m.info("%s: %dms",t,Math.round(performance.now()-r)),o}var It=y(()=>{"use strict";H()});async function _r({failFast:e,onStep:t,page:r,spec:o,variables:n}){let s=performance.now();return vd({currentId:o.entryNode,failFast:e,onStep:t,page:r,runStartTime:s,spec:o,startIndex:0,variables:n})}function kd({onStep:e,steps:t,target:r}){t.forEach(o=>{r.push(o),e?.(o)})}async function vd({currentId:e,failFast:t,onStep:r,page:o,runStartTime:n,spec:s,startIndex:a,variables:i}){let l=[],c=i,p=e;for(;p!=null;){let f=s.nodes[p];if(f==null)throw new Error(`Node "${p}" not found in spec`);let u=p,h=f.label??`${f.type} (${p})`;m.info("Executing node: %s [%s]",h,f.type);let g=await Js({failFast:t,node:f,nodeId:u,page:o,runStartTime:n,spec:s,startIndex:a+l.length,variables:c});if(kd({onStep:r,steps:g.steps,target:l}),c=g.variables,t&&g.steps.some(b=>b.status==="failed"))break;p=f.next}return{steps:l,variables:c}}async function Js({failFast:e,node:t,nodeId:r,page:o,runStartTime:n,spec:s,startIndex:a,variables:i}){let l=performance.now(),c=t.label??`${t.type} (${t.id})`,p=t.timeout??Sd;if(Rd(t))return Pd({failFast:e,node:t,page:o,spec:s,startIndex:a,timeout:p,variables:i});let f=ht({node:t,page:o});try{let u=await Id({node:t,page:o,timeout:p,variables:i}),h=Math.round(performance.now()-l),g=u.assertions.some(k=>k.status==="failed"),b=await K({label:`Snapshot [${c}]`,fn:()=>he({page:o,runStartTime:n,targets:f})});return{steps:[{annotations:b.annotations,assertions:u.assertions,detail:void 0,duration:h,nodeId:r,nodeType:t.type,screenshotBase64:b.screenshotBase64,snapshotTimestamp:b.snapshotTimestamp,status:g?"failed":"passed",stepIndex:a,title:c,url:b.url,viewportHeight:b.viewportHeight,viewportWidth:b.viewportWidth}],variables:u.variables}}catch(u){let h=Math.round(performance.now()-l),g=u instanceof Error?u.message:String(u),b=await K({label:`Snapshot [${c}] (error)`,fn:()=>he({page:o,runStartTime:n,targets:f})});return{steps:[{annotations:b.annotations,assertions:[],detail:g,duration:h,nodeId:r,nodeType:t.type,screenshotBase64:b.screenshotBase64,snapshotTimestamp:b.snapshotTimestamp,status:"failed",stepIndex:a,title:c,url:b.url,viewportHeight:b.viewportHeight,viewportWidth:b.viewportWidth}],variables:i}}}function Rd(e){return["if","loop","forEach","parallel","try","group"].includes(e.type)}async function Pd({failFast:e,node:t,page:r,spec:o,startIndex:n,timeout:s,variables:a}){let i={executeSequence:Td,failFast:e,page:r,spec:o,startIndex:n,timeout:s,variables:a};switch(t.type){case"if":return Tr({...i,node:t});case"loop":return Ir({...i,node:t});case"forEach":return Ar({...i,node:t});case"parallel":return Nr({...i,node:t});case"try":return jr({...i,node:t});case"group":return $r({...i,node:t})}}function xd(e){return e.some(t=>t.status==="failed")}function Cd({nodeId:e,spec:t,timeout:r}){let o=t.nodes[e];if(o==null)throw new Error(`Node "${e}" not found in spec`);return o.timeout==null?{...o,timeout:r}:o}async function Td({failFast:e,nodeIds:t,page:r,spec:o,startIndex:n,timeout:s,variables:a}){let i=[],l=a;for(let c of t){let p=Cd({nodeId:c,spec:o,timeout:s}),f=await Js({failFast:e,node:p,nodeId:c,page:r,runStartTime:0,spec:o,startIndex:n+i.length,variables:l});if(i.push(...f.steps),l=f.variables,e&&xd(f.steps))break}return{steps:i,variables:l}}async function Id({node:e,page:t,timeout:r,variables:o}){if(Ad(e)){let s=await Yt({node:e,page:t,timeout:r,variables:o});return{assertions:[],variables:s.variables}}return{assertions:await Nd({node:e,page:t,timeout:r,variables:o}),variables:o}}function Ad(e){return["goto","click","dblclick","fill","select","hover","press","check","uncheck","clear","rightClick","handleDialog","scroll","clipboard","setPermission","waitFor","waitForUrl","waitForResponse","waitForRequest","screenshot","setViewport","wait","fail","setVariable","extractText","upload","drag","scrollIntoView","type","focus"].includes(e.type)}async function Nd({node:e,page:t,timeout:r,variables:o}){let n=e;switch(n.type){case"assertVisible":return[await He({locator:T({locator:n.locator,page:t}),timeout:r})];case"assertNotVisible":return[await Je({locator:T({locator:n.locator,page:t}),timeout:r})];case"assertText":{let s=E({ref:n.expected,variables:o});return[await wr({expected:s,locator:T({locator:n.locator,page:t}),operator:n.operator,timeout:r})]}case"assertUrl":{let s=E({ref:n.expected,variables:o});return[br({expected:s,operator:n.operator,url:t.url()})]}case"assertCount":{let s=Kt({ref:n.expected,variables:o});return[await Sr({expected:s,locator:T({locator:n.locator,page:t}),operator:n.operator})]}case"assertValue":{let s=E({ref:n.expected,variables:o});return[await kr({expected:s,locator:T({locator:n.locator,page:t}),operator:n.operator,timeout:r})]}case"assertAttribute":{let s=E({ref:n.expected,variables:o});return[await Cs({attribute:n.attribute,expected:s,locator:T({locator:n.locator,page:t}),operator:n.operator,timeout:r})]}case"assertEnabled":return[await Ts({locator:T({locator:n.locator,page:t}),timeout:r})];case"assertDisabled":return[await Is({locator:T({locator:n.locator,page:t}),timeout:r})];case"assertTitle":case"assertChecked":case"assertNotChecked":case"assertFocused":case"assertCookie":case"assertResponse":return Gs({node:n,page:t,timeout:r,variables:o})}}var Sd,Wr=y(()=>{"use strict";Qt();Ke();Hs();Er();me();H();It();Be();se();Sd=5e3});async function Xe({baseUrl:e,browser:t,cookies:r,extraVariables:o,navigateTo:n,onStep:s,runId:a,spec:i}){let l=await t.newContext({baseURL:e});m.info("Browser context created"),r.length>0&&await l.addCookies(r);let c=await l.newPage();m.info("Page created");let p=Me(c);n!=null&&(m.info("Navigating to: %s",n),await c.goto(n,{waitUntil:"domcontentloaded"}),m.info("Navigation complete"));function f(k){s?.(k),St({context:l,page:c,runId:a,stepIndex:k.stepIndex,stepResult:k})}let u={...qe({defs:i.variables}),...o};m.info("Starting graph execution (entry: %s)",i.entryNode);let h=await _r({failFast:!0,onStep:f,page:c,spec:i,variables:u}),g=h.steps.filter(k=>k.status==="passed").length,b=h.steps.filter(k=>k.status==="failed").length,P={duration:h.steps.reduce((k,S)=>k+S.duration,0),failCount:b,passCount:g,runId:a,status:b>0?"failed":"passed",workflowName:""};return await kt({monitor:p,runId:a,steps:h.steps,summary:P}),await l.close(),h.steps}var Lr=y(()=>{"use strict";lr();vt();Wr();H();se()});import{z as At}from"zod";var qr,Br=y(()=>{"use strict";qr=At.object({from:At.string().min(1).describe("Key of the source state in the states record"),to:At.string().min(1).describe("Key of the target state in the states record"),workflow:At.string().min(1).describe("Filename (without .json) of the workflow in .ripplo/workflows/ that executes this edge")}).describe("A directed edge between two states, executed by a workflow")});import{z as F}from"zod";var Ks,Nt,jt,Ys,Qs,je,Mr=y(()=>{"use strict";Ks=F.object({precondition:F.string().min(1).describe("Name of the precondition to check or execute, e.g. 'auth:admin'")}).describe("Request payload sent by Ripplo to both the check and execute endpoints"),Nt=F.object({satisfied:F.boolean().describe("Whether the precondition is already satisfied. If true, execution is skipped.")}).describe("Response from POST {preconditionApiUrl}/check"),jt=F.object({data:F.record(F.string(),F.string()).optional().describe("Key-value data returned by the precondition. Values are injected as variables that can be interpolated into route patterns ({{key}}) and workflow spec variable references. For example, a data:project precondition should return { projectId: 'clx...' } so the route /projects/{{projectId}}/settings resolves correctly."),error:F.string().optional().describe("Human-readable error message if success is false"),navigateTo:F.string().optional().describe("URL to navigate the browser to after this precondition executes. Use this to set the starting page for the test \u2014 e.g. an auth token URL or the page the workflow begins on. If multiple preconditions return navigateTo, only the last one is used."),success:F.boolean().describe("Whether the precondition was successfully satisfied")}).describe("Response from PUT {preconditionApiUrl}/execute. Set-Cookie headers are automatically captured and injected into the browser context. The data field provides values for route param interpolation and workflow variables."),Ys=F.object({preconditions:F.array(F.string().min(1)).describe("Names of all preconditions that were executed during this run")}).describe("Request payload sent after a run completes. Fire-and-forget \u2014 errors are logged but don't fail the run."),Qs=F.object({error:F.string().optional().describe("Human-readable error message if success is false"),success:F.boolean().describe("Whether teardown completed successfully")}).describe("Response from PUT {preconditionApiUrl}/teardown"),je=F.object({depends:F.array(F.string().min(1)).optional().describe("Names of other preconditions that must be satisfied first. Resolved via topological sort; cycles are rejected at validation time."),description:F.string().min(1).describe("Human-readable description of what this precondition ensures"),returns:F.array(F.string().min(1)).optional().describe("Keys that the execute response's data field will contain. e.g. ['projectId', 'workflowId']. These are used for route param interpolation ({{projectId}}) and workflow variables. Declared here so generated types are strongly typed per precondition.")}).describe("A named precondition declared at the graph level. States reference these by name.")});import{z as $t}from"zod";var zr,Gr=y(()=>{"use strict";zr=$t.object({preconditions:$t.array($t.string().min(1)).describe("Ordered list of precondition names to satisfy before entering this state"),route:$t.string().min(1).describe("URL pattern with {{placeholders}} for dynamic segments, e.g. '/projects/{{projectId}}/settings'")}).describe("A distinct application state \u2014 a unique combination of location, auth context, and data conditions")});import{z as we}from"zod";var et,Hr=y(()=>{"use strict";Br();Mr();Gr();et=we.object({edges:we.array(qr).describe("Directed edges between states, each executed by a workflow"),preconditions:we.record(we.string(),je).describe("Named preconditions keyed by name (e.g. 'auth:admin', 'data:three-projects'). States reference these by name."),resetPrecondition:we.string().optional().describe("Name of a precondition to run before every state setup as a global clean slate"),states:we.record(we.string(),zr).describe("States keyed by stable ID (kebab-case)"),version:we.literal(3).describe("Schema version, always 3")}).describe("Ripplo State Graph v3 \u2014 models application states, edges, and executable preconditions")});var Zs=y(()=>{"use strict";Hr()});var $e=y(()=>{"use strict";Br();Hr();Mr();Gr();Zs()});var ea=mt(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.timingSafeEqual=void 0;function Xs(e,t=""){if(!e)throw new Error(t)}function Ed(e,t){if(e.byteLength!==t.byteLength)return!1;e instanceof DataView||(e=new DataView(ArrayBuffer.isView(e)?e.buffer:e)),t instanceof DataView||(t=new DataView(ArrayBuffer.isView(t)?t.buffer:t)),Xs(e instanceof DataView),Xs(t instanceof DataView);let r=e.byteLength,o=0,n=-1;for(;++n<r;)o|=e.getUint8(n)^t.getUint8(n);return o===0}Et.timingSafeEqual=Ed});var oa=mt(Q=>{"use strict";var Od=Q&&Q.__extends||(function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(o,n){o.__proto__=n}||function(o,n){for(var s in n)n.hasOwnProperty(s)&&(o[s]=n[s])},e(t,r)};return function(t,r){e(t,r);function o(){this.constructor=t}t.prototype=r===null?Object.create(r):(o.prototype=r.prototype,new o)}})();Object.defineProperty(Q,"__esModule",{value:!0});var D=256,Jr=(function(){function e(t){t===void 0&&(t="="),this._paddingCharacter=t}return e.prototype.encodedLength=function(t){return this._paddingCharacter?(t+2)/3*4|0:(t*8+5)/6|0},e.prototype.encode=function(t){for(var r="",o=0;o<t.length-2;o+=3){var n=t[o]<<16|t[o+1]<<8|t[o+2];r+=this._encodeByte(n>>>18&63),r+=this._encodeByte(n>>>12&63),r+=this._encodeByte(n>>>6&63),r+=this._encodeByte(n>>>0&63)}var s=t.length-o;if(s>0){var n=t[o]<<16|(s===2?t[o+1]<<8:0);r+=this._encodeByte(n>>>18&63),r+=this._encodeByte(n>>>12&63),s===2?r+=this._encodeByte(n>>>6&63):r+=this._paddingCharacter||"",r+=this._paddingCharacter||""}return r},e.prototype.maxDecodedLength=function(t){return this._paddingCharacter?t/4*3|0:(t*6+7)/8|0},e.prototype.decodedLength=function(t){return this.maxDecodedLength(t.length-this._getPaddingLength(t))},e.prototype.decode=function(t){if(t.length===0)return new Uint8Array(0);for(var r=this._getPaddingLength(t),o=t.length-r,n=new Uint8Array(this.maxDecodedLength(o)),s=0,a=0,i=0,l=0,c=0,p=0,f=0;a<o-4;a+=4)l=this._decodeChar(t.charCodeAt(a+0)),c=this._decodeChar(t.charCodeAt(a+1)),p=this._decodeChar(t.charCodeAt(a+2)),f=this._decodeChar(t.charCodeAt(a+3)),n[s++]=l<<2|c>>>4,n[s++]=c<<4|p>>>2,n[s++]=p<<6|f,i|=l&D,i|=c&D,i|=p&D,i|=f&D;if(a<o-1&&(l=this._decodeChar(t.charCodeAt(a)),c=this._decodeChar(t.charCodeAt(a+1)),n[s++]=l<<2|c>>>4,i|=l&D,i|=c&D),a<o-2&&(p=this._decodeChar(t.charCodeAt(a+2)),n[s++]=c<<4|p>>>2,i|=p&D),a<o-3&&(f=this._decodeChar(t.charCodeAt(a+3)),n[s++]=p<<6|f,i|=f&D),i!==0)throw new Error("Base64Coder: incorrect characters for decoding");return n},e.prototype._encodeByte=function(t){var r=t;return r+=65,r+=25-t>>>8&6,r+=51-t>>>8&-75,r+=61-t>>>8&-15,r+=62-t>>>8&3,String.fromCharCode(r)},e.prototype._decodeChar=function(t){var r=D;return r+=(42-t&t-44)>>>8&-D+t-43+62,r+=(46-t&t-48)>>>8&-D+t-47+63,r+=(47-t&t-58)>>>8&-D+t-48+52,r+=(64-t&t-91)>>>8&-D+t-65+0,r+=(96-t&t-123)>>>8&-D+t-97+26,r},e.prototype._getPaddingLength=function(t){var r=0;if(this._paddingCharacter){for(var o=t.length-1;o>=0&&t[o]===this._paddingCharacter;o--)r++;if(t.length<4||r>2)throw new Error("Base64Coder: incorrect padding")}return r},e})();Q.Coder=Jr;var tt=new Jr;function Ud(e){return tt.encode(e)}Q.encode=Ud;function Fd(e){return tt.decode(e)}Q.decode=Fd;var ta=(function(e){Od(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype._encodeByte=function(r){var o=r;return o+=65,o+=25-r>>>8&6,o+=51-r>>>8&-75,o+=61-r>>>8&-13,o+=62-r>>>8&49,String.fromCharCode(o)},t.prototype._decodeChar=function(r){var o=D;return o+=(44-r&r-46)>>>8&-D+r-45+62,o+=(94-r&r-96)>>>8&-D+r-95+63,o+=(47-r&r-58)>>>8&-D+r-48+52,o+=(64-r&r-91)>>>8&-D+r-65+0,o+=(96-r&r-123)>>>8&-D+r-97+26,o},t})(Jr);Q.URLSafeCoder=ta;var ra=new ta;function Dd(e){return ra.encode(e)}Q.encodeURLSafe=Dd;function Vd(e){return ra.decode(e)}Q.decodeURLSafe=Vd;Q.encodedLength=function(e){return tt.encodedLength(e)};Q.maxDecodedLength=function(e){return tt.maxDecodedLength(e)};Q.decodedLength=function(e){return tt.decodedLength(e)}});var sa=mt((na,Ot)=>{"use strict";(function(e,t){var r={};t(r);var o=r.default;for(var n in r)o[n]=r[n];typeof Ot=="object"&&typeof Ot.exports=="object"?Ot.exports=o:typeof define=="function"&&define.amd?define(function(){return o}):e.sha256=o})(na,function(e){"use strict";e.__esModule=!0,e.digestLength=32,e.blockSize=64;var t=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function r(f,u,h,g,b){for(var P,k,S,N,j,I,G,A,V,_,We,Le,ft;b>=64;){for(P=u[0],k=u[1],S=u[2],N=u[3],j=u[4],I=u[5],G=u[6],A=u[7],_=0;_<16;_++)We=g+_*4,f[_]=(h[We]&255)<<24|(h[We+1]&255)<<16|(h[We+2]&255)<<8|h[We+3]&255;for(_=16;_<64;_++)V=f[_-2],Le=(V>>>17|V<<15)^(V>>>19|V<<13)^V>>>10,V=f[_-15],ft=(V>>>7|V<<25)^(V>>>18|V<<14)^V>>>3,f[_]=(Le+f[_-7]|0)+(ft+f[_-16]|0);for(_=0;_<64;_++)Le=(((j>>>6|j<<26)^(j>>>11|j<<21)^(j>>>25|j<<7))+(j&I^~j&G)|0)+(A+(t[_]+f[_]|0)|0)|0,ft=((P>>>2|P<<30)^(P>>>13|P<<19)^(P>>>22|P<<10))+(P&k^P&S^k&S)|0,A=G,G=I,I=j,j=N+Le|0,N=S,S=k,k=P,P=Le+ft|0;u[0]+=P,u[1]+=k,u[2]+=S,u[3]+=N,u[4]+=j,u[5]+=I,u[6]+=G,u[7]+=A,g+=64,b-=64}return g}var o=(function(){function f(){this.digestLength=e.digestLength,this.blockSize=e.blockSize,this.state=new Int32Array(8),this.temp=new Int32Array(64),this.buffer=new Uint8Array(128),this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this.reset()}return f.prototype.reset=function(){return this.state[0]=1779033703,this.state[1]=3144134277,this.state[2]=1013904242,this.state[3]=2773480762,this.state[4]=1359893119,this.state[5]=2600822924,this.state[6]=528734635,this.state[7]=1541459225,this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this},f.prototype.clean=function(){for(var u=0;u<this.buffer.length;u++)this.buffer[u]=0;for(var u=0;u<this.temp.length;u++)this.temp[u]=0;this.reset()},f.prototype.update=function(u,h){if(h===void 0&&(h=u.length),this.finished)throw new Error("SHA256: can't update because hash was finished.");var g=0;if(this.bytesHashed+=h,this.bufferLength>0){for(;this.bufferLength<64&&h>0;)this.buffer[this.bufferLength++]=u[g++],h--;this.bufferLength===64&&(r(this.temp,this.state,this.buffer,0,64),this.bufferLength=0)}for(h>=64&&(g=r(this.temp,this.state,u,g,h),h%=64);h>0;)this.buffer[this.bufferLength++]=u[g++],h--;return this},f.prototype.finish=function(u){if(!this.finished){var h=this.bytesHashed,g=this.bufferLength,b=h/536870912|0,P=h<<3,k=h%64<56?64:128;this.buffer[g]=128;for(var S=g+1;S<k-8;S++)this.buffer[S]=0;this.buffer[k-8]=b>>>24&255,this.buffer[k-7]=b>>>16&255,this.buffer[k-6]=b>>>8&255,this.buffer[k-5]=b>>>0&255,this.buffer[k-4]=P>>>24&255,this.buffer[k-3]=P>>>16&255,this.buffer[k-2]=P>>>8&255,this.buffer[k-1]=P>>>0&255,r(this.temp,this.state,this.buffer,0,k),this.finished=!0}for(var S=0;S<8;S++)u[S*4+0]=this.state[S]>>>24&255,u[S*4+1]=this.state[S]>>>16&255,u[S*4+2]=this.state[S]>>>8&255,u[S*4+3]=this.state[S]>>>0&255;return this},f.prototype.digest=function(){var u=new Uint8Array(this.digestLength);return this.finish(u),u},f.prototype._saveState=function(u){for(var h=0;h<this.state.length;h++)u[h]=this.state[h]},f.prototype._restoreState=function(u,h){for(var g=0;g<this.state.length;g++)this.state[g]=u[g];this.bytesHashed=h,this.finished=!1,this.bufferLength=0},f})();e.Hash=o;var n=(function(){function f(u){this.inner=new o,this.outer=new o,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;var h=new Uint8Array(this.blockSize);if(u.length>this.blockSize)new o().update(u).finish(h).clean();else for(var g=0;g<u.length;g++)h[g]=u[g];for(var g=0;g<h.length;g++)h[g]^=54;this.inner.update(h);for(var g=0;g<h.length;g++)h[g]^=106;this.outer.update(h),this.istate=new Uint32Array(8),this.ostate=new Uint32Array(8),this.inner._saveState(this.istate),this.outer._saveState(this.ostate);for(var g=0;g<h.length;g++)h[g]=0}return f.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},f.prototype.clean=function(){for(var u=0;u<this.istate.length;u++)this.ostate[u]=this.istate[u]=0;this.inner.clean(),this.outer.clean()},f.prototype.update=function(u){return this.inner.update(u),this},f.prototype.finish=function(u){return this.outer.finished?this.outer.finish(u):(this.inner.finish(u),this.outer.update(u,this.digestLength).finish(u)),this},f.prototype.digest=function(){var u=new Uint8Array(this.digestLength);return this.finish(u),u},f})();e.HMAC=n;function s(f){var u=new o().update(f),h=u.digest();return u.clean(),h}e.hash=s,e.default=s;function a(f,u){var h=new n(f).update(u),g=h.digest();return h.clean(),g}e.hmac=a;function i(f,u,h,g){var b=g[0];if(b===0)throw new Error("hkdf: cannot expand more");u.reset(),b>1&&u.update(f),h&&u.update(h),u.update(g),u.finish(f),g[0]++}var l=new Uint8Array(e.digestLength);function c(f,u,h,g){u===void 0&&(u=l),g===void 0&&(g=32);for(var b=new Uint8Array([1]),P=a(u,f),k=new n(P),S=new Uint8Array(k.digestLength),N=S.length,j=new Uint8Array(g),I=0;I<g;I++)N===S.length&&(i(S,k,h,b),N=0),j[I]=S[N++];return k.clean(),S.fill(0),b.fill(0),j}e.hkdf=c;function p(f,u,h,g){for(var b=new n(f),P=b.digestLength,k=new Uint8Array(4),S=new Uint8Array(P),N=new Uint8Array(P),j=new Uint8Array(g),I=0;I*P<g;I++){var G=I+1;k[0]=G>>>24&255,k[1]=G>>>16&255,k[2]=G>>>8&255,k[3]=G>>>0&255,b.reset(),b.update(u),b.update(k),b.finish(N);for(var A=0;A<P;A++)S[A]=N[A];for(var A=2;A<=h;A++){b.reset(),b.update(N).finish(N);for(var V=0;V<P;V++)S[V]^=N[V]}for(var A=0;A<P&&I*P+A<g;A++)j[I*P+A]=S[A]}for(var I=0;I<P;I++)S[I]=N[I]=0;for(var I=0;I<4;I++)k[I]=0;return b.clean(),j}e.pbkdf2=p})});var la=mt(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.Webhook=Ee.WebhookVerificationError=void 0;var _d=ea(),aa=oa(),Wd=sa(),ia=300,Kr=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype),this.name="ExtendableError",this.stack=new Error(t).stack}},be=class e extends Kr{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype),this.name="WebhookVerificationError"}};Ee.WebhookVerificationError=be;var Ut=class e{constructor(t,r){if(!t)throw new Error("Secret can't be empty.");if(r?.format==="raw")t instanceof Uint8Array?this.key=t:this.key=Uint8Array.from(t,o=>o.charCodeAt(0));else{if(typeof t!="string")throw new Error("Expected secret to be of type string");t.startsWith(e.prefix)&&(t=t.substring(e.prefix.length)),this.key=aa.decode(t)}}verify(t,r){let o={};for(let u of Object.keys(r))o[u.toLowerCase()]=r[u];let n=o["webhook-id"],s=o["webhook-signature"],a=o["webhook-timestamp"];if(!s||!n||!a)throw new be("Missing required headers");let i=this.verifyTimestamp(a),c=this.sign(n,i,t).split(",")[1],p=s.split(" "),f=new globalThis.TextEncoder;for(let u of p){let[h,g]=u.split(",");if(h==="v1"&&(0,_d.timingSafeEqual)(f.encode(g),f.encode(c)))return JSON.parse(t.toString())}throw new be("No matching signature found")}sign(t,r,o){if(typeof o!="string")if(o.constructor.name==="Buffer")o=o.toString();else throw new Error("Expected payload to be of type string or Buffer.");let n=new TextEncoder,s=Math.floor(r.getTime()/1e3),a=n.encode(`${t}.${s}.${o}`);return`v1,${aa.encode(Wd.hmac(this.key,a))}`}verifyTimestamp(t){let r=Math.floor(Date.now()/1e3),o=parseInt(t,10);if(isNaN(o))throw new be("Invalid Signature Headers");if(r-o>ia)throw new be("Message timestamp too old");if(o>r+ia)throw new be("Message timestamp too new");return new Date(o*1e3)}};Ee.Webhook=Ut;Ut.prefix="whsec_"});import ca from"crypto";function Ft({body:e,secret:t}){let r=new da.Webhook(t),o=`msg_${ca.randomUUID()}`,n=new Date,s=r.sign(o,n,e),a=Math.floor(n.getTime()/1e3);return{"webhook-id":o,"webhook-signature":s,"webhook-timestamp":String(a)}}function rt(){return`whsec_${ca.randomBytes(24).toString("base64")}`}var da,Yr=y(()=>{"use strict";da=li(la(),1)});import{parseSetCookie as Ld}from"set-cookie-parser";import{z as ua}from"zod";async function ot({apiUrl:e,cookies:t,executed:r,webhookSecret:o}){if(r.length!==0)try{let n=JSON.stringify({preconditions:r}),s=await fetch(`${e}/teardown`,{body:n,headers:{"Content-Type":"application/json",...Qr({cookies:t}),...Ft({body:n,secret:o})},method:"PUT"});s.ok||m.error("Teardown returned %s",String(s.status))}catch{m.error("Teardown request failed")}}function qd({preconditionNames:e,preconditions:t}){let r=[],o=new Set;function n(s){if(o.has(s))return;o.add(s);let a=t[s];a?.depends!=null&&a.depends.forEach(i=>{n(i)}),r.push(s)}return e.forEach(s=>{n(s)}),r}async function Bd({apiUrl:e,cookies:t,name:r,webhookSecret:o}){let n=JSON.stringify({precondition:r}),s=await fetch(`${e}/check`,{body:n,headers:{"Content-Type":"application/json",...Qr({cookies:t}),...Ft({body:n,secret:o})},method:"POST"});if(!s.ok)return!1;let a=await s.json(),i=Nt.safeParse(a);if(!i.success)throw new Error(`Check response for "${r}" has invalid shape: ${i.error.message}`);return i.data.satisfied}async function Md({apiUrl:e,cookies:t,name:r,webhookSecret:o}){let n=JSON.stringify({precondition:r}),s=await fetch(`${e}/execute`,{body:n,headers:{"Content-Type":"application/json",...Qr({cookies:t}),...Ft({body:n,secret:o})},method:"PUT"});if(!s.ok)throw new Error(`Execute for "${r}" returned ${String(s.status)}`);let a=await s.json(),i=jt.safeParse(a);if(!i.success)throw new Error(`Execute response for "${r}" has invalid shape: ${i.error.message}`);if(!i.data.success){let c=i.data.error??"no error detail";throw new Error(`Precondition "${r}" failed to execute: ${c}`)}return{cookies:zd({domain:new URL(e).hostname,res:s}),data:i.data.data??{},navigateTo:i.data.navigateTo}}function Qr({cookies:e}){return e.length===0?{}:{Cookie:e.map(r=>`${r.name}=${r.value}`).join("; ")}}function zd({domain:e,res:t}){let r=t.headers.getSetCookie();return Ld(r,{decodeValues:!1}).map(n=>Gd({cookie:n,domain:e}))}function Gd({cookie:e,domain:t}){let r={domain:e.domain??t,httpOnly:e.httpOnly??!1,name:e.name,path:e.path??"/",secure:e.secure??!1,value:e.value};return e.sameSite!=null&&(r.sameSite=Jd({raw:e.sameSite})),e.expires!=null?r.expires=Math.floor(e.expires.getTime()/1e3):e.maxAge!=null&&(r.expires=Math.floor(Date.now()/1e3)+e.maxAge),r}function Jd({raw:e}){return Hd[e.toLowerCase()]??"Lax"}async function Pe({baseUrl:e,project:t,webhookSecret:r,workflowSlug:o}){let n={apiUrl:void 0,cookies:[],data:{},executed:[],navigateTo:void 0},s=t.stateGraph;if(s==null)return n;let a=(s.edges??[]).find(f=>f.workflowSlug===o);if(a?.sourceState==null)return n;let i=Zd({baseUrl:e,preconditionApiPath:t.preconditionApiPath}),l=a.sourceState.preconditions;if(l.length===0)return{...n,apiUrl:i};if(i==null)return n;let c=Kd.safeParse(s.preconditions);if(!c.success)return{...n,apiUrl:i};let p=await Qd({apiUrl:i,preconditionNames:l,preconditions:c.data,webhookSecret:r});return{apiUrl:i,cookies:p.cookies,data:p.data,executed:p.executed,navigateTo:p.navigateTo}}async function Yd({acc:e,apiUrl:t,name:r,webhookSecret:o}){if(await Bd({apiUrl:t,cookies:e.cookies,name:r,webhookSecret:o}))return e;let s=await Md({apiUrl:t,cookies:e.cookies,name:r,webhookSecret:o});return{cookies:[...e.cookies,...s.cookies],data:{...e.data,...s.data},executed:[...e.executed,r],navigateTo:s.navigateTo??e.navigateTo}}async function Qd({apiUrl:e,preconditionNames:t,preconditions:r,webhookSecret:o}){let n=qd({preconditionNames:t,preconditions:r}),a={cookies:[],data:{},executed:[],navigateTo:void 0};for(let i of n)a=await Yd({acc:a,apiUrl:e,name:i,webhookSecret:o});return a}function Zd({baseUrl:e,preconditionApiPath:t}){if(t.length!==0)return t.startsWith("http://")||t.startsWith("https://")?t:`${e}${t}`}var Hd,Kd,Zr=y(()=>{"use strict";$e();$e();H();Yr();Hd={lax:"Lax",none:"None",strict:"Strict"};Kd=ua.record(ua.string(),je)});import{graphql as Xr}from"gql.tada";async function nt({agentProfileId:e,config:t,runId:r}){let o=await $({config:t,document:eu,variables:{agentProfileId:e??null,platform:"chromium",runId:r}});if(o.startRun==null)throw new Error("Failed to start run");let n=o.startRun.id,s=Promise.resolve();function a(l){s=s.then(()=>Xd({config:t,runResultId:n,steps:[l]})).catch(c=>{let p=c instanceof Error?c.message:"Unknown error";m.error("Failed to submit step %d: %s",l.stepIndex,p)})}async function i({statusOverride:l,steps:c,summary:p}){await s;let f=c.filter(b=>b.status==="passed").length,u=c.filter(b=>b.status==="failed").length,h=c.reduce((b,P)=>b+P.duration,0),g=l??(u>0?"failed":"passed");await $({config:t,document:ru,variables:{duration:h,failCount:u,passCount:f,runResultId:n,status:g,summary:p??null,warnCount:0}})}return{complete:i,enqueueStep:a,runResultId:n}}async function Xd({config:e,runResultId:t,steps:r}){let o=r.map(n=>({annotations:n.annotations.map(s=>({height:s.height,label:s.label,type:s.type,width:s.width,x:s.x,y:s.y})),assertions:n.assertions.map(s=>({description:s.description,detail:s.detail,status:s.status})),detail:n.detail,duration:n.duration,nodeType:n.nodeType,screenshotBase64:n.screenshotBase64,snapshotTimestamp:n.snapshotTimestamp,status:n.status,stepIndex:n.stepIndex,title:n.title,url:n.url,viewportHeight:n.viewportHeight,viewportWidth:n.viewportWidth}));await $({config:e,document:tu,variables:{runResultId:t,steps:o}})}var eu,tu,ru,eo=y(()=>{"use strict";Ye();H();eu=Xr(`
96
96
  mutation StartRunCLI($runId: String!, $platform: String!, $agentProfileId: String) {
97
97
  startRun(runId: $runId, platform: $platform, agentProfileId: $agentProfileId) {
98
98
  id
99
99
  }
100
100
  }
101
- `),cd=Oo(`
101
+ `),tu=Xr(`
102
102
  mutation SubmitRunStepsCLI($runResultId: String!, $steps: [StepInput!]!) {
103
103
  submitRunSteps(runResultId: $runResultId, steps: $steps)
104
104
  }
105
- `),dd=Oo(`
105
+ `),ru=Xr(`
106
106
  mutation CompleteRunCLI(
107
107
  $runResultId: String!
108
108
  $status: String!
@@ -125,14 +125,14 @@ ${o}`].join(`
125
125
  status
126
126
  }
127
127
  }
128
- `)});import{graphql as St,readFragment as Fo}from"gql.tada";async function Do({agentProfileDescription:e,agentProfileId:t,baseUrl:o,browser:r,config:n,headed:s,runId:a,workflowId:i}){let l="unknown",c,p,f=!1;try{f=r==null,p=fd({externalBrowser:r,headed:s}),await so({baseUrl:o});let{project:h,workflow:y}=await L({label:"Run context resolved",fn:()=>wd({config:n,workflowId:i})});l=y.name;let x=Sd(y.spec);u.info("Executing workflow: %s",y.name),c=await L({label:"Streaming run started",fn:()=>He({agentProfileId:t,config:n,runId:a})}),await gd({agentProfileDescription:e,agentProfileId:t,baseUrl:o,browserPromise:p,config:n,headed:s,ownsBrowser:f,project:h,runId:a,specData:x,streaming:c,workflow:y})}catch(h){throw await md({browserPromise:p,error:h,ownsBrowser:f,runId:a,streaming:c,workflowName:l}),h}}function fd({externalBrowser:e,headed:t}){return e!=null?Promise.resolve(e):L({label:"Browser launched",fn:()=>re({headed:t})})}async function md({browserPromise:e,error:t,ownsBrowser:o,runId:r,streaming:n,workflowName:s}){let a=t instanceof Error?t.message:String(t),i=t instanceof Error?t.stack:void 0;await ns({error:a,runId:r,stack:i,workflowName:s}),n!=null&&await n.complete({statusOverride:"failed",steps:[],summary:a}).catch(()=>{}),o&&e!=null&&await(await e.catch(()=>{}))?.close()}async function gd({agentProfileDescription:e,agentProfileId:t,baseUrl:o,browserPromise:r,config:n,headed:s,ownsBrowser:a,project:i,runId:l,specData:c,streaming:p,workflow:f}){let[h,y]=await Promise.all([L({label:"Preconditions resolved",fn:()=>ye({baseUrl:o,project:i,workflowSlug:f.slug})}),r]);if(t!=null){a&&await y.close(),await hd({agentProfileDescription:e,agentProfileId:t,baseUrl:o,config:n,headed:s,preconditionResult:h,runId:l,specData:c,streaming:p,workflow:f});return}await yd({baseUrl:o,browser:y,preconditionResult:h,runId:l,specData:c,streaming:p})}async function hd({agentProfileDescription:e,agentProfileId:t,baseUrl:o,config:r,headed:n,preconditionResult:s,runId:a,specData:i,streaming:l,workflow:c}){let p=e!=null&&e.length>0?e:await bd({config:r,profileId:t});await Xt({baseUrl:o,cookies:s.cookies,executedPreconditions:s.executed,extraVariables:s.data,headed:n,navigateTo:s.navigateTo,runId:a,serverUrl:r.ripploServerUrl,spec:i,streaming:l,systemPrompt:p,token:r.token,workflowContext:{description:c.name,expectedOutcome:c.name,name:c.name}}),await Us(s)}async function yd({baseUrl:e,browser:t,preconditionResult:o,runId:r,specData:n,streaming:s}){let a=await L({label:"Spec executed",fn:()=>Me({baseUrl:e,browser:t,cookies:o.cookies,extraVariables:o.data,navigateTo:o.navigateTo,onStep:s.enqueueStep,runId:r,spec:n})});await Us(o),await s.complete({statusOverride:void 0,steps:a,summary:void 0});let i=a.filter(c=>c.status==="passed").length,l=a.filter(c=>c.status==="failed").length;u.info("Run complete: %d passed, %d failed",i,l)}async function Us(e){e.apiUrl!=null&&await ze({apiUrl:e.apiUrl,cookies:e.cookies,executed:e.executed})}async function wd({config:e,workflowId:t}){let o=await T({config:e,document:ud,variables:{projectId:e.projectId}});if(o.project==null)throw new Error("Project not found");let n={...Fo(Os,o.project),...e.baseUrl==null?{}:{baseUrl:e.baseUrl},...e.preconditionApiPath==null?{}:{preconditionApiPath:e.preconditionApiPath}},a=(n.workflows??[]).find(l=>Fo(Vo,l).id===t);if(a==null)throw new Error(`Workflow ${t} not found`);let i=Fo(Vo,a);return{project:n,workflow:i}}async function bd({config:e,profileId:t}){let o=await T({config:e,document:pd,variables:{id:t}});if(o.agentProfile==null)throw new Error(`Agent profile not found: ${t}`);let r=o.agentProfile,n=r.description;if(n==null||n.length===0)throw new Error(`Agent profile "${r.name}" has no description`);return u.info("Using agent profile: %s",r.name),Ve({description:n,output:r.output??void 0,successCriteria:r.successCriteria??void 0})}function Sd(e){if(e==null)throw new Error("Workflow has no spec");let t=ue(e);if(!t.success){let o=t.errors.map(r=>`${r.path}: ${r.message}`).join("; ");throw new Error(`Invalid spec: ${o}`)}return t.data}var Vo,Os,ud,pd,Fs=m(()=>{"use strict";he();Yt();eo();at();ao();_e();ct();xo();D();gt();Eo();Uo();Vo=St(`
128
+ `)});import{graphql as Dt,readFragment as to}from"gql.tada";async function oo({agentProfileDescription:e,agentProfileId:t,baseUrl:r,browser:o,config:n,headed:s,runId:a,webhookSecret:i,workflowId:l}){let c="unknown",p,f,u=!1;try{u=o==null,f=su({externalBrowser:o,headed:s}),await vr({baseUrl:r});let{project:h,workflow:g}=await K({label:"Run context resolved",fn:()=>du({config:n,workflowId:l})});c=g.name;let b=pu(g.spec);m.info("Executing workflow: %s",g.name),p=await K({label:"Streaming run started",fn:()=>nt({agentProfileId:t,config:n,runId:a})}),await iu({agentProfileDescription:e,agentProfileId:t,baseUrl:r,browserPromise:f,config:n,headed:s,ownsBrowser:u,project:h,runId:a,specData:b,streaming:p,webhookSecret:i,workflow:g})}catch(h){throw await au({browserPromise:f,error:h,ownsBrowser:u,runId:a,streaming:p,workflowName:c}),h}}function su({externalBrowser:e,headed:t}){return e!=null?Promise.resolve(e):K({label:"Browser launched",fn:()=>ue({headed:t})})}async function au({browserPromise:e,error:t,ownsBrowser:r,runId:o,streaming:n,workflowName:s}){let a=t instanceof Error?t.message:String(t),i=t instanceof Error?t.stack:void 0;await Ps({error:a,runId:o,stack:i,workflowName:s}),n!=null&&await n.complete({statusOverride:"failed",steps:[],summary:a}).catch(()=>{}),r&&e!=null&&await(await e.catch(()=>{}))?.close()}async function iu({agentProfileDescription:e,agentProfileId:t,baseUrl:r,browserPromise:o,config:n,headed:s,ownsBrowser:a,project:i,runId:l,specData:c,streaming:p,webhookSecret:f,workflow:u}){let[h,g]=await Promise.all([K({label:"Preconditions resolved",fn:()=>Pe({baseUrl:r,project:i,webhookSecret:f,workflowSlug:u.slug})}),o]);if(t!=null){a&&await g.close(),await lu({agentProfileDescription:e,agentProfileId:t,baseUrl:r,config:n,headed:s,preconditionResult:h,runId:l,specData:c,streaming:p,webhookSecret:f,workflow:u});return}await cu({baseUrl:r,browser:g,preconditionResult:h,runId:l,specData:c,streaming:p,webhookSecret:f})}async function lu({agentProfileDescription:e,agentProfileId:t,baseUrl:r,config:o,headed:n,preconditionResult:s,runId:a,specData:i,streaming:l,webhookSecret:c,workflow:p}){let f=e!=null&&e.length>0?e:await uu({config:o,profileId:t});await gr({baseUrl:r,cookies:s.cookies,executedPreconditions:s.executed,extraVariables:s.data,headed:n,navigateTo:s.navigateTo,runId:a,serverUrl:o.ripploServerUrl,spec:i,streaming:l,systemPrompt:f,token:o.token,workflowContext:{description:p.name,expectedOutcome:p.name,name:p.name}}),await fa({preconditionResult:s,webhookSecret:c})}async function cu({baseUrl:e,browser:t,preconditionResult:r,runId:o,specData:n,streaming:s,webhookSecret:a}){let i=await K({label:"Spec executed",fn:()=>Xe({baseUrl:e,browser:t,cookies:r.cookies,extraVariables:r.data,navigateTo:r.navigateTo,onStep:s.enqueueStep,runId:o,spec:n})});await fa({preconditionResult:r,webhookSecret:a}),await s.complete({statusOverride:void 0,steps:i,summary:void 0});let l=i.filter(p=>p.status==="passed").length,c=i.filter(p=>p.status==="failed").length;m.info("Run complete: %d passed, %d failed",l,c)}async function fa({preconditionResult:e,webhookSecret:t}){e.apiUrl!=null&&await ot({apiUrl:e.apiUrl,cookies:e.cookies,executed:e.executed,webhookSecret:t})}async function du({config:e,workflowId:t}){let r=await $({config:e,document:ou,variables:{projectId:e.projectId}});if(r.project==null)throw new Error("Project not found");let n={...to(pa,r.project),...e.baseUrl==null?{}:{baseUrl:e.baseUrl},...e.preconditionApiPath==null?{}:{preconditionApiPath:e.preconditionApiPath}},a=(n.workflows??[]).find(l=>to(ro,l).id===t);if(a==null)throw new Error(`Workflow ${t} not found`);let i=to(ro,a);return{project:n,workflow:i}}async function uu({config:e,profileId:t}){let r=await $({config:e,document:nu,variables:{id:t}});if(r.agentProfile==null)throw new Error(`Agent profile not found: ${t}`);let o=r.agentProfile,n=o.description;if(n==null||n.length===0)throw new Error(`Agent profile "${o.name}" has no description`);return m.info("Using agent profile: %s",o.name),Ge({description:n,output:o.output??void 0,successCriteria:o.successCriteria??void 0})}function pu(e){if(e==null)throw new Error("Workflow has no spec");let t=ye(e);if(!t.success){let r=t.errors.map(o=>`${o.path}: ${o.message}`).join("; ");throw new Error(`Invalid spec: ${r}`)}return t.data}var ro,pa,ou,nu,ma=y(()=>{"use strict";Re();pr();yr();bt();Rr();Ye();vt();Lr();H();It();Zr();eo();ro=Dt(`
129
129
  fragment WorkflowRun on Workflow {
130
130
  id
131
131
  slug
132
132
  name
133
133
  spec
134
134
  }
135
- `),Os=St(`
135
+ `),pa=Dt(`
136
136
  fragment ProjectRun on Project {
137
137
  id
138
138
  baseUrl
@@ -151,13 +151,13 @@ ${o}`].join(`
151
151
  ...WorkflowRun
152
152
  }
153
153
  }
154
- `,[Vo]),ud=St(`
154
+ `,[ro]),ou=Dt(`
155
155
  query ProjectRun($projectId: String!) {
156
156
  project(id: $projectId) {
157
157
  ...ProjectRun
158
158
  }
159
159
  }
160
- `,[Os]),pd=St(`
160
+ `,[pa]),nu=Dt(`
161
161
  query AgentProfileRun($id: String!) {
162
162
  agentProfile(id: $id) {
163
163
  id
@@ -167,7 +167,7 @@ ${o}`].join(`
167
167
  successCriteria
168
168
  }
169
169
  }
170
- `)});var U=m(()=>{"use strict";Ot();Jt();Yt();eo();Le();at();ws();ao();_e();lo();Rs();yo();Fs();xo();Po();ie();D();gt();Eo();Oe();Uo();Q()});import kd from"fs";import Rd from"path";import{z as F}from"zod";function Ds(e){return Rd.join(e,".ripplo","graph.json")}function Wo(e){let t=kd.readFileSync(e,"utf8"),o=JSON.parse(t);return Vs.parse(o)}function Lo(e){return{edges:e.edges,preconditions:e.preconditions??{},resetPrecondition:e.resetPrecondition,states:e.states,version:e.version}}var Vs,_o=m(()=>{"use strict";Vs=F.object({edges:F.array(F.object({from:F.string(),to:F.string(),workflow:F.string()})),preconditions:F.record(F.string(),F.unknown()).optional(),resetPrecondition:F.string().optional(),states:F.record(F.string(),F.object({preconditions:F.array(F.string()),route:F.string()})),version:F.literal(3)})});import vd from"fs";import Pd from"path";import{z as Ce}from"zod";function Je(e){return Pd.join(e,".ripplo","workflows")}function Ye(e){let t=vd.readFileSync(e,"utf8"),o=JSON.parse(t);return qo.parse(o)}var qo,Ke=m(()=>{"use strict";he();qo=Ce.object({additionalChecks:Ce.array(Ce.string()).default([]),description:Ce.string(),expectedOutcome:Ce.string(),name:Ce.string(),spec:Pe})});var Go={};xa(Go,{deleteWorkflowFile:()=>Ad,duplicateWorkflowFile:()=>Nd,startFileWatcher:()=>Mo,syncAll:()=>Bo});import xd from"crypto";import fe from"fs";import Qe from"path";import{watch as Td}from"chokidar";import{graphql as Cd}from"gql.tada";async function Bo(e){let t=await _s(e);return u.info("Synced %d workflow(s) + graph to dev session",qs(e.cwd)),t}function Mo({config:e,cwd:t,lastHash:o}){let r=Qe.join(t,".ripplo"),n=o,s,a=Td(r,{depth:2,ignoreInitial:!0,interval:1e3,persistent:!0,usePolling:!0});a.on("all",(l,c)=>{c.endsWith(".json")&&(s!=null&&clearTimeout(s),s=setTimeout(()=>{i({config:e,cwd:t})},500))});async function i(l){try{let c=Ws(l.cwd),p=Ls(c);if(p===n)return;n=p,await _s(l),u.info("Dev session synced (%d workflow(s))",qs(l.cwd))}catch(c){let p=c instanceof Error?c.message:"Unknown error";u.error("Sync failed: %s",p)}}return function(){s!=null&&clearTimeout(s),a.close()}}function Ws(e){let t=Ds(e),o=Wo(t),r=JSON.stringify(Lo(o)),n=Je(e),a=(fe.existsSync(n)?fe.readdirSync(n).filter(i=>i.endsWith(".json")):[]).map(i=>{let l=Qe.join(n,i),c=Ye(l),p=i.replace(/\.json$/,"");return{description:c.description,expectedOutcome:c.expectedOutcome,name:c.name,slug:p,spec:JSON.stringify(c.spec)}});return{graphSpec:r,workflows:a}}function Ls(e){return xd.createHash("sha256").update(JSON.stringify(e)).digest("hex")}async function _s({config:e,cwd:t}){let o=Ws(t),r=Ls(o),n=await T({config:e,document:Id,variables:{graphSpec:o.graphSpec,projectId:e.projectId,workflows:[...o.workflows]}});if(n.syncDevSession==null)throw new Error("syncDevSession returned null");return{devSessionId:n.syncDevSession.id,hash:r}}function qs(e){let t=Je(e);return fe.existsSync(t)?fe.readdirSync(t).filter(o=>o.endsWith(".json")).length:0}function Ad({cwd:e,slug:t}){let o=Qe.join(Je(e),`${t}.json`);return fe.existsSync(o)?(fe.unlinkSync(o),!0):!1}function Nd({cwd:e,newSlug:t,sourceSlug:o}){let r=Je(e),n=Qe.join(r,`${o}.json`);if(!fe.existsSync(n))return!1;let s=Ye(n),a={...s,name:`${s.name} (copy)`};return fe.writeFileSync(Qe.join(r,`${t}.json`),JSON.stringify(a,null,2)),!0}var Id,kt=m(()=>{"use strict";_o();Ke();U();Id=Cd(`
170
+ `)});var q=y(()=>{"use strict";Qt();ur();pr();yr();Ke();bt();Vs();Rr();Ye();xr();qs();Er();ma();Lr();Wr();me();H();It();Zr();Yr();Be();eo();se()});import fu from"fs";import mu from"path";import{z as B}from"zod";function ga(e){return mu.join(e,".ripplo","graph.json")}function no(e){let t=fu.readFileSync(e,"utf8"),r=JSON.parse(t);return ha.parse(r)}function so(e){return{edges:e.edges,preconditions:e.preconditions??{},resetPrecondition:e.resetPrecondition,states:e.states,version:e.version}}var ha,ao=y(()=>{"use strict";ha=B.object({edges:B.array(B.object({from:B.string(),to:B.string(),workflow:B.string()})),preconditions:B.record(B.string(),B.unknown()).optional(),resetPrecondition:B.string().optional(),states:B.record(B.string(),B.object({preconditions:B.array(B.string()),route:B.string()})),version:B.literal(3)})});import hu from"fs";import gu from"path";import{z as Oe}from"zod";function st(e){return gu.join(e,".ripplo","workflows")}function at(e){let t=hu.readFileSync(e,"utf8"),r=JSON.parse(t);return io.parse(r)}var io,it=y(()=>{"use strict";Re();io=Oe.object({additionalChecks:Oe.array(Oe.string()).default([]),description:Oe.string(),expectedOutcome:Oe.string(),name:Oe.string(),spec:Ne})});var uo={};ai(uo,{deleteWorkflowFile:()=>ku,duplicateWorkflowFile:()=>vu,startFileWatcher:()=>co,syncAll:()=>lo});import yu from"crypto";import Se from"fs";import lt from"path";import{watch as wu}from"chokidar";import{graphql as bu}from"gql.tada";async function lo(e){let t=await ba(e);return m.info("Synced %d workflow(s) + graph to dev session",Sa(e.cwd)),t}function co({config:e,cwd:t,lastHash:r}){let o=lt.join(t,".ripplo"),n=r,s,a=wu(o,{depth:2,ignoreInitial:!0,interval:1e3,persistent:!0,usePolling:!0});a.on("all",(l,c)=>{c.endsWith(".json")&&(s!=null&&clearTimeout(s),s=setTimeout(()=>{i({config:e,cwd:t})},500))});async function i(l){try{let c=ya(l.cwd),p=wa(c);if(p===n)return;n=p,await ba(l),m.info("Dev session synced (%d workflow(s))",Sa(l.cwd))}catch(c){let p=c instanceof Error?c.message:"Unknown error";m.error("Sync failed: %s",p)}}return function(){s!=null&&clearTimeout(s),a.close()}}function ya(e){let t=ga(e),r=no(t),o=JSON.stringify(so(r)),n=st(e),a=(Se.existsSync(n)?Se.readdirSync(n).filter(i=>i.endsWith(".json")):[]).map(i=>{let l=lt.join(n,i),c=at(l),p=i.replace(/\.json$/,"");return{description:c.description,expectedOutcome:c.expectedOutcome,name:c.name,slug:p,spec:JSON.stringify(c.spec)}});return{graphSpec:o,workflows:a}}function wa(e){return yu.createHash("sha256").update(JSON.stringify(e)).digest("hex")}async function ba({config:e,cwd:t}){let r=ya(t),o=wa(r),n=await $({config:e,document:Su,variables:{graphSpec:r.graphSpec,projectId:e.projectId,workflows:[...r.workflows]}});if(n.syncDevSession==null)throw new Error("syncDevSession returned null");return{devSessionId:n.syncDevSession.id,hash:o}}function Sa(e){let t=st(e);return Se.existsSync(t)?Se.readdirSync(t).filter(r=>r.endsWith(".json")).length:0}function ku({cwd:e,slug:t}){let r=lt.join(st(e),`${t}.json`);return Se.existsSync(r)?(Se.unlinkSync(r),!0):!1}function vu({cwd:e,newSlug:t,sourceSlug:r}){let o=st(e),n=lt.join(o,`${r}.json`);if(!Se.existsSync(n))return!1;let s=at(n),a={...s,name:`${s.name} (copy)`};return Se.writeFileSync(lt.join(o,`${t}.json`),JSON.stringify(a,null,2)),!0}var Su,Vt=y(()=>{"use strict";ao();it();q();Su=bu(`
171
171
  mutation SyncDevSession(
172
172
  $projectId: String!
173
173
  $graphSpec: String!
@@ -177,13 +177,13 @@ ${o}`].join(`
177
177
  id
178
178
  }
179
179
  }
180
- `)});U();import{config as ka}from"dotenv";import Nt from"path";import{fileURLToPath as pp}from"url";U();kt();import{availableParallelism as jd}from"os";import{createClient as $d}from"graphql-sse";import{graphql as Ze}from"gql.tada";import{print as zo}from"graphql";import{input as Ed}from"@inquirer/prompts";import Od from"p-limit";var Ud=Ze(`
180
+ `)});q();import{config as Xa}from"dotenv";import Ht from"path";import{fileURLToPath as sf}from"url";q();Vt();import{availableParallelism as Ru}from"os";import{createClient as Pu}from"graphql-sse";import{graphql as ct}from"gql.tada";import{print as po}from"graphql";import{input as xu}from"@inquirer/prompts";import Cu from"p-limit";var Tu=ct(`
181
181
  mutation EndDevSession($projectId: String!) {
182
182
  endDevSession(projectId: $projectId) {
183
183
  id
184
184
  }
185
185
  }
186
- `),Fd=Ze(`
186
+ `),Iu=ct(`
187
187
  subscription RunRequestedDev {
188
188
  runRequested {
189
189
  agentProfileDescription
@@ -193,7 +193,7 @@ ${o}`].join(`
193
193
  workflowId
194
194
  }
195
195
  }
196
- `),Vd=Ze(`
196
+ `),Au=ct(`
197
197
  query PendingDevRuns($devSessionId: String!) {
198
198
  pendingDevRuns(devSessionId: $devSessionId) {
199
199
  id
@@ -206,14 +206,14 @@ ${o}`].join(`
206
206
  }
207
207
  }
208
208
  }
209
- `),Dd=Ze(`
209
+ `),Nu=ct(`
210
210
  subscription DevWorkflowDeleteRequested($projectId: String!) {
211
211
  devWorkflowDeleteRequested(projectId: $projectId) {
212
212
  projectId
213
213
  slug
214
214
  }
215
215
  }
216
- `),Wd=Ze(`
216
+ `),ju=ct(`
217
217
  subscription DevWorkflowDuplicateRequested($projectId: String!) {
218
218
  devWorkflowDuplicateRequested(projectId: $projectId) {
219
219
  projectId
@@ -221,16 +221,16 @@ ${o}`].join(`
221
221
  newSlug
222
222
  }
223
223
  }
224
- `);async function Rt({concurrency:e,headed:t}){let o=_();if(o==null)return E("Not logged in. Run: ripplo login");let r=process.cwd();u.info("Starting dev session...");let n=await Qd(o),{devSessionId:s,hash:a}=await Bo({config:o,cwd:r}),i=Mo({config:o,cwd:r,lastHash:a});u.info("Connecting to %s...",o.ripploServerUrl);let l=o,c=$d({headers:{Authorization:`Bearer ${l.token}`},on:{connected:S=>{S&&u.info("Reconnected.")},connecting:S=>{S&&u.info("Reconnecting to server...")}},retryAttempts:1/0,url:`${l.ripploServerUrl}/graphql`,retry:async S=>{let j=Math.min(1e3*2**S,3e4);u.warn("Connection lost. Reconnecting in %dms...",j),await new Promise(ae=>{setTimeout(ae,j)})}});async function p(){i(),c.dispose();try{await T({config:l,document:Ud,variables:{projectId:l.projectId}}),u.info("Dev session ended.")}catch{u.warn("Failed to clean up dev session.")}}process.on("SIGINT",()=>{p().then(()=>process.exit(0))}),process.on("SIGTERM",()=>{p().then(()=>process.exit(0))}),process.on("uncaughtException",S=>{u.error("Unexpected error: %s",S.message),p().then(()=>process.exit(1))}),process.on("unhandledRejection",S=>{let j=S instanceof Error?S.message:String(S);u.error("Unhandled rejection: %s",j),p().then(()=>process.exit(1))}),u.info("Dev mode active. Watching files + waiting for runs...");let f=new Set,h=e??jd();u.info("Max concurrent runs: %d",h);let y=Od(h),x=c.iterate({query:zo(Fd)}),R=c.iterate({query:zo(Dd),variables:{projectId:o.projectId}}),$=c.iterate({query:zo(Wd),variables:{projectId:o.projectId}});await Promise.all([Ld({activeRunIds:f,baseUrl:n,config:o,headed:t,limiter:y,subscription:x}),qd({activeRunIds:f,baseUrl:n,config:o,devSessionId:s,headed:t,limiter:y}),zd({cwd:r,subscription:R}),Jd({cwd:r,subscription:$})])}async function Ld({activeRunIds:e,baseUrl:t,config:o,headed:r,limiter:n,subscription:s}){for await(let a of s){let i=Kd(a);i!=null&&(e.has(i.runId)||(u.info("Run requested: %s (workflow %s)",i.runId,i.workflowId),e.add(i.runId),n(()=>Bs({agentProfileDescription:i.agentProfileDescription,agentProfileId:i.agentProfileId,baseUrl:t,config:o,headed:r,runId:i.runId,workflowId:i.workflowId}).finally(()=>{e.delete(i.runId)}))))}}var _d=5e3;async function qd({activeRunIds:e,baseUrl:t,config:o,devSessionId:r,headed:n,limiter:s}){for(;;)await new Promise(a=>{setTimeout(a,_d)}),await Bd({activeRunIds:e,baseUrl:t,config:o,devSessionId:r,headed:n,limiter:s})}async function Bd({activeRunIds:e,baseUrl:t,config:o,devSessionId:r,headed:n,limiter:s}){try{let a=await T({config:o,document:Vd,variables:{devSessionId:r}});if(a.pendingDevRuns==null)throw new Error("pendingDevRuns returned null");a.pendingDevRuns.filter(l=>!e.has(l.id)).forEach(l=>{let c=l.workflow?.id;c!=null&&(u.info("Polling picked up run: %s (workflow %s)",l.id,c),e.add(l.id),s(()=>Bs({agentProfileDescription:l.agentProfile?.description??void 0,agentProfileId:l.agentProfile?.id??void 0,baseUrl:t,config:o,headed:n,runId:l.id,workflowId:c}).finally(()=>{e.delete(l.id)})))})}catch(a){let i=a instanceof Error?a.message:String(a);u.warn("Polling for pending runs failed: %s",i)}}async function Bs({agentProfileDescription:e,agentProfileId:t,baseUrl:o,config:r,headed:n,runId:s,workflowId:a}){try{let i=_()??r,l=i.baseUrl??o;await qe({maxRuns:100}),await Do({agentProfileDescription:e,agentProfileId:t,baseUrl:l,browser:void 0,config:i,headed:n,runId:s,workflowId:a})}catch(i){Md({error:i,runId:s})}}function Md({error:e,runId:t}){let o=e instanceof Error?e.message:String(e);if(o.includes("already claimed")){u.info("Run %s already claimed by another instance, skipping",t);return}u.error("Run failed: %s",o)}function Gd(e){if(!("runId"in e)||!("workflowId"in e)||!("executor"in e)||typeof e.runId!="string"||typeof e.workflowId!="string"||typeof e.executor!="string")return;let t="agentProfileId"in e&&typeof e.agentProfileId=="string"?e.agentProfileId:void 0;return{agentProfileDescription:"agentProfileDescription"in e&&typeof e.agentProfileDescription=="string"?e.agentProfileDescription:void 0,agentProfileId:t,executor:e.executor,runId:e.runId,workflowId:e.workflowId}}async function zd({cwd:e,subscription:t}){let{deleteWorkflowFile:o}=await Promise.resolve().then(()=>(kt(),Go));for await(let r of t){let n=Hd(r);if(n==null)continue;o({cwd:e,slug:n})?u.info("Deleted workflow file: %s.json",n):u.warn("Workflow file not found for deletion: %s.json",n)}}function Hd(e){if(typeof e!="object"||e==null||!("data"in e))return;let t=e.data;if(typeof t!="object"||t==null||!("devWorkflowDeleteRequested"in t))return;let o=t.devWorkflowDeleteRequested;if(!(typeof o!="object"||o==null||!("slug"in o))&&typeof o.slug=="string")return o.slug}async function Jd({cwd:e,subscription:t}){let{duplicateWorkflowFile:o}=await Promise.resolve().then(()=>(kt(),Go));for await(let r of t){let n=Yd(r);if(n==null)continue;o({cwd:e,newSlug:n.newSlug,sourceSlug:n.sourceSlug})?u.info("Duplicated workflow: %s.json \u2192 %s.json",n.sourceSlug,n.newSlug):u.warn("Source workflow file not found for duplication: %s.json",n.sourceSlug)}}function Yd(e){if(typeof e!="object"||e==null||!("data"in e))return;let t=e.data;if(typeof t!="object"||t==null||!("devWorkflowDuplicateRequested"in t))return;let o=t.devWorkflowDuplicateRequested;if(!(typeof o!="object"||o==null)&&!(!("sourceSlug"in o)||!("newSlug"in o)||typeof o.sourceSlug!="string"||typeof o.newSlug!="string"))return{newSlug:o.newSlug,sourceSlug:o.sourceSlug}}function Kd(e){if(typeof e!="object"||e==null||!("data"in e))return;let t=e.data;if(typeof t!="object"||t==null||!("runRequested"in t))return;let o=t.runRequested;if(!(typeof o!="object"||o==null))return Gd(o)}async function Qd(e){if(e.baseUrl!=null)return e.baseUrl;let t=await Ed({default:"http://localhost:3000",message:"Base URL (local dev server):"});return ne({...e,baseUrl:t}),t}he();U();import{readFileSync as Ms}from"fs";import{graphql as Xe,readFragment as Ho}from"gql.tada";async function Gs(e){let t=await ru(e);u.info("Starting agent test against %s",t.baseUrl);let o=await Xd({config:t.config,workflowId:t.workflowId});u.info("Created run: %s",o);let r=await He({agentProfileId:t.agentProfileId,config:t.config,runId:o}),n=await re({headed:e.headed}),s=await n.newContext({baseURL:t.baseUrl});t.cookies.length>0&&(await s.addCookies([...t.cookies]),u.info("Injected %d cookies from preconditions",t.cookies.length));let a=await s.newPage();t.navigateTo!=null&&(u.info("Navigating to precondition start page: %s",t.navigateTo),await a.goto(t.navigateTo,{waitUntil:"domcontentloaded"}));try{let i=await Fe({baseUrl:t.baseUrl,executedPreconditions:t.executedPreconditions,extraVariables:t.extraVariables,onStep:r.enqueueStep,page:a,runId:o,serverUrl:t.config.ripploServerUrl,spec:t.spec,systemPrompt:t.systemPrompt,token:t.config.token,workflowContext:t.workflowContext}),l=i.verdict==="pass"?"passed":"failed";await r.complete({statusOverride:l,steps:i.steps,summary:i.findings}),u.info(`
224
+ `);async function _t({concurrency:e,headed:t}){let r=M();if(r==null)return W("Not logged in. Run: ripplo login");let o=Bu({config:r}),n=process.cwd();m.info("Starting dev session...");let s=await Mu(o),{devSessionId:a,hash:i}=await lo({config:o,cwd:n}),l=co({config:o,cwd:n,lastHash:i});m.info("Connecting to %s...",o.ripploServerUrl);let c=o,p=Pu({headers:{Authorization:`Bearer ${c.token}`},on:{connected:S=>{S&&m.info("Reconnected.")},connecting:S=>{S&&m.info("Reconnecting to server...")}},retryAttempts:1/0,url:`${c.ripploServerUrl}/graphql`,retry:async S=>{let N=Math.min(1e3*2**S,3e4);m.warn("Connection lost. Reconnecting in %dms...",N),await new Promise(j=>{setTimeout(j,N)})}});async function f(){l(),p.dispose();try{await $({config:c,document:Tu,variables:{projectId:c.projectId}}),m.info("Dev session ended.")}catch{m.warn("Failed to clean up dev session.")}}process.on("SIGINT",()=>{f().then(()=>process.exit(0))}),process.on("SIGTERM",()=>{f().then(()=>process.exit(0))}),process.on("uncaughtException",S=>{m.error("Unexpected error: %s",S.message),f().then(()=>process.exit(1))}),process.on("unhandledRejection",S=>{let N=S instanceof Error?S.message:String(S);m.error("Unhandled rejection: %s",N),f().then(()=>process.exit(1))}),m.info("Dev mode active. Watching files + waiting for runs...");let u=new Set,h=e??Ru();m.info("Max concurrent runs: %d",h);let g=Cu(h),b=p.iterate({query:po(Iu)}),P=p.iterate({query:po(Nu),variables:{projectId:o.projectId}}),k=p.iterate({query:po(ju),variables:{projectId:o.projectId}});await Promise.all([$u({activeRunIds:u,baseUrl:s,config:o,headed:t,limiter:g,subscription:b}),Ou({activeRunIds:u,baseUrl:s,config:o,devSessionId:a,headed:t,limiter:g}),Vu({cwd:n,subscription:P}),Wu({cwd:n,subscription:k})])}async function $u({activeRunIds:e,baseUrl:t,config:r,headed:o,limiter:n,subscription:s}){for await(let a of s){let i=qu(a);i!=null&&(e.has(i.runId)||(m.info("Run requested: %s (workflow %s)",i.runId,i.workflowId),e.add(i.runId),n(()=>ka({agentProfileDescription:i.agentProfileDescription,agentProfileId:i.agentProfileId,baseUrl:t,config:r,headed:o,runId:i.runId,workflowId:i.workflowId}).finally(()=>{e.delete(i.runId)}))))}}var Eu=5e3;async function Ou({activeRunIds:e,baseUrl:t,config:r,devSessionId:o,headed:n,limiter:s}){for(;;)await new Promise(a=>{setTimeout(a,Eu)}),await Uu({activeRunIds:e,baseUrl:t,config:r,devSessionId:o,headed:n,limiter:s})}async function Uu({activeRunIds:e,baseUrl:t,config:r,devSessionId:o,headed:n,limiter:s}){try{let a=await $({config:r,document:Au,variables:{devSessionId:o}});if(a.pendingDevRuns==null)throw new Error("pendingDevRuns returned null");a.pendingDevRuns.filter(l=>!e.has(l.id)).forEach(l=>{let c=l.workflow?.id;c!=null&&(m.info("Polling picked up run: %s (workflow %s)",l.id,c),e.add(l.id),s(()=>ka({agentProfileDescription:l.agentProfile?.description??void 0,agentProfileId:l.agentProfile?.id??void 0,baseUrl:t,config:r,headed:n,runId:l.id,workflowId:c}).finally(()=>{e.delete(l.id)})))})}catch(a){let i=a instanceof Error?a.message:String(a);m.warn("Polling for pending runs failed: %s",i)}}async function ka({agentProfileDescription:e,agentProfileId:t,baseUrl:r,config:o,headed:n,runId:s,workflowId:a}){try{let i=M()??o,l=i.baseUrl??r;await Qe({maxRuns:100}),await oo({agentProfileDescription:e,agentProfileId:t,baseUrl:l,browser:void 0,config:i,headed:n,runId:s,webhookSecret:i.webhookSecret,workflowId:a})}catch(i){Fu({error:i,runId:s})}}function Fu({error:e,runId:t}){let r=e instanceof Error?e.message:String(e);if(r.includes("already claimed")){m.info("Run %s already claimed by another instance, skipping",t);return}m.error("Run failed: %s",r)}function Du(e){if(!("runId"in e)||!("workflowId"in e)||!("executor"in e)||typeof e.runId!="string"||typeof e.workflowId!="string"||typeof e.executor!="string")return;let t="agentProfileId"in e&&typeof e.agentProfileId=="string"?e.agentProfileId:void 0;return{agentProfileDescription:"agentProfileDescription"in e&&typeof e.agentProfileDescription=="string"?e.agentProfileDescription:void 0,agentProfileId:t,executor:e.executor,runId:e.runId,workflowId:e.workflowId}}async function Vu({cwd:e,subscription:t}){let{deleteWorkflowFile:r}=await Promise.resolve().then(()=>(Vt(),uo));for await(let o of t){let n=_u(o);if(n==null)continue;r({cwd:e,slug:n})?m.info("Deleted workflow file: %s.json",n):m.warn("Workflow file not found for deletion: %s.json",n)}}function _u(e){if(typeof e!="object"||e==null||!("data"in e))return;let t=e.data;if(typeof t!="object"||t==null||!("devWorkflowDeleteRequested"in t))return;let r=t.devWorkflowDeleteRequested;if(!(typeof r!="object"||r==null||!("slug"in r))&&typeof r.slug=="string")return r.slug}async function Wu({cwd:e,subscription:t}){let{duplicateWorkflowFile:r}=await Promise.resolve().then(()=>(Vt(),uo));for await(let o of t){let n=Lu(o);if(n==null)continue;r({cwd:e,newSlug:n.newSlug,sourceSlug:n.sourceSlug})?m.info("Duplicated workflow: %s.json \u2192 %s.json",n.sourceSlug,n.newSlug):m.warn("Source workflow file not found for duplication: %s.json",n.sourceSlug)}}function Lu(e){if(typeof e!="object"||e==null||!("data"in e))return;let t=e.data;if(typeof t!="object"||t==null||!("devWorkflowDuplicateRequested"in t))return;let r=t.devWorkflowDuplicateRequested;if(!(typeof r!="object"||r==null)&&!(!("sourceSlug"in r)||!("newSlug"in r)||typeof r.sourceSlug!="string"||typeof r.newSlug!="string"))return{newSlug:r.newSlug,sourceSlug:r.sourceSlug}}function qu(e){if(typeof e!="object"||e==null||!("data"in e))return;let t=e.data;if(typeof t!="object"||t==null||!("runRequested"in t))return;let r=t.runRequested;if(!(typeof r!="object"||r==null))return Du(r)}function Bu({config:e}){if(e.webhookSecret.length>0)return e;let t={...e,webhookSecret:rt()};return ie(t),m.info("Generated webhook secret"),t}async function Mu(e){if(e.baseUrl!=null)return e.baseUrl;let t=await xu({default:"http://localhost:3000",message:"Base URL (local dev server):"});return ie({...e,baseUrl:t}),t}Re();q();import{readFileSync as va}from"fs";import{graphql as dt,readFragment as fo}from"gql.tada";async function Ra(e){let t=await Yu(e);m.info("Starting agent test against %s",t.baseUrl);let r=await Gu({config:t.config,workflowId:t.workflowId});m.info("Created run: %s",r);let o=await nt({agentProfileId:t.agentProfileId,config:t.config,runId:r}),n=await ue({headed:e.headed}),s=await n.newContext({baseURL:t.baseUrl});t.cookies.length>0&&(await s.addCookies([...t.cookies]),m.info("Injected %d cookies from preconditions",t.cookies.length));let a=await s.newPage();t.navigateTo!=null&&(m.info("Navigating to precondition start page: %s",t.navigateTo),await a.goto(t.navigateTo,{waitUntil:"domcontentloaded"}));try{let i=await ze({baseUrl:t.baseUrl,executedPreconditions:t.executedPreconditions,extraVariables:t.extraVariables,onStep:o.enqueueStep,page:a,runId:r,serverUrl:t.config.ripploServerUrl,spec:t.spec,systemPrompt:t.systemPrompt,token:t.config.token,workflowContext:t.workflowContext}),l=i.verdict==="pass"?"passed":"failed";await o.complete({statusOverride:l,steps:i.steps,summary:i.findings}),m.info(`
225
225
  === Agent Summary ===
226
- %s`,i.findings),eu({result:i})}finally{await n.close()}}var Zd=Xe(`
226
+ %s`,i.findings),Hu({result:i})}finally{await n.close()}}var zu=dt(`
227
227
  mutation CreateRunAgentTest($workflowId: String!, $platforms: [String!]!, $concurrency: Int!) {
228
228
  createRun(workflowId: $workflowId, platforms: $platforms, concurrency: $concurrency) {
229
229
  id
230
230
  }
231
231
  }
232
- `);async function Xd({config:e,workflowId:t}){let o=await T({config:e,document:Zd,variables:{concurrency:1,platforms:["chromium"],workflowId:t}});return o.createRun==null?E("Failed to create run"):o.createRun.id}function eu({result:e}){u.info(`
233
- === Summary ===`),u.info("Steps: %d",e.steps.length);let t=e.steps.filter(r=>r.status==="passed").length,o=e.steps.filter(r=>r.status==="failed").length;u.info("Passed: %d, Failed: %d",t,o),u.info("Generated spec has %d nodes",Object.keys(e.generatedSpec.nodes).length)}var tu=Xe(`
232
+ `);async function Gu({config:e,workflowId:t}){let r=await $({config:e,document:zu,variables:{concurrency:1,platforms:["chromium"],workflowId:t}});return r.createRun==null?W("Failed to create run"):r.createRun.id}function Hu({result:e}){m.info(`
233
+ === Summary ===`),m.info("Steps: %d",e.steps.length);let t=e.steps.filter(o=>o.status==="passed").length,r=e.steps.filter(o=>o.status==="failed").length;m.info("Passed: %d, Failed: %d",t,r),m.info("Generated spec has %d nodes",Object.keys(e.generatedSpec.nodes).length)}var Ju=dt(`
234
234
  query AgentProfileForCLI($id: String!) {
235
235
  agentProfile(id: $id) {
236
236
  id
@@ -240,7 +240,7 @@ ${o}`].join(`
240
240
  successCriteria
241
241
  }
242
242
  }
243
- `),Jo=Xe(`
243
+ `),mo=dt(`
244
244
  fragment WorkflowAgentTest on Workflow {
245
245
  id
246
246
  name
@@ -249,7 +249,7 @@ ${o}`].join(`
249
249
  expectedOutcome
250
250
  spec
251
251
  }
252
- `),zs=Xe(`
252
+ `),Pa=dt(`
253
253
  fragment ProjectAgentTest on Project {
254
254
  id
255
255
  baseUrl
@@ -268,14 +268,14 @@ ${o}`].join(`
268
268
  ...WorkflowAgentTest
269
269
  }
270
270
  }
271
- `,[Jo]),ou=Xe(`
271
+ `,[mo]),Ku=dt(`
272
272
  query ProjectAgentTest($projectId: String!) {
273
273
  project(id: $projectId) {
274
274
  ...ProjectAgentTest
275
275
  }
276
276
  }
277
- `,[zs]);async function ru(e){let t=nu(),o=await su({config:t,params:e}),r=await iu({config:t,params:e});if(r==null)return E("No workflow. Provide --workflow <id>");let n=e.url??r.baseUrl,s=r.spec??(e.specPath==null?void 0:du(e.specPath));return o==null?E("No system prompt. Provide --agent-profile <id> or --prompt <text|file>"):{agentProfileId:e.agentProfileId,baseUrl:n,config:t,cookies:r.cookies,executedPreconditions:r.executedPreconditions,extraVariables:r.extraVariables,navigateTo:r.navigateTo,spec:s,systemPrompt:o,workflowContext:r.workflowContext,workflowId:r.workflowId}}function nu(){let e=_();return e??E("Not logged in. Run: ripplo login")}async function su({config:e,params:t}){if(t.agentProfileId!=null&&e!=null)return au({config:e,profileId:t.agentProfileId});if(t.promptArg!=null)return cu(t.promptArg)}async function au({config:e,profileId:t}){let o=await T({config:e,document:tu,variables:{id:t}});if(o.agentProfile==null)return E(`Agent profile not found: ${t}`);let r=o.agentProfile,n=r.description;return n==null||n.length===0?E(`Agent profile "${r.name}" has no description to use as system prompt`):(u.info("Using agent profile: %s",r.name),Ve({description:n,output:r.output??void 0,successCriteria:r.successCriteria??void 0}))}async function iu({config:e,params:t}){if(t.workflowId==null||e==null)return;let o=await lu(e),n={...Ho(zs,o),...e.baseUrl==null?{}:{baseUrl:e.baseUrl},...e.preconditionApiPath==null?{}:{preconditionApiPath:e.preconditionApiPath}},a=(n.workflows??[]).find(f=>Ho(Jo,f).id===t.workflowId);if(a==null)return E(`Workflow not found: ${t.workflowId}`);let i=Ho(Jo,a);u.info("Using workflow: %s",i.name);let l=await ye({baseUrl:n.baseUrl,project:n,workflowSlug:i.slug}),c=i.spec==null?void 0:Hs(i.spec),p={description:i.description,expectedOutcome:i.expectedOutcome,name:i.name};return{baseUrl:n.baseUrl,cookies:l.cookies,executedPreconditions:l.executed,extraVariables:l.data,navigateTo:l.navigateTo,spec:c,workflowContext:p,workflowId:i.id}}async function lu(e){let t=await T({config:e,document:ou,variables:{projectId:e.projectId}});return t.project==null?E("Project not found. Check your config."):t.project}function cu(e){try{return Ms(e,"utf8")}catch{return e}}function du(e){let t=JSON.parse(Ms(e,"utf8"));return Hs(t)}function Hs(e){let t=ue(e);if(!t.success){let o=t.errors.map(r=>`${r.path}: ${r.message}`).join("; ");return E(`Invalid spec: ${o}`)}return t.data}Te();U();import et from"fs";import Ie from"path";function Ys({graphPath:e,outputPath:t}){let o=pu(e),r=fu(o),n=Object.entries(r.preconditions).map(([l,c])=>({name:l,returns:c.returns}));if(n.length===0){u.warn("No preconditions found in graph. Nothing to generate.");return}let s=mu(n),a=uu({graphPath:o,outputPath:t}),i=Ie.dirname(a);et.existsSync(i)||et.mkdirSync(i,{recursive:!0}),et.writeFileSync(a,s),u.info("Generated %s with %d precondition(s)",a,n.length)}function uu({graphPath:e,outputPath:t}){return t!=null?Ie.resolve(t):Ie.join(Ie.dirname(e),"..","generated","precondition-api.ts")}function pu(e){if(e!=null)return Ie.resolve(e);let t=Ie.join(process.cwd(),".ripplo","graph.json");if(!et.existsSync(t))throw new Error("No .ripplo/graph.json found.");return t}function fu(e){let t=et.readFileSync(e,"utf8"),o=JSON.parse(t),r=typeof o=="object"&&o!=null&&"_meta"in o?Object.fromEntries(Object.entries(o).filter(([s])=>s!=="_meta")):o,n=Ge.safeParse(r);if(!n.success){let s=n.error.issues.map(a=>`${a.path.join(".")}: ${a.message}`).join("; ");throw new Error(`Invalid graph: ${s}`)}return n.data}function mu(e){let t=e.map(r=>` "${r.name}"`).join(`,
278
- `),o=gu(e);return`// Generated by: ripplo generate-types
277
+ `,[Pa]);async function Yu(e){let t=Qu(),r=await Zu({config:t,params:e}),o=await ep({config:t,params:e});if(o==null)return W("No workflow. Provide --workflow <id>");let n=e.url??o.baseUrl,s=o.spec??(e.specPath==null?void 0:op(e.specPath));return r==null?W("No system prompt. Provide --agent-profile <id> or --prompt <text|file>"):{agentProfileId:e.agentProfileId,baseUrl:n,config:t,cookies:o.cookies,executedPreconditions:o.executedPreconditions,extraVariables:o.extraVariables,navigateTo:o.navigateTo,spec:s,systemPrompt:r,workflowContext:o.workflowContext,workflowId:o.workflowId}}function Qu(){let e=M();return e??W("Not logged in. Run: ripplo login")}async function Zu({config:e,params:t}){if(t.agentProfileId!=null&&e!=null)return Xu({config:e,profileId:t.agentProfileId});if(t.promptArg!=null)return rp(t.promptArg)}async function Xu({config:e,profileId:t}){let r=await $({config:e,document:Ju,variables:{id:t}});if(r.agentProfile==null)return W(`Agent profile not found: ${t}`);let o=r.agentProfile,n=o.description;return n==null||n.length===0?W(`Agent profile "${o.name}" has no description to use as system prompt`):(m.info("Using agent profile: %s",o.name),Ge({description:n,output:o.output??void 0,successCriteria:o.successCriteria??void 0}))}async function ep({config:e,params:t}){if(t.workflowId==null||e==null)return;let r=await tp(e),n={...fo(Pa,r),...e.baseUrl==null?{}:{baseUrl:e.baseUrl},...e.preconditionApiPath==null?{}:{preconditionApiPath:e.preconditionApiPath}},a=(n.workflows??[]).find(f=>fo(mo,f).id===t.workflowId);if(a==null)return W(`Workflow not found: ${t.workflowId}`);let i=fo(mo,a);m.info("Using workflow: %s",i.name);let l=await Pe({baseUrl:n.baseUrl,project:n,webhookSecret:e.webhookSecret,workflowSlug:i.slug}),c=i.spec==null?void 0:xa(i.spec),p={description:i.description,expectedOutcome:i.expectedOutcome,name:i.name};return{baseUrl:n.baseUrl,cookies:l.cookies,executedPreconditions:l.executed,extraVariables:l.data,navigateTo:l.navigateTo,spec:c,workflowContext:p,workflowId:i.id}}async function tp(e){let t=await $({config:e,document:Ku,variables:{projectId:e.projectId}});return t.project==null?W("Project not found. Check your config."):t.project}function rp(e){try{return va(e,"utf8")}catch{return e}}function op(e){let t=JSON.parse(va(e,"utf8"));return xa(t)}function xa(e){let t=ye(e);if(!t.success){let r=t.errors.map(o=>`${o.path}: ${o.message}`).join("; ");return W(`Invalid spec: ${r}`)}return t.data}$e();q();import ut from"fs";import Ue from"path";function Ta({graphPath:e,outputPath:t}){let r=sp(e),o=ap(r),n=Object.entries(o.preconditions).map(([l,c])=>({name:l,returns:c.returns}));if(n.length===0){m.warn("No preconditions found in graph. Nothing to generate.");return}let s=ip(n),a=np({graphPath:r,outputPath:t}),i=Ue.dirname(a);ut.existsSync(i)||ut.mkdirSync(i,{recursive:!0}),ut.writeFileSync(a,s),m.info("Generated %s with %d precondition(s)",a,n.length)}function np({graphPath:e,outputPath:t}){return t!=null?Ue.resolve(t):Ue.join(Ue.dirname(e),"..","generated","precondition-api.ts")}function sp(e){if(e!=null)return Ue.resolve(e);let t=Ue.join(process.cwd(),".ripplo","graph.json");if(!ut.existsSync(t))throw new Error("No .ripplo/graph.json found.");return t}function ap(e){let t=ut.readFileSync(e,"utf8"),r=JSON.parse(t),o=typeof r=="object"&&r!=null&&"_meta"in r?Object.fromEntries(Object.entries(r).filter(([s])=>s!=="_meta")):r,n=et.safeParse(o);if(!n.success){let s=n.error.issues.map(a=>`${a.path.join(".")}: ${a.message}`).join("; ");throw new Error(`Invalid graph: ${s}`)}return n.data}function ip(e){let t=e.map(o=>` "${o.name}"`).join(`,
278
+ `),r=lp(e);return`// Generated by: ripplo generate-types
279
279
  // Do not edit manually \u2014 regenerate when graph preconditions change.
280
280
 
281
281
  import { z } from "zod";
@@ -287,7 +287,7 @@ ${t},
287
287
  export type PreconditionName = (typeof preconditionNames)[number];
288
288
 
289
289
  // Strongly typed data returned by each precondition's execute response
290
- ${o}
290
+ ${r}
291
291
 
292
292
  // POST {preconditionApiPath}/check
293
293
  export const PreconditionCheckRequestSchema = z.object({
@@ -324,15 +324,15 @@ export const PreconditionTeardownResponseSchema = z.object({
324
324
  error: z.string().optional(),
325
325
  });
326
326
  export type PreconditionTeardownResponse = z.infer<typeof PreconditionTeardownResponseSchema>;
327
- `}function Js(e){return e.split(/[^a-zA-Z0-9]/).map(t=>{let o=t[0];return o==null?"":o.toUpperCase()+t.slice(1)}).join("")}function gu(e){let t=e.filter(n=>n.returns!=null&&n.returns.length>0);if(t.length===0)return"export type PreconditionDataMap = Record<PreconditionName, Record<string, string>>;";let o=t.map(n=>{let s=Js(n.name),a=n.returns.map(i=>` readonly ${i}: string;`).join(`
327
+ `}function Ca(e){return e.split(/[^a-zA-Z0-9]/).map(t=>{let r=t[0];return r==null?"":r.toUpperCase()+t.slice(1)}).join("")}function lp(e){let t=e.filter(n=>n.returns!=null&&n.returns.length>0);if(t.length===0)return"export type PreconditionDataMap = Record<PreconditionName, Record<string, string>>;";let r=t.map(n=>{let s=Ca(n.name),a=n.returns.map(i=>` readonly ${i}: string;`).join(`
328
328
  `);return`export interface ${s}Data {
329
329
  ${a}
330
- }`}),r=e.map(n=>{let a=n.returns!=null&&n.returns.length>0?`${Js(n.name)}Data`:"Record<string, never>";return` readonly "${n.name}": ${a};`});return[...o,"",`export interface PreconditionDataMap {
331
- ${r.join(`
330
+ }`}),o=e.map(n=>{let a=n.returns!=null&&n.returns.length>0?`${Ca(n.name)}Data`:"Record<string, never>";return` readonly "${n.name}": ${a};`});return[...r,"",`export interface PreconditionDataMap {
331
+ ${o.join(`
332
332
  `)}
333
333
  }`].join(`
334
334
 
335
- `)}U();import Ne from"fs";import It from"path";U();import wu from"crypto";import bu from"http";import{exec as Su}from"child_process";import{z as Ks}from"zod";var hu="https://ripplo.ai",Yo="https://ripplo-dev.up.railway.app",yu=Ks.object({RIPPLO_SERVER_URL:Ks.string().min(1).default(hu)}),Qs;function Zs(){return Qs??=yu.parse(process.env),Qs}var ku=`<!DOCTYPE html>
335
+ `)}q();import De from"fs";import zt from"path";q();import up from"crypto";import pp from"http";import{exec as fp}from"child_process";import{z as Ia}from"zod";var cp="https://ripplo.ai",ho="https://ripplo-dev.up.railway.app",dp=Ia.object({RIPPLO_SERVER_URL:Ia.string().min(1).default(cp)}),Aa;function Na(){return Aa??=dp.parse(process.env),Aa}var mp=`<!DOCTYPE html>
336
336
  <html lang="en">
337
337
  <head>
338
338
  <meta charset="utf-8" />
@@ -369,23 +369,23 @@ ${r.join(`
369
369
  </div>
370
370
  <script>setTimeout(function(){window.close()},3000)</script>
371
371
  </body>
372
- </html>`;async function vt({url:e}){let t=e??Zs().RIPPLO_SERVER_URL,o=wu.randomBytes(16).toString("hex"),{port:r,tokenPromise:n}=await Ru(o),s=`${t}/cli/authorize?port=${String(r)}&state=${encodeURIComponent(o)}`;u.info("Opening browser to authorize..."),u.info("If the browser doesn't open, visit: %s",s),Pu(s);let a=await n;u.info("Authorized successfully.");let i={cloudBaseUrl:"",projectId:"",ripploServerUrl:t,token:a};return ne(i),i}function Ru(e){return new Promise(t=>{let o,r=new Promise(s=>{o=s}),n=bu.createServer((s,a)=>{let i=new URL(s.url??"","http://localhost");if(i.pathname!=="/callback"){a.writeHead(404),a.end();return}let l=i.searchParams.get("state"),c=i.searchParams.get("token");if(l!==e){a.writeHead(400,{"Content-Type":"text/html"}),a.end("<html><body><h1>Invalid state parameter</h1></body></html>");return}if(c==null){a.writeHead(400,{"Content-Type":"text/html"}),a.end("<html><body><h1>Missing token</h1></body></html>");return}a.writeHead(200,{"Content-Type":"text/html"}),a.end(ku),n.close(),o(c)});n.listen(0,()=>{let s=n.address();if(s==null||typeof s=="string")throw new Error("Failed to get server address");t({port:s.port,tokenPromise:r})})})}function vu(){return process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open"}function Pu(e){let t=vu();Su(`${t} "${e}"`,()=>{})}U();import X from"fs";import Y from"path";import{fileURLToPath as ra}from"url";import{z as M}from"zod";import{McpServer as YS}from"@modelcontextprotocol/sdk/server/mcp.js";import{z as QS}from"zod";U();he();Ke();import{z as B}from"zod";var xu=B.object({additionalProperties:B.unknown().optional(),properties:B.record(B.string(),B.record(B.string(),B.unknown())).optional(),required:B.array(B.string()).optional(),type:B.string().optional()}),$b=B.object({oneOf:B.array(xu).optional()});function Tu(){return`---
372
+ </html>`;async function Wt({url:e}){let t=e??Na().RIPPLO_SERVER_URL,r=up.randomBytes(16).toString("hex"),{port:o,tokenPromise:n}=await hp(r),s=`${t}/cli/authorize?port=${String(o)}&state=${encodeURIComponent(r)}`;m.info("Opening browser to authorize..."),m.info("If the browser doesn't open, visit: %s",s),yp(s);let a=await n;m.info("Authorized successfully.");let i=M(),l=i==null?{cloudBaseUrl:"",projectId:"",ripploServerUrl:t,token:a,webhookSecret:""}:{cloudBaseUrl:i.cloudBaseUrl,projectId:i.projectId,ripploServerUrl:t,token:a,webhookSecret:i.webhookSecret};return ie(l),l}function hp(e){return new Promise(t=>{let r,o=new Promise(s=>{r=s}),n=pp.createServer((s,a)=>{let i=new URL(s.url??"","http://localhost");if(i.pathname!=="/callback"){a.writeHead(404),a.end();return}let l=i.searchParams.get("state"),c=i.searchParams.get("token");if(l!==e){a.writeHead(400,{"Content-Type":"text/html"}),a.end("<html><body><h1>Invalid state parameter</h1></body></html>");return}if(c==null){a.writeHead(400,{"Content-Type":"text/html"}),a.end("<html><body><h1>Missing token</h1></body></html>");return}a.writeHead(200,{"Content-Type":"text/html"}),a.end(mp),n.close(),r(c)});n.listen(0,()=>{let s=n.address();if(s==null||typeof s=="string")throw new Error("Failed to get server address");t({port:s.port,tokenPromise:o})})})}function gp(){return process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open"}function yp(e){let t=gp();fp(`${t} "${e}"`,()=>{})}q();import le from"fs";import ne from"path";import{fileURLToPath as Ua}from"url";import{z as X}from"zod";import{McpServer as Kk}from"@modelcontextprotocol/sdk/server/mcp.js";import{z as Qk}from"zod";q();Re();it();import{z as Z}from"zod";var wp=Z.object({additionalProperties:Z.unknown().optional(),properties:Z.record(Z.string(),Z.record(Z.string(),Z.unknown())).optional(),required:Z.array(Z.string()).optional(),type:Z.string().optional()}),$S=Z.object({oneOf:Z.array(wp).optional()});function bp(){return`---
373
373
 
374
374
  ## Referenced Schemas
375
375
 
376
- ${[Ae("Locator",k),Ae("StringValueRef",A),Ae("NumericValueRef",Re),Ae("ComparisonOperator",V),Ae("NumericOperator",de),Ae("Condition",ve)].join(`
376
+ ${[Fe("Locator",x),Fe("StringValueRef",U),Fe("NumericValueRef",Ie),Fe("ComparisonOperator",z),Fe("NumericOperator",ge),Fe("Condition",Ae)].join(`
377
377
 
378
- `)}`}var Eb=Tu();function Ae(e,t){return`### ${e}
378
+ `)}`}var ES=bp();function Fe(e,t){return`### ${e}
379
379
 
380
380
  \`\`\`json
381
- ${JSON.stringify(B.toJSONSchema(t),null,2)}
382
- \`\`\``}var Ob=["## try","","The `try` node uses a refinement: at least one of `catch` or `finally` is required.","","Fields: body (required), catch? (optional), finally? (optional)","Plus base fields: id, type, next?, timeout?, label?, comment?"].join(`
383
- `);U();import{graphql as Pt,readFragment as Wb}from"gql.tada";import Xs from"figures";var z={cross:Xs.cross,tick:Xs.tick};var Cu=Pt(`
381
+ ${JSON.stringify(Z.toJSONSchema(t),null,2)}
382
+ \`\`\``}var OS=["## try","","The `try` node uses a refinement: at least one of `catch` or `finally` is required.","","Fields: body (required), catch? (optional), finally? (optional)","Plus base fields: id, type, next?, timeout?, label?, comment?"].join(`
383
+ `);q();import{graphql as Lt,readFragment as _S}from"gql.tada";import ja from"figures";var te={cross:ja.cross,tick:ja.tick};var Sp=Lt(`
384
384
  fragment WorkflowIdMCP on Workflow {
385
385
  id
386
386
  slug
387
387
  }
388
- `),qb=Pt(`
388
+ `),qS=Lt(`
389
389
  query ProjectWorkflowIdsMCP($projectId: String!) {
390
390
  project(id: $projectId) {
391
391
  id
@@ -397,14 +397,14 @@ ${JSON.stringify(B.toJSONSchema(t),null,2)}
397
397
  }
398
398
  }
399
399
  }
400
- `,[Cu]),Bb=Pt(`
400
+ `,[Sp]),BS=Lt(`
401
401
  mutation CreateRunMCP($workflowId: String!, $platforms: [String!]!, $concurrency: Int!) {
402
402
  createRun(workflowId: $workflowId, platforms: $platforms, concurrency: $concurrency) {
403
403
  id
404
404
  status
405
405
  }
406
406
  }
407
- `),Mb=Pt(`
407
+ `),MS=Lt(`
408
408
  query RunStatusMCP($id: String!) {
409
409
  run(id: $id) {
410
410
  id
@@ -431,10 +431,10 @@ ${JSON.stringify(B.toJSONSchema(t),null,2)}
431
431
  }
432
432
  }
433
433
  }
434
- `);Te();import{z as Hb}from"zod";Te();_o();import Qb from"fs";import Xb from"path";import nS from"fs";import aS from"path";import{z as J}from"zod";var lS=J.object({baseUrl:J.string().optional(),cloudBaseUrl:J.string(),preconditionApiPath:J.string().optional(),projectId:J.string()});var cS=J.object({states:J.record(J.string(),J.object({preconditions:J.array(J.string())}))});Ke();var ea={assertAttribute:"assertion",assertChecked:"assertion",assertCookie:"assertion",assertCount:"assertion",assertDisabled:"assertion",assertEnabled:"assertion",assertFocused:"assertion",assertNotChecked:"assertion",assertNotVisible:"assertion",assertResponse:"assertion",assertText:"assertion",assertTitle:"assertion",assertUrl:"assertion",assertValue:"assertion",assertVisible:"assertion",check:"action",clear:"action",click:"action",clipboard:"other",dblclick:"action",drag:"action",extractText:"other",fail:"other",fill:"action",focus:"action",forEach:"controlFlow",goto:"other",group:"controlFlow",handleDialog:"action",hover:"action",if:"controlFlow",loop:"controlFlow",parallel:"controlFlow",press:"action",rightClick:"action",screenshot:"other",scroll:"action",scrollIntoView:"action",select:"action",setPermission:"other",setVariable:"other",setViewport:"other",try:"controlFlow",type:"action",uncheck:"action",upload:"action",wait:"other",waitFor:"other",waitForRequest:"other",waitForResponse:"other",waitForUrl:"other"},Iu=new Set,Au=new Set;Object.entries(ea).forEach(([e,t])=>{t==="assertion"&&Iu.add(e),t==="action"&&Au.add(e)});var Nu=new Set,ju=new Set;Object.entries(ea).forEach(([e,t])=>{t==="controlFlow"&&Nu.add(e),t==="assertion"&&ju.add(e)});var pS=["","## Review Instructions","Compare the **Declared Intent** against the **Workflow Steps** and answer these questions:","","1. Does the workflow actually test the **Expected Outcome**? Look at the assertions \u2014 do they verify that the expected outcome was achieved, or do they only check intermediate states?","2. Does the workflow exercise the flow described in **Description**? Are the right forms filled, buttons clicked, and pages navigated?","3. Are there assertions after the key state-changing action (e.g., after form submission, after deletion, after creation)? The final result should be verified, not just that a button was clicked.","4. If there are **Additional Checks**, does the workflow have assertions that cover them?","5. Could this workflow pass even if the feature is broken? For example, if it only asserts a page loaded but never checks the actual outcome.","","If any answer is NO, revise the workflow to address the gap. Then call `validate_workflow` and `review_workflow` again."].join(`
435
- `);he();Ke();import wS from"fs";import SS from"path";import PS from"fs";import TS from"path";var oa=["get_graph_documentation","get_node_schema","get_precondition_schema","get_spec_documentation","get_spec_patterns","review_workflow","run","validate_graph","validate_settings","validate_workflow"];var $u=M.looseObject({mcpServers:M.record(M.string(),M.unknown())});function xt(){let e=Y.join(process.cwd(),".mcp.json"),t=Eu()?{args:[Ou()],command:"node"}:Uu(),o=Lu(e),r={...o,mcpServers:{...o.mcpServers,ripplo:t}};X.writeFileSync(e,JSON.stringify(r,null,2)),u.info("Wrote MCP config to %s",e)}function Eu(){let e=ra(import.meta.url),t=Y.dirname(Y.dirname(e));return X.existsSync(Y.join(t,"tsup.config.ts"))}function Ou(){let e=ra(import.meta.url),t=Y.dirname(Y.dirname(e));return Y.join(t,"mcp","index.js")}function Uu(){return process.platform==="win32"?{args:["/c","npx","-y","--package","ripplo@latest","ripplo-mcp"],command:"cmd"}:{args:["-y","--package","ripplo@latest","ripplo-mcp"],command:"npx"}}var Fu=M.looseObject({permissions:M.looseObject({allow:M.array(M.string())}).optional()}),Vu=M.record(M.string(),M.looseObject({autoApproveTools:M.array(M.string()).optional()}));function na(){let e=process.cwd(),t=[];return X.existsSync(Y.join(e,".claude"))&&(Du(e),t.push(".claude/settings.json")),X.existsSync(Y.join(e,".vscode","cline_mcp_settings.json"))&&(Wu(e),t.push(".vscode/cline_mcp_settings.json")),t}function Du(e){let t=Y.join(e,".claude","settings.json"),o="mcp__ripplo__*",r=sa(t,Fu,{}),n=r.permissions?.allow??[];if(n.includes(o))return;let s={...r,permissions:{...r.permissions,allow:[...n,o]}};X.writeFileSync(t,JSON.stringify(s,null,2)+`
436
- `)}function Wu(e){let t=Y.join(e,".vscode","cline_mcp_settings.json"),o=sa(t,Vu,{}),r=o.ripplo??{},n={...o,ripplo:{...r,autoApproveTools:[...oa]}};X.writeFileSync(t,JSON.stringify(n,null,2)+`
437
- `)}function sa(e,t,o){if(!X.existsSync(e))return o;let r=JSON.parse(X.readFileSync(e,"utf8")),n=t.safeParse(r);return n.success?n.data:o}function Lu(e){if(!X.existsSync(e))return{mcpServers:{}};let t=JSON.parse(X.readFileSync(e,"utf8")),o=$u.safeParse(t);return o.success?o.data:{mcpServers:{}}}U();import _u from"path";import{input as Ko,select as qu}from"@inquirer/prompts";import{graphql as ia}from"gql.tada";var Bu=ia(`
434
+ `);$e();import{z as HS}from"zod";$e();ao();import QS from"fs";import XS from"path";import nk from"fs";import ak from"path";import{z as oe}from"zod";var lk=oe.object({baseUrl:oe.string().optional(),cloudBaseUrl:oe.string(),preconditionApiPath:oe.string().optional(),projectId:oe.string()});var ck=oe.object({states:oe.record(oe.string(),oe.object({preconditions:oe.array(oe.string())}))});it();var $a={assertAttribute:"assertion",assertChecked:"assertion",assertCookie:"assertion",assertCount:"assertion",assertDisabled:"assertion",assertEnabled:"assertion",assertFocused:"assertion",assertNotChecked:"assertion",assertNotVisible:"assertion",assertResponse:"assertion",assertText:"assertion",assertTitle:"assertion",assertUrl:"assertion",assertValue:"assertion",assertVisible:"assertion",check:"action",clear:"action",click:"action",clipboard:"other",dblclick:"action",drag:"action",extractText:"other",fail:"other",fill:"action",focus:"action",forEach:"controlFlow",goto:"other",group:"controlFlow",handleDialog:"action",hover:"action",if:"controlFlow",loop:"controlFlow",parallel:"controlFlow",press:"action",rightClick:"action",screenshot:"other",scroll:"action",scrollIntoView:"action",select:"action",setPermission:"other",setVariable:"other",setViewport:"other",try:"controlFlow",type:"action",uncheck:"action",upload:"action",wait:"other",waitFor:"other",waitForRequest:"other",waitForResponse:"other",waitForUrl:"other"},kp=new Set,vp=new Set;Object.entries($a).forEach(([e,t])=>{t==="assertion"&&kp.add(e),t==="action"&&vp.add(e)});var Rp=new Set,Pp=new Set;Object.entries($a).forEach(([e,t])=>{t==="controlFlow"&&Rp.add(e),t==="assertion"&&Pp.add(e)});var pk=["","## Review Instructions","Compare the **Declared Intent** against the **Workflow Steps** and answer these questions:","","1. Does the workflow actually test the **Expected Outcome**? Look at the assertions \u2014 do they verify that the expected outcome was achieved, or do they only check intermediate states?","2. Does the workflow exercise the flow described in **Description**? Are the right forms filled, buttons clicked, and pages navigated?","3. Are there assertions after the key state-changing action (e.g., after form submission, after deletion, after creation)? The final result should be verified, not just that a button was clicked.","4. If there are **Additional Checks**, does the workflow have assertions that cover them?","5. Could this workflow pass even if the feature is broken? For example, if it only asserts a page loaded but never checks the actual outcome.","","If any answer is NO, revise the workflow to address the gap. Then call `validate_workflow` and `review_workflow` again."].join(`
435
+ `);Re();it();import wk from"fs";import Sk from"path";import Pk from"fs";import Ck from"path";var Oa=["get_graph_documentation","get_node_schema","get_precondition_schema","get_spec_documentation","get_spec_patterns","review_workflow","run","validate_graph","validate_settings","validate_workflow"];var xp=X.looseObject({mcpServers:X.record(X.string(),X.unknown())});function qt(){let e=ne.join(process.cwd(),".mcp.json"),t=Cp()?{args:[Tp()],command:"node"}:Ip(),r=Ep(e),o={...r,mcpServers:{...r.mcpServers,ripplo:t}};le.writeFileSync(e,JSON.stringify(o,null,2)),m.info("Wrote MCP config to %s",e)}function Cp(){let e=Ua(import.meta.url),t=ne.dirname(ne.dirname(e));return le.existsSync(ne.join(t,"tsup.config.ts"))}function Tp(){let e=Ua(import.meta.url),t=ne.dirname(ne.dirname(e));return ne.join(t,"mcp","index.js")}function Ip(){return process.platform==="win32"?{args:["/c","npx","-y","--package","ripplo@latest","ripplo-mcp"],command:"cmd"}:{args:["-y","--package","ripplo@latest","ripplo-mcp"],command:"npx"}}var Ap=X.looseObject({permissions:X.looseObject({allow:X.array(X.string())}).optional()}),Np=X.record(X.string(),X.looseObject({autoApproveTools:X.array(X.string()).optional()}));function Fa(){let e=process.cwd(),t=[];return le.existsSync(ne.join(e,".claude"))&&(jp(e),t.push(".claude/settings.json")),le.existsSync(ne.join(e,".vscode","cline_mcp_settings.json"))&&($p(e),t.push(".vscode/cline_mcp_settings.json")),t}function jp(e){let t=ne.join(e,".claude","settings.json"),r="mcp__ripplo__*",o=Da(t,Ap,{}),n=o.permissions?.allow??[];if(n.includes(r))return;let s={...o,permissions:{...o.permissions,allow:[...n,r]}};le.writeFileSync(t,JSON.stringify(s,null,2)+`
436
+ `)}function $p(e){let t=ne.join(e,".vscode","cline_mcp_settings.json"),r=Da(t,Np,{}),o=r.ripplo??{},n={...r,ripplo:{...o,autoApproveTools:[...Oa]}};le.writeFileSync(t,JSON.stringify(n,null,2)+`
437
+ `)}function Da(e,t,r){if(!le.existsSync(e))return r;let o=JSON.parse(le.readFileSync(e,"utf8")),n=t.safeParse(o);return n.success?n.data:r}function Ep(e){if(!le.existsSync(e))return{mcpServers:{}};let t=JSON.parse(le.readFileSync(e,"utf8")),r=xp.safeParse(t);return r.success?r.data:{mcpServers:{}}}q();import Op from"path";import{input as go,select as Up}from"@inquirer/prompts";import{graphql as _a}from"gql.tada";var Fp=_a(`
438
438
  query ProjectsCLI {
439
439
  projects {
440
440
  id
@@ -443,7 +443,7 @@ ${JSON.stringify(B.toJSONSchema(t),null,2)}
443
443
  cloudBaseUrl
444
444
  }
445
445
  }
446
- `);async function Tt(e){let t=await T({config:e,document:Bu,variables:void 0});if(t.projects==null)throw new Error("Failed to fetch projects");return t.projects.map(o=>({baseUrl:o.baseUrl,cloudBaseUrl:o.cloudBaseUrl,id:o.id,name:o.name}))}var aa="__create_new__",Mu=ia(`
446
+ `);async function Bt(e){let t=await $({config:e,document:Fp,variables:void 0});if(t.projects==null)throw new Error("Failed to fetch projects");return t.projects.map(r=>({baseUrl:r.baseUrl,cloudBaseUrl:r.cloudBaseUrl,id:r.id,name:r.name}))}var Va="__create_new__",Dp=_a(`
447
447
  mutation CreateProjectShared(
448
448
  $name: String!
449
449
  $baseUrl: String!
@@ -462,12 +462,12 @@ ${JSON.stringify(B.toJSONSchema(t),null,2)}
462
462
  name
463
463
  }
464
464
  }
465
- `);async function Ct({config:e,projects:t}){if(t.length===1){let n=t[0];if(n==null)throw new Error("No project found");return u.info("Auto-selected project: %s",n.name),n}let o=[...t.map(n=>({name:n.name,value:n.id})),{name:"+ Create new project",value:aa}],r=await qu({choices:o,message:"Select a project:"});if(r!==aa){let n=t.find(s=>s.id===r);if(n==null)throw new Error("Selected project not found");return n}return Qo({config:e})}async function Qo({config:e}){let t=process.cwd(),o=_u.basename(t),r=await Ko({default:o,message:"Project name:"}),n=await Ko({default:"http://localhost:3000",message:"Base URL (local dev server):"}),s=await Ko({message:"Deployed environment URL (staging):"}),a=await T({config:e,document:Mu,variables:{baseUrl:n,cloudBaseUrl:s,name:r,provider:"local",repoUrl:t}});if(a.createProject==null)throw new Error("Failed to create project");return u.info("Created project: %s",a.createProject.name),{baseUrl:n,cloudBaseUrl:s,id:a.createProject.id,name:a.createProject.name}}async function la({url:e}){let t=await Gu({url:e});u.info("%s Logged in",z.tick);let o=await zu({config:t});u.info("%s Selected project: %s",z.tick,o.name),await new Promise(a=>{process.stderr.write("",()=>{a()})});let r=t.baseUrl??o.baseUrl,n={...t,baseUrl:r,cloudBaseUrl:o.cloudBaseUrl,projectId:o.id};ne(n),Ju(process.cwd()),u.info("%s Created .ripplo/",z.tick),xt(),u.info("%s Installed MCP config into .mcp.json",z.tick);let s=na();s.length>0&&u.info("%s Auto-allowlisted tools in %s",z.tick,s.join(", ")),Qt(),u.info("Starting dev mode..."),await Rt({concurrency:void 0,headed:!1})}async function Gu({url:e}){let t=_();return t??(u.info("Not logged in. Let's authenticate first."),vt({url:e}))}async function zu({config:e}){let t=await Tt(e);return t.length===0?Qo({config:e}):Ct({config:e,projects:t})}var Hu={edges:[],preconditions:{},states:{},version:3};function Ju(e){let t=It.join(e,".ripplo"),o=It.join(t,"graph.json"),r=It.join(t,"workflows");Ne.mkdirSync(r,{recursive:!0}),Ne.existsSync(o)||Ne.writeFileSync(o,JSON.stringify(Hu,null,2)+`
466
- `),Ku(e)}var Yu=[".ripplo/debug/",".ripplo/settings.local.json"];function Ku(e){let t=It.join(e,".gitignore");if(!Ne.existsSync(t))return;let o=Ne.readFileSync(t,"utf8"),r=Yu.filter(s=>!o.includes(s));if(r.length===0)return;let n=o.endsWith(`
465
+ `);async function Mt({config:e,projects:t}){if(t.length===1){let n=t[0];if(n==null)throw new Error("No project found");return m.info("Auto-selected project: %s",n.name),n}let r=[...t.map(n=>({name:n.name,value:n.id})),{name:"+ Create new project",value:Va}],o=await Up({choices:r,message:"Select a project:"});if(o!==Va){let n=t.find(s=>s.id===o);if(n==null)throw new Error("Selected project not found");return n}return yo({config:e})}async function yo({config:e}){let t=process.cwd(),r=Op.basename(t),o=await go({default:r,message:"Project name:"}),n=await go({default:"http://localhost:3000",message:"Base URL (local dev server):"}),s=await go({message:"Deployed environment URL (staging):"}),a=await $({config:e,document:Dp,variables:{baseUrl:n,cloudBaseUrl:s,name:o,provider:"local",repoUrl:t}});if(a.createProject==null)throw new Error("Failed to create project");return m.info("Created project: %s",a.createProject.name),{baseUrl:n,cloudBaseUrl:s,id:a.createProject.id,name:a.createProject.name}}async function Wa({url:e}){let t=await Vp({url:e});m.info("%s Logged in",te.tick);let r=await _p({config:t});m.info("%s Selected project: %s",te.tick,r.name),await new Promise(i=>{process.stderr.write("",()=>{i()})});let o=t.baseUrl??r.baseUrl,n=t.webhookSecret.length>0?t.webhookSecret:rt(),s={...t,baseUrl:o,cloudBaseUrl:r.cloudBaseUrl,projectId:r.id,webhookSecret:n};ie(s),Lp(process.cwd()),m.info("%s Created .ripplo/",te.tick),qt(),m.info("%s Installed MCP config into .mcp.json",te.tick);let a=Fa();a.length>0&&m.info("%s Auto-allowlisted tools in %s",te.tick,a.join(", ")),mr(),m.info("Starting dev mode..."),await _t({concurrency:void 0,headed:!1})}async function Vp({url:e}){let t=M();return t??(m.info("Not logged in. Let's authenticate first."),Wt({url:e}))}async function _p({config:e}){let t=await Bt(e);return t.length===0?yo({config:e}):Mt({config:e,projects:t})}var Wp={edges:[],preconditions:{},states:{},version:3};function Lp(e){let t=zt.join(e,".ripplo"),r=zt.join(t,"graph.json"),o=zt.join(t,"workflows");De.mkdirSync(o,{recursive:!0}),De.existsSync(r)||De.writeFileSync(r,JSON.stringify(Wp,null,2)+`
466
+ `),Bp(e)}var qp=[".ripplo/debug/",".ripplo/settings.local.json"];function Bp(e){let t=zt.join(e,".gitignore");if(!De.existsSync(t))return;let r=De.readFileSync(t,"utf8"),o=qp.filter(s=>!r.includes(s));if(o.length===0)return;let n=r.endsWith(`
467
467
  `)?"":`
468
- `;Ne.writeFileSync(t,o+n+r.join(`
468
+ `;De.writeFileSync(t,r+n+o.join(`
469
469
  `)+`
470
- `)}U();async function ca({url:e}){let t=await vt({url:e}),o=await Tt(t),r=await Ct({config:t,projects:o});ne({...t,projectId:r.id}),u.info("Logged in to project: %s",r.id),process.exit(0)}U();import{search as np}from"@inquirer/prompts";import ee from"chalk";import sp from"ora";he();U();import{graphql as At,readFragment as je}from"gql.tada";U();import{graphql as Qu}from"gql.tada";var Zu=Qu(`
470
+ `)}q();async function La({url:e}){let t=await Wt({url:e}),r=await Bt(t),o=await Mt({config:t,projects:r});ie({...t,projectId:o.id}),m.info("Logged in to project: %s",o.id),process.exit(0)}q();import{search as Qp}from"@inquirer/prompts";import ce from"chalk";import Zp from"ora";Re();q();import{graphql as Gt,readFragment as Ve}from"gql.tada";q();import{graphql as Mp}from"gql.tada";var zp=Mp(`
471
471
  mutation SubmitRunResultsCLI(
472
472
  $runId: String!
473
473
  $platform: String!
@@ -494,7 +494,7 @@ ${JSON.stringify(B.toJSONSchema(t),null,2)}
494
494
  status
495
495
  }
496
496
  }
497
- `);async function da({config:e,runId:t,steps:o}){let r=o.filter(i=>i.status==="passed").length,n=o.filter(i=>i.status==="failed").length,s=o.reduce((i,l)=>i+l.duration,0),a=n>0?"failed":"passed";await T({config:e,document:Zu,variables:{agentProfileId:null,duration:s,failCount:n,passCount:r,platform:"chromium",runId:t,status:a,steps:o,warnCount:0}})}var $e=At(`
497
+ `);async function qa({config:e,runId:t,steps:r}){let o=r.filter(i=>i.status==="passed").length,n=r.filter(i=>i.status==="failed").length,s=r.reduce((i,l)=>i+l.duration,0),a=n>0?"failed":"passed";await $({config:e,document:zp,variables:{agentProfileId:null,duration:s,failCount:n,passCount:o,platform:"chromium",runId:t,status:a,steps:r,warnCount:0}})}var _e=Gt(`
498
498
  fragment WorkflowCore on Workflow {
499
499
  id
500
500
  name
@@ -502,7 +502,7 @@ ${JSON.stringify(B.toJSONSchema(t),null,2)}
502
502
  source
503
503
  spec
504
504
  }
505
- `),ua=At(`
505
+ `),Ba=Gt(`
506
506
  fragment ProjectCore on Project {
507
507
  id
508
508
  name
@@ -526,17 +526,17 @@ ${JSON.stringify(B.toJSONSchema(t),null,2)}
526
526
  ...WorkflowCore
527
527
  }
528
528
  }
529
- `,[$e]),Xu=At(`
529
+ `,[_e]),Gp=Gt(`
530
530
  query ProjectCore($projectId: String!) {
531
531
  project(id: $projectId) {
532
532
  ...ProjectCore
533
533
  }
534
534
  }
535
- `,[ua]),ep=At(`
535
+ `,[Ba]),Hp=Gt(`
536
536
  mutation CreateRunCore($workflowId: String!, $platforms: [String!]!, $concurrency: Int!) {
537
537
  createRun(workflowId: $workflowId, platforms: $platforms, concurrency: $concurrency) {
538
538
  id
539
539
  }
540
540
  }
541
- `);async function pa({config:e,headed:t,onStep:o,workflowId:r,workflowName:n}){await qe({maxRuns:100});let s=await ma(e),a=s.workflows??[],i=tp({workflowId:r,workflowName:n,workflows:a}),l=je($e,i),c=op(l.spec),[p,f,h]=await Promise.all([L({label:"Preconditions resolved",fn:()=>ye({baseUrl:s.baseUrl,project:s,workflowSlug:l.slug})}),L({label:"Browser launched",fn:()=>re({headed:t})}),rp({config:e,workflowId:l.id})]),y=await L({label:"Spec executed",fn:()=>Me({baseUrl:s.baseUrl,browser:f,cookies:p.cookies,extraVariables:p.data,navigateTo:p.navigateTo,onStep:o,runId:h,spec:c})});await f.close(),await da({config:e,runId:h,steps:y}),p.apiUrl!=null&&await ze({apiUrl:p.apiUrl,cookies:p.cookies,executed:p.executed});let x=y.filter(S=>S.status==="passed").length,R=y.filter(S=>S.status==="failed").length;return{duration:y.reduce((S,j)=>S+j.duration,0),failed:R,passed:x,runId:h,steps:y,workflowName:l.name}}async function fa({config:e}){return((await ma(e)).workflows??[]).map(r=>je($e,r)).map(r=>({id:r.id,name:r.name,source:r.source}))}async function ma(e){let t=await T({config:e,document:Xu,variables:{projectId:e.projectId}});if(t.project==null)throw new Error("No project found. Check your config.");return{...je(ua,t.project),...e.baseUrl==null?{}:{baseUrl:e.baseUrl},...e.preconditionApiPath==null?{}:{preconditionApiPath:e.preconditionApiPath}}}function tp({workflowId:e,workflowName:t,workflows:o}){if(e!=null){let r=o.find(n=>je($e,n).id===e);if(r==null)throw new Error(`Workflow with ID "${e}" not found`);return r}if(t!=null){let r=o.find(n=>je($e,n).name.toLowerCase()===t.toLowerCase());if(r==null){let n=o.map(s=>je($e,s).name).join(", ");throw new Error(`Workflow "${t}" not found. Available: ${n}`)}return r}throw new Error("Either workflowId or workflowName must be provided")}function op(e){if(e==null)throw new Error("Workflow has no spec defined");let t=ue(e);if(!t.success){let o=t.errors.map(r=>`${r.path}: ${r.message}`).join("; ");throw new Error(`Invalid spec: ${o}`)}return t.data}async function rp({config:e,workflowId:t}){let o=await T({config:e,document:ep,variables:{concurrency:1,platforms:["chromium"],workflowId:t}});if(o.createRun==null)throw new Error("Failed to create run");return o.createRun.id}async function ga({headed:e,workflowId:t}){let o=_();if(o==null)return E("Not logged in. Run: ripplo login");let r=t??await ap(o);if(r==null)return E("No workflow selected.");let n=sp("Running workflow...").start(),s=await pa({config:o,headed:e,onStep:void 0,workflowId:r,workflowName:void 0});n.stop(),ip(s.steps)}async function ap(e){let o=(await fa({config:e})).map(r=>({name:`${r.name} (${r.source})`,value:r.id}));return np({message:"Select a workflow:",source:r=>r==null?o:o.filter(n=>n.name.toLowerCase().includes(r.toLowerCase()))})}function ip(e){let t=e.filter(n=>n.status==="passed").length,o=e.filter(n=>n.status==="failed").length,r=e.reduce((n,s)=>n+s.duration,0);u.info("Results:"),e.forEach(n=>{lp(n)}),u.info("%s, %s %s",ee.green(`${String(t)} passed`),ee.red(`${String(o)} failed`),ee.dim(`${String(r)}ms`))}function lp(e){let t=e.status==="passed"?ee.green(z.tick):ee.red(z.cross);u.info(" %s %s %s",t,e.title,ee.dim(`${String(e.duration)}ms`)),e.assertions.forEach(o=>{let r=o.status==="passed"?ee.green(z.tick):ee.red(z.cross),n=o.detail==null?"":ee.dim(` \u2014 ${o.detail}`);u.info(" %s %s%s",r,o.description,n)}),e.detail!=null&&u.info(" %s",ee.dim(e.detail))}U();function ha(){if(_()==null)return E("Not logged in. Run: ripplo login");xt(),u.info("Restart Claude Code to pick up the new MCP server."),process.exit(0)}U();import cp from"chalk";import{z as ya}from"zod";var wa="0.0.6",ba="ripplo",dp=ya.object({version:ya.string()});function Sa(){up().then(e=>{e==null||e===wa||u.info(cp.yellow(`Update available: ${wa} \u2192 ${e}
542
- Run \`npm install -g ${ba}\` to update`))}).catch(()=>{})}async function up(){let e=new AbortController,t=setTimeout(()=>{e.abort()},3e3);try{let o=await fetch(`https://registry.npmjs.org/${ba}/latest`,{headers:{accept:"application/json"},signal:e.signal});if(!o.ok)return;let r=await o.json();return dp.parse(r).version}catch{return}finally{clearTimeout(t)}}var Ra=Nt.resolve(Nt.dirname(pp(import.meta.url)),"..");ka({path:Nt.join(Ra,".env.local"),quiet:!0});ka({path:Nt.join(Ra,".env"),quiet:!0});async function fp(){Sa();let e=process.argv[2],t=e==null?void 0:vp[e];if(t==null){Pp();return}await t()}function mp(){let e=process.argv.slice(3),t=e.indexOf("--output"),o=t===-1?void 0:e[t+1];return{graphPath:e.find(n=>!n.startsWith("--")&&n!==o),outputPath:o}}function gp(){if(process.argv.includes("--dev"))return Yo;let e=process.argv.indexOf("--url");if(e!==-1)return process.argv[e+1]}function hp(){return ca({url:gp()})}function yp(){let e=process.argv.includes("--dev")?Yo:void 0;return la({url:e})}function wp(){let e=process.argv.includes("--headed"),t=process.argv.slice(3).find(o=>!o.startsWith("--"));return ga({headed:e,workflowId:t})}function bp(){let e=mp();Ys(e)}function Sp(){let e=process.argv.slice(3),t=kp(e);return t.agentProfileId==null&&t.promptArg==null?(u.error("Usage: ripplo agent-test (--agent-profile <id> | --prompt <text|file>) [--workflow <id> | --url <url>] [--spec <file>] [--headed]"),Promise.resolve()):Gs(t)}function kp(e){return{agentProfileId:tt(e,"--agent-profile"),headed:e.includes("--headed"),promptArg:tt(e,"--prompt"),specPath:tt(e,"--spec"),url:tt(e,"--url"),workflowId:tt(e,"--workflow")}}function tt(e,t){let o=e.indexOf(t);return o===-1?void 0:e[o+1]}function Rp(){let e=process.argv.slice(3),t=e.includes("--headed"),o=e.indexOf("--concurrency"),r=o===-1?void 0:Number(e[o+1]),n=r!=null&&Number.isFinite(r)&&r>0?r:void 0;return Rt({concurrency:n,headed:t})}var vp={"agent-test":Sp,dev:Rp,"generate-types":bp,init:yp,login:hp,run:wp,"setup-mcp":ha};function Pp(){u.info("Usage: ripplo <command>"),u.info(" login Authenticate with Ripplo"),u.info(" init Create a new project (no GitHub required)"),u.info(" run Execute a workflow spec via Playwright"),u.info(" dev Start dev mode: watch files + run workflows from the UI"),u.info(" agent-test Run an autonomous agent test locally"),u.info(" setup-mcp Configure MCP server in .mcp.json"),u.info(" generate-types Generate Zod schemas + TS types for precondition API")}fp().catch(e=>{u.error(e,"Unexpected error"),process.exit(1)});export{fp as main};
541
+ `);async function Ma({config:e,headed:t,onStep:r,workflowId:o,workflowName:n}){await Qe({maxRuns:100});let s=await Ga(e),a=s.workflows??[],i=Jp({workflowId:o,workflowName:n,workflows:a}),l=Ve(_e,i),c=Kp(l.spec),[p,f,u]=await Promise.all([K({label:"Preconditions resolved",fn:()=>Pe({baseUrl:s.baseUrl,project:s,webhookSecret:e.webhookSecret,workflowSlug:l.slug})}),K({label:"Browser launched",fn:()=>ue({headed:t})}),Yp({config:e,workflowId:l.id})]),h=await K({label:"Spec executed",fn:()=>Xe({baseUrl:s.baseUrl,browser:f,cookies:p.cookies,extraVariables:p.data,navigateTo:p.navigateTo,onStep:r,runId:u,spec:c})});await f.close(),await qa({config:e,runId:u,steps:h}),p.apiUrl!=null&&await ot({apiUrl:p.apiUrl,cookies:p.cookies,executed:p.executed,webhookSecret:e.webhookSecret});let g=h.filter(k=>k.status==="passed").length,b=h.filter(k=>k.status==="failed").length;return{duration:h.reduce((k,S)=>k+S.duration,0),failed:b,passed:g,runId:u,steps:h,workflowName:l.name}}async function za({config:e}){return((await Ga(e)).workflows??[]).map(o=>Ve(_e,o)).map(o=>({id:o.id,name:o.name,source:o.source}))}async function Ga(e){let t=await $({config:e,document:Gp,variables:{projectId:e.projectId}});if(t.project==null)throw new Error("No project found. Check your config.");return{...Ve(Ba,t.project),...e.baseUrl==null?{}:{baseUrl:e.baseUrl},...e.preconditionApiPath==null?{}:{preconditionApiPath:e.preconditionApiPath}}}function Jp({workflowId:e,workflowName:t,workflows:r}){if(e!=null){let o=r.find(n=>Ve(_e,n).id===e);if(o==null)throw new Error(`Workflow with ID "${e}" not found`);return o}if(t!=null){let o=r.find(n=>Ve(_e,n).name.toLowerCase()===t.toLowerCase());if(o==null){let n=r.map(s=>Ve(_e,s).name).join(", ");throw new Error(`Workflow "${t}" not found. Available: ${n}`)}return o}throw new Error("Either workflowId or workflowName must be provided")}function Kp(e){if(e==null)throw new Error("Workflow has no spec defined");let t=ye(e);if(!t.success){let r=t.errors.map(o=>`${o.path}: ${o.message}`).join("; ");throw new Error(`Invalid spec: ${r}`)}return t.data}async function Yp({config:e,workflowId:t}){let r=await $({config:e,document:Hp,variables:{concurrency:1,platforms:["chromium"],workflowId:t}});if(r.createRun==null)throw new Error("Failed to create run");return r.createRun.id}async function Ha({headed:e,workflowId:t}){let r=M();if(r==null)return W("Not logged in. Run: ripplo login");let o=t??await Xp(r);if(o==null)return W("No workflow selected.");let n=Zp("Running workflow...").start(),s=await Ma({config:r,headed:e,onStep:void 0,workflowId:o,workflowName:void 0});n.stop(),ef(s.steps)}async function Xp(e){let r=(await za({config:e})).map(o=>({name:`${o.name} (${o.source})`,value:o.id}));return Qp({message:"Select a workflow:",source:o=>o==null?r:r.filter(n=>n.name.toLowerCase().includes(o.toLowerCase()))})}function ef(e){let t=e.filter(n=>n.status==="passed").length,r=e.filter(n=>n.status==="failed").length,o=e.reduce((n,s)=>n+s.duration,0);m.info("Results:"),e.forEach(n=>{tf(n)}),m.info("%s, %s %s",ce.green(`${String(t)} passed`),ce.red(`${String(r)} failed`),ce.dim(`${String(o)}ms`))}function tf(e){let t=e.status==="passed"?ce.green(te.tick):ce.red(te.cross);m.info(" %s %s %s",t,e.title,ce.dim(`${String(e.duration)}ms`)),e.assertions.forEach(r=>{let o=r.status==="passed"?ce.green(te.tick):ce.red(te.cross),n=r.detail==null?"":ce.dim(` \u2014 ${r.detail}`);m.info(" %s %s%s",o,r.description,n)}),e.detail!=null&&m.info(" %s",ce.dim(e.detail))}q();function Ja(){if(M()==null)return W("Not logged in. Run: ripplo login");qt(),m.info("Restart Claude Code to pick up the new MCP server."),process.exit(0)}q();import rf from"chalk";import{z as Ka}from"zod";var Ya="0.0.7",Qa="ripplo",of=Ka.object({version:Ka.string()});function Za(){nf().then(e=>{e==null||e===Ya||m.info(rf.yellow(`Update available: ${Ya} \u2192 ${e}
542
+ Run \`npm install -g ${Qa}\` to update`))}).catch(()=>{})}async function nf(){let e=new AbortController,t=setTimeout(()=>{e.abort()},3e3);try{let r=await fetch(`https://registry.npmjs.org/${Qa}/latest`,{headers:{accept:"application/json"},signal:e.signal});if(!r.ok)return;let o=await r.json();return of.parse(o).version}catch{return}finally{clearTimeout(t)}}var ei=Ht.resolve(Ht.dirname(sf(import.meta.url)),"..");Xa({path:Ht.join(ei,".env.local"),quiet:!0});Xa({path:Ht.join(ei,".env"),quiet:!0});async function af(){Za();let e=process.argv[2],t=e==null?void 0:yf[e];if(t==null){wf();return}await t()}function lf(){let e=process.argv.slice(3),t=e.indexOf("--output"),r=t===-1?void 0:e[t+1];return{graphPath:e.find(n=>!n.startsWith("--")&&n!==r),outputPath:r}}function cf(){if(process.argv.includes("--dev"))return ho;let e=process.argv.indexOf("--url");if(e!==-1)return process.argv[e+1]}function df(){return La({url:cf()})}function uf(){let e=process.argv.includes("--dev")?ho:void 0;return Wa({url:e})}function pf(){let e=process.argv.includes("--headed"),t=process.argv.slice(3).find(r=>!r.startsWith("--"));return Ha({headed:e,workflowId:t})}function ff(){let e=lf();Ta(e)}function mf(){let e=process.argv.slice(3),t=hf(e);return t.agentProfileId==null&&t.promptArg==null?(m.error("Usage: ripplo agent-test (--agent-profile <id> | --prompt <text|file>) [--workflow <id> | --url <url>] [--spec <file>] [--headed]"),Promise.resolve()):Ra(t)}function hf(e){return{agentProfileId:pt(e,"--agent-profile"),headed:e.includes("--headed"),promptArg:pt(e,"--prompt"),specPath:pt(e,"--spec"),url:pt(e,"--url"),workflowId:pt(e,"--workflow")}}function pt(e,t){let r=e.indexOf(t);return r===-1?void 0:e[r+1]}function gf(){let e=process.argv.slice(3),t=e.includes("--headed"),r=e.indexOf("--concurrency"),o=r===-1?void 0:Number(e[r+1]),n=o!=null&&Number.isFinite(o)&&o>0?o:void 0;return _t({concurrency:n,headed:t})}var yf={"agent-test":mf,dev:gf,"generate-types":ff,init:uf,login:df,run:pf,"setup-mcp":Ja};function wf(){m.info("Usage: ripplo <command>"),m.info(" login Authenticate with Ripplo"),m.info(" init Create a new project (no GitHub required)"),m.info(" run Execute a workflow spec via Playwright"),m.info(" dev Start dev mode: watch files + run workflows from the UI"),m.info(" agent-test Run an autonomous agent test locally"),m.info(" setup-mcp Configure MCP server in .mcp.json"),m.info(" generate-types Generate Zod schemas + TS types for precondition API")}af().catch(e=>{m.error(e,"Unexpected error"),process.exit(1)});export{af as main};