ripplo 0.7.61 → 0.7.62

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.
@@ -1,139 +0,0 @@
1
- #!/usr/bin/env node
2
- import { createRequire as __ripploCreateRequire } from "node:module";
3
- const require = globalThis.require ?? __ripploCreateRequire(import.meta.url);
4
- import{$ as F,A as De,B as He,D as qe,E as b,F as I,G as Ue,H as $,I as Me,K as _e,L as $e,M as C,O as Fe,P as Oe,Q as Ne,R as je,S as Be,T,V as Ke,W as Ge,X as ze,Z as Je,_ as Qe,b as ee,f as ae,i as v,n as Se,p as we,r as ve,u as Ie,v as Ce,w as Te,x as Le,y as We,z as Ae}from"./chunk-7C6PFZJF.js";import{e as ye,f as ge}from"./chunk-ZPCVY23H.js";import{a as re,d as R,e as ie,f as M,i as _,s as E,u as he}from"./chunk-LHXEVZIV.js";import{d as X,e as y,f as s,g as U,h as Z}from"./chunk-PXYDLKAG.js";import{$ as de,ba as ce,ca as ue,da as pe,ea as fe,f as oe,fa as me,i as ne,m as te,pa as ke,qa as xe,ra as Pe,sa as Re,ta as Ee,u as se,va as be,y as le}from"./chunk-6SKODQ54.js";import"./chunk-63TU4VJ7.js";import kn from"path";import{createClient as xn}from"graphql-sse";import Pn,{AbortError as Rn}from"p-retry";import{graphql as V}from"gql.tada";import{graphql as Gr}from"gql.tada";import{print as zr}from"graphql";async function Ve({config:e,cwd:r,headed:o,pool:n,runId:t,signal:i,testSlug:a,workClass:l,workflowSlug:d}){let c=await R(r);if(c.isErr())return await T(e,t,`lockfile:${c.error.kind}`),{kind:"dispatch-error",reason:{detail:`lockfile:${c.error.kind}`,type:"generic"}};let p=Kr(c.value,{testSlug:a,workflowSlug:d});if(p==null)return await T(e,t,`no-test:${d}/${a}`),{kind:"dispatch-error",reason:{detail:`no-test:${d}/${a}`,type:"generic"}};let u=await b({headed:o,workClass:l,task:()=>n.execute({headed:o,runId:t,testRef:p},i)});return!u.serverNotified&&u.outcome.kind==="error"&&await T(e,t,u.outcome.detail),u.outcome}function Kr(e,{testSlug:r,workflowSlug:o}){let t=e.workflows.find(i=>te(i.name)===o)?.tests.find(i=>i.slug===r);return t==null?void 0:se(t)}var Jr=6e4,Qr=Gr(`
5
- subscription RunRequestedWatch($devSessionId: String!) {
6
- runRequested(devSessionId: $devSessionId) {
7
- runId
8
- testSlug
9
- workflowId
10
- workflowSlug
11
- }
12
- }
13
- `);async function Ye(e){let r=Math.min(1e3*2**e,Jr)+Xr();await new Promise(o=>setTimeout(o,r))}function Xe({claim:e,cwd:r,devSessionId:o,onSubscriptionDead:n,pool:t,sseClient:i,sseHealth:a}){let l=new Set;return i.subscribe({query:zr(Qr),variables:{devSessionId:o}},{complete:()=>{},error:d=>{let c=d instanceof Error?d.message:String(d);s.warn("runRequested SSE failed: %s; re-registering session",c),n(c)},next:d=>{Vr({claim:e,cwd:r,event:d.data?.runRequested,inFlightRunIds:l,pool:t})}},{connected:()=>{a.onConnected()},connecting:d=>{a.onConnecting(d),d&&s.debug("runRequested SSE reconnecting")}})}function Vr({claim:e,cwd:r,event:o,inFlightRunIds:n,pool:t}){if(o==null)return;if(n.has(o.runId)){s.warn({runId:o.runId,workflowSlug:o.workflowSlug},"duplicate runRequested event; skipping dispatch");return}n.add(o.runId),process.stdout.write(`ripplo: run ${o.workflowSlug}
14
- `),ee(r);let i=v(r).match(l=>l,l=>{s.error({failure:l,runId:o.runId},"failed to load env for run dispatch; skipping")});if(i==null){n.delete(o.runId);return}let a=Yr(e(o.runId),o);a.started(),Ve({config:i,cwd:r,headed:a.headed,pool:t,runId:o.runId,signal:a.signal,testSlug:o.testSlug,workClass:a.workClass,workflowSlug:o.workflowSlug}).then(l=>{a.finished(l)}).catch(l=>{s.error({err:l,runId:o.runId,workflowSlug:o.workflowSlug},"run execution failed; daemon continuing"),a.finished({detail:l instanceof Error?l.message:String(l),kind:"error"})}).finally(()=>{n.delete(o.runId)})}function Yr(e,r){return e==null?(s.debug({runId:r.runId,workflowSlug:r.workflowSlug},"dispatching unclaimed run (externally triggered or replayed)"),{headed:!1,signal:new AbortController().signal,workClass:"p0-ui",finished:()=>{},started:()=>{}}):{headed:e.headed,signal:Oe(e.token),workClass:"p1-cli",finished:o=>{e.finished(r.runId,o)},started:()=>{e.started(r.runId)}}}function Xr(){return Math.floor(Math.random()*2700)+300}import{graphql as O}from"gql.tada";import{print as Zr}from"graphql";var eo=O(`
15
- subscription TeleportRequestedWatch($devSessionId: String!) {
16
- teleportRequested(devSessionId: $devSessionId) {
17
- runId
18
- stepIndex
19
- kind
20
- testSlug
21
- workflowSlug
22
- }
23
- }
24
- `),ro=O(`
25
- query TeleportRunRepro($id: String!) {
26
- run(id: $id) {
27
- id
28
- reproJson
29
- }
30
- }
31
- `),oo=O(`
32
- mutation ReportTeleportResult($devSessionId: String!, $runId: String!, $status: String!) {
33
- reportTeleportResult(devSessionId: $devSessionId, runId: $runId, status: $status)
34
- }
35
- `);function Ze({cwd:e,devSessionId:r,onSubscriptionDead:o,sseClient:n}){let t=new Set,i=n.subscribe({query:Zr(eo),variables:{devSessionId:r}},{complete:()=>{},error:a=>{let l=a instanceof Error?a.message:String(a);s.warn("teleportRequested SSE failed: %s; re-registering session",l),o(l)},next:a=>{no({cwd:e,devSessionId:r,event:a.data?.teleportRequested,running:t})}});return()=>{t.forEach(a=>{a.abort()}),t.clear(),i()}}function no({cwd:e,devSessionId:r,event:o,running:n}){if(o==null)return;let t=new AbortController;n.add(t),to({cwd:e,devSessionId:r,event:o,signal:t.signal}).catch(i=>{s.error({err:i},"teleport failed; daemon continuing")}).finally(()=>{n.delete(t)})}async function to({cwd:e,devSessionId:r,event:o,signal:n}){let t=d=>io({cwd:e,devSessionId:r,runId:o.runId,status:d}),i=await ao(e,o);if(i==null){s.warn({runId:o.runId},"teleport could not resolve target"),await t("unplannable");return}process.stdout.write(`ripplo: teleport ${lo(o)} step ${String(o.stepIndex+1)}
36
- `);let l=await Je({cwd:e,onReady:()=>{t("opened")},signal:n,step:o.stepIndex+1,target:i});l.kind==="done"&&l.result.kind==="handed-over"||(s.warn({kind:l.kind,runId:o.runId},"teleport could not open"),await t(l.kind==="unplannable"?"unplannable":"error"))}async function io({cwd:e,devSessionId:r,runId:o,status:n}){let t=v(e).match(i=>i,()=>null);t!=null&&await y({config:t,document:oo,variables:{devSessionId:r,runId:o,status:n}}).catch(()=>null)}async function ao(e,r){if(r.kind==="explore"){let o=await so(e,r.runId);return o==null?null:{kind:"explore",repro:o}}return r.testSlug==null||r.workflowSlug==null?null:{kind:"test",ref:`${r.workflowSlug}/${r.testSlug}`}}async function so(e,r){let o=v(e).match(t=>t,()=>null);if(o==null)return null;let n=await y({config:o,document:ro,variables:{id:r}}).catch(()=>null);return n?.run?.reproJson==null?null:ce.parse(JSON.parse(n.run.reproJson))}function lo(e){return e.kind==="explore"?"explore finding":`${String(e.workflowSlug)}/${String(e.testSlug)}`}function er(){let e=!0,r,o=null,n=()=>{o!=null&&(clearTimeout(o),o=null)};return{markUnhealthy:t=>{e=!1,r=t,n()},onConnected:()=>{n(),o=setTimeout(()=>{e=!0,r=void 0,o=null},1e4)},onConnecting:()=>{n()},snapshot:()=>({detail:r,ok:e})}}import co from"fs";import tr from"net";import{err as ir,ok as uo}from"neverthrow";async function ar({cwd:e,onConnection:r}){Z(e);let o=he(e),n=await rr({onConnection:r,socketPath:o});return n.isOk()||n.error.kind!=="stale-candidate"?n.map(or(o)).mapErr(nr(o)):await po(o)?ir({kind:"already-running",socketPath:o}):(sr(o),(await rr({onConnection:r,socketPath:o})).map(or(o)).mapErr(nr(o)))}function po(e){return new Promise(r=>{let o=tr.connect(e);o.once("connect",()=>{o.destroy(),r(!0)}),o.once("error",()=>{r(!1)})})}async function rr(e){let r=await fo(e);return r.kind==="listening"?uo(r.server):ir(r.error)}function fo({onConnection:e,socketPath:r}){return new Promise(o=>{let n=tr.createServer(e);n.once("error",t=>{o({error:t.code==="EADDRINUSE"?{kind:"stale-candidate"}:{kind:"listen-failed",message:t.message},kind:"failed"})}),n.listen(r,()=>{o({kind:"listening",server:n})})})}function or(e){return r=>({socketPath:e,close:()=>{r.close(),sr(e)}})}function sr(e){co.rmSync(e,{force:!0})}function nr(e){return r=>r.kind==="stale-candidate"?{kind:"already-running",socketPath:e}:{kind:"bind-failed",message:r.message}}import{randomInt as mo,randomUUID as yo}from"crypto";function dr(e){let r={attempts:0,consecutiveErrors:0,driverBackoffUntil:0,findings:0,lastUnhealthyReportMs:0,lockfile:null,prepared:null,preparing:!1,refreshing:!1,windowAttempts:0,windowFindings:0,windowStartMs:Date.now()},o=N(e,r);return{priority:"p3",next:()=>xo(e,r),onResult:()=>{},ready:()=>o,status:()=>({attempts:r.attempts,findings:r.findings}),stop:()=>Promise.resolve()}}var go=10;async function N(e,r){if(!r.preparing){r.preparing=!0;try{let o=await e.loadLockfile(),n=o==null?null:await So(o);if(n==null||o==null)return;r.lockfile=o.lockfile,r.prepared=n,j(r),e.notifyWork()}finally{r.preparing=!1}}}async function So({lockfile:e,rawHash:r}){let o=await pe(e);return o==null?null:{exploration:o,lockfileHashValue:r,strategy:de("even")}}var wo=6,ho=3e4,vo=2e4;function j(e){e.consecutiveErrors=0,e.driverBackoffUntil=0,e.lastUnhealthyReportMs=0}async function ko(e,r){if(!(r.refreshing||r.preparing||r.prepared==null)){r.refreshing=!0;try{let o=await e.loadLockfile();if(o==null||o.rawHash===r.prepared.lockfileHashValue)return;s.info("workflow definitions changed, re-preparing exploration"),r.prepared=null,await N(e,r)}finally{r.refreshing=!1}}}function xo(e,r){ko(e,r);let o=r.prepared;if(o==null||Date.now()<r.driverBackoffUntil)return null;let n=fe({lockfileHash:o.lockfileHashValue,prepared:o.exploration,random:Po,strategy:{...o.strategy,maxAttemptLength:e.maxTrailLength()}});if(n==null)return null;let t=n.baseStateTest.name;return{id:`explore:${yo()}`,label:t,run:i=>Ro({assign:n,params:e,signal:i,state:r})}}var lr=2**31;function Po(){return mo(lr)/lr}async function Ro({assign:e,params:r,signal:o,state:n}){if(!await r.probeApp()){cr({params:r,reason:"app-unreachable",state:n});return}let t=await r.executeTrail(e,o);if(t.kind==="aborted")return;if(t.kind==="error"){bo({params:r,reason:t.reason,state:n});return}j(n),n.attempts+=1,n.windowAttempts+=1;let i=t.kind==="finding";i&&(n.findings+=1,n.windowFindings+=1,s.info("exploration finding recorded")),r.reportProgress({attempts:1,findings:i?1:0,result:t}),n.windowAttempts>=go&&Eo(n)}function Eo(e){let r=Date.now()-e.windowStartMs;s.info({attempts:e.windowAttempts,avgTrailMs:Math.round(r/e.windowAttempts),findings:e.windowFindings,windowMs:r,yield:Number((e.windowFindings/e.windowAttempts).toFixed(3))},"explore window"),e.windowAttempts=0,e.windowFindings=0,e.windowStartMs=Date.now()}function bo({params:e,reason:r,state:o}){if(r?.startsWith("lockfile:daemon-load-failed")===!0){Io(e,o);return}cr({params:e,reason:r,state:o})}function Io(e,r){r.preparing||(r.prepared=null,N(e,r))}function cr({params:e,reason:r,state:o}){let n=To(r);if(n==="trail"){j(o);return}o.consecutiveErrors+=1,s.debug("exploration infra error: %s",r),!(o.consecutiveErrors<wo)&&(n==="driver"&&(o.driverBackoffUntil=Date.now()+ho),Co({params:e,reason:r,state:o}))}function Co({params:e,reason:r,state:o}){let n=Date.now();n-o.lastUnhealthyReportMs<vo||(o.lastUnhealthyReportMs=n,s.warn("exploration unhealthy after %d consecutive infra errors (last: %s)",o.consecutiveErrors,r),e.reportUnhealthy())}function To(e){if(e==null||e==="error"||e==="app-unreachable"||e.startsWith("transport:"))return"infra";if(e.startsWith("runtime:")){let r=e.slice(8);return r==="driver-launch"?"driver":le(r)?"infra":"trail"}return"trail"}function B(e){return{priority:e,next:()=>null,onResult:()=>{}}}function ur({config:e,executorIsLocal:r,pool:o}){return Ao({appUrl:e.appUrl,cwd:e.cwd,executorIsLocal:r,executeTrail:async(n,t)=>(await o).exploreTrail(n,t)})}function Ao({appUrl:e,cwd:r,executeTrail:o,executorIsLocal:n}){let t={concurrency:2,enabled:!1,maxTrailLength:12},i={notify:()=>{}},a={report:p=>{}},l={report:()=>{}},d=Do({appUrl:e,cwd:r,executeTrail:o,maxTrailLength:()=>t.maxTrailLength,notifyWork:()=>{i.notify()},reportProgress:p=>{a.report(p)},reportUnhealthy:()=>{l.report()}}),c=ve({now:Date.now,probe:qo,setTimer:Uo,sources:[B("p0"),B("p1"),d],execute:({job:p,priority:u,signal:f})=>b({headed:!1,workClass:Mo(u),task:()=>p.run(f)}),exploreConcurrency:()=>t.concurrency,exploreEnabled:()=>t.enabled&&n()});return $(()=>{c.notifyQueueChange()}),i.notify=()=>{c.notifyQueueChange()},{notifyExecutorChanged:()=>{c.notifyQueueChange()},progress:()=>d.status(),setConcurrency:p=>{n()&&p!==t.concurrency&&s.info({workers:p},"explore local worker count changed"),t.concurrency=p,c.notifyQueueChange()},setEnabled:p=>{t.enabled=p,c.notifyQueueChange()},setMaxTrailLength:p=>{t.maxTrailLength=p},setReportProgress:p=>{a.report=p},setReportUnhealthy:p=>{l.report=p},status:()=>({explorer:Ho(t.enabled,c.stalled()),exploring:c.explorationActive(),progress:d.status()}),stop:()=>{c.stop(),$(null),d.stop()}}}function Do({appUrl:e,cwd:r,executeTrail:o,maxTrailLength:n,notifyWork:t,reportProgress:i,reportUnhealthy:a}){return dr({cwd:r,executeTrail:o,maxTrailLength:n,notifyWork:t,reportProgress:i,reportUnhealthy:a,loadLockfile:async()=>{let{fingerprint:l,result:d}=await ie(r),c=await C(r);return c==null?null:d.match(async p=>({fingerprint:l,lockfile:await E(r,p),rawHash:c}),()=>Promise.resolve(null))},probeApp:async()=>await Se(e)==null})}function Ho(e,r){return e?r>0?"stalled":"on":"off"}function qo(){let e=Ue();return{headedActive:e.headedActive,interactiveActive:e.active,interactiveQueued:e.queued,poolSize:e.poolSize}}function Uo(e,r){let o=setTimeout(e,r);return()=>{clearTimeout(o)}}function Mo(e){switch(e){case"p0":return"p0-ui";case"p1":return"p1-cli";case"p2":return"p2-cover";case"p3":return"p3-explore"}}import{graphql as Zo}from"gql.tada";import{connect as $o}from"net";import Fo from"ssh2";import{WebSocket as fr,createWebSocketStream as Oo}from"ws";var _o="ripplo-";function K(e){return Object.entries(e).map(([r,o])=>`${_o}${r}.${o}`)}var{Server:No,utils:pr}=Fo;function mr(){let e=pr.generateKeyPairSync("ed25519"),r=pr.parseKey(e.private);if(r instanceof Error)throw r;return{fingerprint:r.getPublicSSH().toString("base64"),privateKey:e.private}}function yr(e){return new Promise((r,o)=>{let n={closers:new Set,stopped:!1},t=new fr(e.relayUrl,K({grant:e.grant,role:"daemon-control"}));t.on("open",()=>{s.info("cloud-executor relay control up"),r({stop:jo(t,n)})}),t.on("message",i=>{Bo(e,n,i)}),t.on("close",(i,a)=>{n.stopped||s.warn({code:i,reason:a.toString()},"relay control closed"),Xo(e,n)}),t.on("error",i=>{o(i instanceof Error?i:new Error(String(i)))})})}function jo(e,r){return()=>(r.stopped=!0,r.closers.forEach(o=>{o()}),e.close(),Promise.resolve())}function Bo(e,r,o){let n=Ko(o);n!=null&&zo(e,r,n.pipeId)}function Ko(e){try{let r=JSON.parse(Go(e));return typeof r=="object"&&r!=null&&"signal"in r&&r.signal==="open-data"&&"pipeId"in r&&typeof r.pipeId=="string"?{pipeId:r.pipeId}:null}catch{return null}}function Go(e){return Buffer.isBuffer(e)?e.toString("utf8"):Array.isArray(e)?Buffer.concat(e).toString("utf8"):Buffer.from(e).toString("utf8")}function zo(e,r,o){if(r.stopped)return;let n=new fr(e.relayUrl,K({pipeId:o,role:"daemon-data"}));n.on("open",()=>{Jo(e,r,n)}),n.on("error",t=>{s.warn({err:t},"cloud-executor relay data pipe error")})}function Jo(e,r,o){let n=Oo(o);n.on("error",()=>{});let t=new No({hostKeys:[e.hostKey.privateKey]},a=>{a.on("authentication",l=>{Vo(l,e.secret)}),a.on("ready",()=>{a.on("tcpip",(l,d,c)=>{Yo({accept:l,allowedPorts:e.allowedPorts,deny:d,destPort:c.destPort})})})}),i=()=>{o.close()};r.closers.add(i),o.on("close",()=>r.closers.delete(i)),Qo(t,n)}function Qo(e,r){e.injectSocket(r)}function Vo(e,r){if(e.method==="password"&&e.password===r){e.accept();return}if(e.method==="none"){e.reject(["password"]);return}e.reject()}function Yo({accept:e,allowedPorts:r,deny:o,destPort:n}){if(!r.includes(n)){o();return}let t=!1,i=$o({autoSelectFamily:!0,host:"localhost",port:n},()=>{t=!0;let a=e();a.on("error",()=>{}),i.pipe(a).pipe(i)});i.on("error",()=>{t||o()})}function Xo(e,r){r.stopped||(r.stopped=!0,r.closers.forEach(o=>{o()}),e.onFatal())}var en=Zo(`
37
- mutation EnterCloudMode(
38
- $devSessionId: String!
39
- $localUrl: String!
40
- $engineUrl: String!
41
- $hostKeyFingerprint: String!
42
- ) {
43
- enterCloudMode(
44
- devSessionId: $devSessionId
45
- localUrl: $localUrl
46
- engineUrl: $engineUrl
47
- hostKeyFingerprint: $hostKeyFingerprint
48
- ) {
49
- __typename
50
- ... on RelaySession {
51
- generation
52
- grant
53
- relayUrl
54
- secret
55
- session
56
- }
57
- ... on DevSessionEndedError {
58
- message
59
- }
60
- ... on TunnelNotConfiguredError {
61
- message
62
- }
63
- }
64
- }
65
- `),L=class extends Error{failure;constructor(r){super(r.kind),this.failure=r}};async function G({config:e,devSessionId:r,onFatal:o}){let n=mr(),i=(await y({config:e,document:en,variables:{devSessionId:r,engineUrl:e.engineUrl,hostKeyFingerprint:n.fingerprint,localUrl:e.appUrl}})).enterCloudMode;if(i==null)throw new L({kind:"empty-response"});if(i.__typename!=="RelaySession")throw new L({kind:"server-error",typename:i.__typename});let a=await yr({allowedPorts:[...new Set([gr(e.appUrl),gr(e.engineUrl)])],grant:i.grant,hostKey:n,onFatal:o,relayUrl:i.relayUrl,secret:i.secret});return s.info({session:i.session},"cloud-executor relay up"),{stop:a.stop}}function gr(e){let r=new URL(e);return r.port.length>0?Number(r.port):r.protocol==="https:"?443:80}var rn=[1e3,3e3,8e3,15e3];function Sr({config:e,onChanged:r}){let o={devSessionId:null,mode:"local",queue:Promise.resolve(),tunnel:void 0},n=()=>{o.tunnel=void 0,i(0)},t=()=>o.mode==="cloud",i=async u=>{let f=o.devSessionId;if(!t()||f==null)return;let m=rn[u];if(m==null){s.warn("tunnel connector gave up; reverting executor to local"),p("local"),F(e,"local");return}if(s.warn({attempt:u+1},"relay tunnel dropped; reconnecting"),await new Promise(w=>setTimeout(w,m)),!(!t()||o.tunnel!=null))try{let w=await G({config:e,devSessionId:f,onFatal:n});if(!t()){await w.stop();return}o.tunnel=w,s.info("relay tunnel reconnected")}catch{i(u+1)}},a=async u=>{let f=await G({config:e,devSessionId:u,onFatal:n});o.tunnel=f,o.mode="cloud",s.info("executor switched to cloud"),r()},l=async()=>{let u=o.tunnel;o.tunnel=void 0,o.mode="local",u!=null&&await u.stop(),s.info("executor switched to local"),r()},d=async u=>{let f=o.devSessionId;if(!(f==null||u===o.mode)){if(u==="cloud"){await a(f);return}await l()}},c=async u=>{s.warn({err:u},"executor switch failed; staying local"),await F(e,"local").catch(()=>{})},p=u=>{o.queue=o.queue.then(()=>d(u).catch(c))};return{request:p,connect:u=>{o.devSessionId=u},current:()=>o.mode,stop:async()=>{await o.queue.catch(()=>{}),await d("local")}}}import{readdir as on}from"fs/promises";import{existsSync as wr}from"fs";import z from"path";async function hr({config:e,cwd:r}){let o=z.join(r,".ripplo","debug");await(await on(o,{withFileTypes:!0}).catch(()=>[])).filter(i=>i.isDirectory()).map(i=>i.name).filter(i=>!i.startsWith("replay-")&&!i.startsWith("explore-")&&!wr(z.join(o,i,je))&&wr(z.join(o,i,"behavior.jsonl"))).reduce((i,a)=>i.then(()=>Be({config:e,debugDir:o,runId:a}).catch(()=>{})),Promise.resolve(void 0))}import{fork as nn}from"child_process";import vr from"os";import{CancellationTokenSource as kr,ResponseError as xr}from"vscode-jsonrpc/node";function Pr(e,r){return()=>{let o=nn(e,["run-worker"],{cwd:r,detached:!0,stdio:["ignore","inherit","inherit","ipc"]});return{connection:He(o),kill:()=>{tn(o)},onExit:n=>{o.once("exit",n)}}}}function Rr(e){let r={closed:!1,devSessionId:e.devSessionId,lockfileProvider:e.lockfileProvider,nextId:0,size:e.initialSize,spawn:e.spawn,waiters:[],workers:[]};return Cr(r),{close:async()=>{r.closed=!0,await Promise.all([...r.workers].map(o=>J(o,r)))},execute:(o,n)=>ln(o,n,r),exploreTrail:(o,n)=>cn(o,n,r),routeSpan:(o,n)=>{let t=r.workers.find(i=>i.runId===o);t?.worker.connection.sendNotification(Ae,{runId:o,span:n})},setSize:o=>{pn(o,r)}}}function tn(e){let r=e.pid;if(r!=null)try{process.kill(-r,"SIGKILL")}catch{e.kill("SIGKILL")}}var an=1e4,sn=1e4,Er=-32800;async function ln(e,r,o){let n=await br(o);if(n.runId=e.runId,!n.alive)return W(n,o),{outcome:{detail:"worker-exit",kind:"error"},serverNotified:!1};let t=new kr,i=()=>{t.cancel()};r.aborted&&t.cancel(),r.addEventListener("abort",i,{once:!0});try{let a=await n.worker.connection.sendRequest(Te,e,t.token),l=Ie.safeParse(a);return l.success?l.data:{outcome:{detail:"bad-outcome-frame",kind:"error"},serverNotified:!1}}catch(a){return dn(a,n)}finally{r.removeEventListener("abort",i),t.dispose(),W(n,o)}}async function br(e){let r=e.workers.find(o=>o.alive&&o.runId===void 0);if(r!=null)return r.runId="pending",await r.ready,r;if(e.workers.length<e.size){let o=Ir(e);return o.runId="pending",await o.ready,o}return new Promise(o=>{e.waiters.push(n=>{n.runId="pending",o(n)})})}function Ir(e){let r=e.spawn(),o={resolve:()=>{}},n={alive:!0,id:e.nextId,ready:new Promise(t=>{o.resolve=t,r.connection.onNotification(Ce,t)}),runId:void 0,worker:r};return e.nextId+=1,r.connection.onRequest(Le,()=>e.lockfileProvider()),r.onExit(()=>{n.alive=!1,e.workers=e.workers.filter(t=>t!==n),r.connection.dispose(),o.resolve()}),e.workers.push(n),n}function W(e,r){if(e.runId=void 0,!e.alive||r.closed)return;if(r.workers.length>r.size){J(e,r);return}let o=r.waiters.shift();o?.(e)}async function J(e,r){if(r.workers=r.workers.filter(t=>t!==e),!e.alive)return;let o=new Promise(t=>{e.worker.onExit(t)});await e.ready,await e.worker.connection.sendNotification(De).catch(()=>{});let n=setTimeout(()=>{e.worker.kill()},an);await o,clearTimeout(n)}function dn(e,r){return e instanceof xr&&e.code===Er?{outcome:{detail:"aborted",kind:"error"},serverNotified:!1}:r.alive?{outcome:{detail:e instanceof Error?e.message:String(e),kind:"error"},serverNotified:!1}:{outcome:{detail:"worker-exit",kind:"error"},serverNotified:!1}}async function cn(e,r,o){let n=await br(o);if(n.runId="explore",!n.alive)return W(n,o),{kind:"error"};let t=new kr,i={cancel:()=>{}},a=()=>{t.cancel();let l=setTimeout(()=>{n.worker.kill()},sn);i.cancel=()=>{clearTimeout(l)}};r.aborted&&a(),r.addEventListener("abort",a,{once:!0});try{let l=await n.worker.connection.sendRequest(We,{assign:e,devSessionId:o.devSessionId},t.token),d=ue.safeParse(l);return d.success?d.data:{kind:"error"}}catch(l){return un(l)}finally{i.cancel(),r.removeEventListener("abort",a),t.dispose(),W(n,o)}}function un(e){return e instanceof xr&&e.code===Er?{kind:"aborted"}:{kind:"error",reason:`transport:${e instanceof Error?e.message.slice(0,120):"unknown"}`}}function pn(e,r){r.size=e,e>vr.availableParallelism()&&s.warn({cores:vr.availableParallelism(),size:e},"worker pool size exceeds available cores");let o=r.workers.filter(t=>t.alive&&t.runId===void 0),n=r.workers.length-e;o.slice(0,Math.max(0,n)).forEach(t=>{J(t,r)}),Cr(r)}function Cr(e){e.closed||Array.from({length:Math.max(0,e.size-e.workers.length)}).forEach(()=>{Ir(e)})}import A from"fs";import{graphql as x}from"gql.tada";import{print as D}from"graphql";var fn=x(`
66
- query DaemonExploration($devSessionId: String!) {
67
- exploration(devSessionId: $devSessionId) {
68
- active
69
- localWorkers
70
- maxTrailLength
71
- }
72
- }
73
- `),mn=x(`
74
- subscription WatchExplorationChanged($devSessionId: String!) {
75
- explorationChanged(devSessionId: $devSessionId) {
76
- exploration {
77
- active
78
- localWorkers
79
- maxTrailLength
80
- }
81
- }
82
- }
83
- `);function Tr({config:e,devSessionId:r,machinery:o,sseClient:n}){return yn({config:e,devSessionId:r,machinery:o}),n.subscribe({query:D(mn),variables:{devSessionId:r}},{complete:()=>{},error:t=>{s.error(t,"exploration subscription error")},next:t=>{Lr(o,t.data?.explorationChanged.exploration)}})}async function yn({config:e,devSessionId:r,machinery:o}){let n=await y({config:e,document:fn,variables:{devSessionId:r}});Lr(o,n.exploration)}function Lr(e,r){r!=null&&(e.setMaxTrailLength(r.maxTrailLength),e.setConcurrency(r.localWorkers),e.setEnabled(r.active))}function Wr({config:e,devSessionId:r,machinery:o}){o.setReportProgress(n=>{Ge({attempts:n.attempts,config:e,devSessionId:r,findings:n.findings,trail:Ke(n.result)}).catch(t=>{s.warn({error:t},"exploration progress report failed")})}),o.setReportUnhealthy(()=>{ze(e,r).catch(n=>{s.warn({error:n},"exploration unhealthy report failed")})})}var gn=x(`
84
- subscription HooksPausedWatch($projectId: String!) {
85
- hooksPausedRequested(projectId: $projectId) {
86
- paused
87
- projectId
88
- }
89
- }
90
- `),Sn=x(`
91
- subscription WatchLocalConcurrencyChanged {
92
- myMaxLocalConcurrentRunsChanged
93
- }
94
- `);function Ar({pool:e,sseClient:r}){return r.subscribe({query:D(Sn)},{complete:()=>{},error:o=>{s.error(o,"localConcurrency subscription error")},next:o=>{let n=o.data?.myMaxLocalConcurrentRunsChanged;n!=null&&(I(n),e.setSize(n))}})}var wn=x(`
95
- subscription WatchExecutorChangeRequested($devSessionId: String!) {
96
- executorChangeRequested(devSessionId: $devSessionId) {
97
- executor
98
- }
99
- }
100
- `);function Dr({config:e,devSessionId:r,sseClient:o,switcher:n}){return n.connect(r),hn({config:e,switcher:n}),vn({devSessionId:r,sseClient:o,switcher:n})}async function hn({config:e,switcher:r}){let o=await Qe(e);if(o.isErr()){s.warn({error:o.error},"initial executor fetch failed, staying local");return}r.request(o.value)}function vn({devSessionId:e,sseClient:r,switcher:o}){return r.subscribe({query:D(wn),variables:{devSessionId:e}},{complete:()=>{},error:n=>{s.error(n,"executor subscription error")},next:n=>{let t=n.data?.executorChangeRequested?.executor;t!=null&&o.request(t)}})}function Hr({cwd:e,projectId:r,sseClient:o}){return o.subscribe({query:D(gn),variables:{projectId:r}},{complete:()=>{},error:n=>{s.error(n,"hooksPaused subscription error")},next:n=>{let t=n.data?.hooksPausedRequested?.paused;t!=null&&Q({cwd:e,paused:t})}})}function Q({cwd:e,paused:r}){let o=we(e);if(r&&!A.existsSync(o)){A.writeFileSync(o,"");return}!r&&A.existsSync(o)&&A.unlinkSync(o)}var En=6e4,qr=500,bn=15e3,Ur=6e4,In=3,Cn=V(`
101
- mutation HeartbeatDevSessionWatch($id: String!) {
102
- heartbeatDevSession(id: $id) {
103
- __typename
104
- ... on DevSession {
105
- id
106
- }
107
- ... on DevSessionEndedError {
108
- message
109
- }
110
- }
111
- }
112
- `),Tn=V(`
113
- query WatchLocalConcurrency {
114
- currentUser {
115
- id
116
- maxLocalConcurrentRuns
117
- }
118
- }
119
- `),Ln=V(`
120
- mutation EndDevSessionWatch($projectId: String!, $cwd: String!) {
121
- endDevSession(projectId: $projectId, cwd: $cwd) {
122
- __typename
123
- ... on DevSession {
124
- id
125
- }
126
- ... on NoActiveDevSessionError {
127
- message
128
- }
129
- }
130
- }
131
- `);async function Yi(){zn();let e=jn(process.cwd()),r=e.cwd,o=_n(r),{executorSwitch:n,exploration:t,poolGate:i}=Wn(e),a={handler:()=>{}},l=Fn(),d=er(),c=Ne({config:e,cwd:r,executor:n.current,explorationStatus:t.status,ready:l.promise,onShutdownRequest:()=>{a.handler()},sseHealth:()=>d.snapshot()}),p=await On({cwd:r,ipc:c,releasePid:o}),u=await M(r);u.isErr()&&(process.stderr.write(`ripplo: ${_(u.error)}
132
- `),process.exit(1));let f=u.value,m=await Mr(()=>$e({config:e,cwd:r,lockfile:f}),{config:e,label:"initial sync"}),w=await C(r);w!=null&&Fe(w),qe({config:e,cwd:r,lockfile:f}).catch(q=>{s.warn({err:q},"retire stale findings failed")});let P=await Qn(e);Q({cwd:r,paused:m.hooksPaused});let g=Me(r);g!=null&&s.info("watching branch %s in %s",g,r);let S=xn({headers:{Authorization:`Bearer ${e.token}`},retry:Ye,retryAttempts:1/0,url:`${e.ripploServerUrl}/graphql`});hr({config:e,cwd:r}).catch(()=>{});let h=Mn({cwd:r,devSessionId:m.devSessionId,initialConcurrency:P});i.provide(h);let H=await An({cwd:r,pool:h}),Y=qn({claim:c.claim,config:e,cwd:r,initialId:m.devSessionId,pool:h,sseClient:S,sseHealth:d}),_r=Dr({config:e,devSessionId:m.devSessionId,sseClient:S,switcher:n}),$r=Hr({cwd:r,projectId:e.projectId,sseClient:S}),Fr=Ar({pool:h,sseClient:S}),Or=Tr({config:e,devSessionId:m.devSessionId,machinery:t,sseClient:S});Wr({config:e,devSessionId:m.devSessionId,machinery:t});let Nr=Hn({config:e,session:Y}),jr=Gn();l.resolve(),Dn(m.devSessionId);let Br=async()=>{Nr(),jr(),t.stop(),p.close(),Y.stop(),_r(),$r(),Fr(),Or(),await h.close(),await n.stop(),await H.stop().catch(()=>{}),await Promise.race([y({config:e,document:Ln,variables:{cwd:e.cwd,projectId:e.projectId}}).catch(()=>{}),new Promise(q=>setTimeout(q,3e3))]),o()},k=()=>{Br().finally(()=>process.exit(0))};a.handler=k,process.on("SIGINT",k),process.on("SIGTERM",k),process.on("SIGHUP",k),process.on("SIGBREAK",k),await new Promise(()=>{})}function Wn(e){let r={handler:()=>{}},o=Sr({config:e,onChanged:()=>{r.handler()}}),n=Nn(),t=ur({config:e,pool:n.pool,executorIsLocal:()=>o.current()==="local"});return r.handler=t.notifyExecutorChanged,{executorSwitch:o,exploration:t,poolGate:n}}function An({cwd:e,pool:r}){return me({localDir:kn.join(e,".ripplo",".local"),writePortFile:!0,onRrwebBatch:()=>{},onSpan:o=>{let n=o.attributes["ripplo.run"];n!=null&&r.routeSpan(n,o)}})}function Dn(e){process.stdout.write(`${Re({devSessionId:e,version:re()})}
133
- `)}function Hn({config:e,session:r}){let o=async()=>{try{let t=await y({config:e,document:Cn,variables:{id:r.getId()}});t.heartbeatDevSession?.__typename==="DevSessionEndedError"&&(s.warn("dev session ended server-side (%s); re-registering",t.heartbeatDevSession.message),await r.reregister())}catch(t){s.warn("heartbeat failed: %s",t instanceof Error?t.message:String(t))}},n=setInterval(()=>{o()},bn);return()=>{clearInterval(n)}}function qn({claim:e,config:r,cwd:o,initialId:n,pool:t,sseClient:i,sseHealth:a}){let l=n,d=null,c=0,p=0,u=g=>{P(g)},f=()=>{let g=Xe({claim:e,cwd:o,devSessionId:l,onSubscriptionDead:u,pool:t,sseClient:i,sseHealth:a}),S=Ze({cwd:o,devSessionId:l,onSubscriptionDead:u,sseClient:i});return()=>{g(),S()}},m=f(),w=async g=>{let S=Date.now();c=S-p>Ur*2?1:c+1,p=S,c>=In&&a.markUnhealthy(g),await Un(Math.min(1e3*2**(c-1),Ur));let h=await M(o);if(h.isErr()){s.error("re-register: compile failed: %s",_(h.error));return}let H=await Mr(()=>_e({config:r,cwd:o,lockfile:h.value}),{config:r,label:"re-register sync"});m(),l=H.devSessionId,m=f(),s.info("re-registered dev session as %s",l)},P=g=>(d!=null||(d=w(g).finally(()=>{d=null})),d);return{getId:()=>l,reregister:()=>P("dev session ended server-side"),stop:()=>{m()}}}function Un(e){return new Promise(r=>setTimeout(r,e))}function Mn({cwd:e,devSessionId:r,initialConcurrency:o}){return Rr({devSessionId:r,initialSize:o,spawn:Pr(Vn(),e),lockfileProvider:async()=>{let n=await R(e);if(n.isErr())return{unavailable:`daemon-load-failed:${n.error.kind}`};let t=await E(e,n.value);return{lockfileJson:oe(ne,t)}}})}function _n(e){try{return ge({cwd:e,onCompromised:$n})}catch(r){throw r instanceof ye&&(process.stderr.write(`${Ee({cwd:r.cwd,pid:r.pid})}
134
- `),process.exit(1)),r}}function $n(){s.error("daemon lock compromised; shutting down"),process.stderr.write(`${be()}
135
- `),process.exit(1)}function Fn(){let e={handler:()=>{}};return{promise:new Promise(o=>{e.handler=o}),resolve:()=>{e.handler()}}}async function On({cwd:e,ipc:r,releasePid:o}){return(await ar({cwd:e,onConnection:r.handleConnection})).match(t=>t,t=>{process.stderr.write(`${ke(t)}
136
- `),o(),process.exit(1)})}function Nn(){let e={provide:()=>{}};return{pool:new Promise(o=>{e.provide=o}),provide:o=>{e.provide(o)}}}function jn(e){return v(e).match(r=>r,r=>{process.stderr.write(`${ae(r)}
137
- `),process.exit(1)})}function Mr(e,{config:r,label:o}){let n=r.ripploServerUrl.includes("localhost")||r.ripploServerUrl.includes("127.0.0.1");return Pn(async()=>{try{return await e()}catch(t){Bn({config:r,error:t});let i=t instanceof Error?t.message:String(t);throw Kn(i)?t:(s.error("%s failed: %s",o,i),new Rn(i))}},{factor:2,maxTimeout:n?2e3:1e4,minTimeout:n?100:1e3,retries:1/0,onFailedAttempt:({attemptNumber:t,error:i})=>{s.warn("%s attempt %d failed \u2014 retrying: %s",o,t,i.message)}})}function Bn({config:e,error:r}){let o=X(r);o==="UNAUTHENTICATED"&&(process.stderr.write(`ripplo: ${Pe()}
138
- `),process.exit(1)),o==="FORBIDDEN"&&(process.stderr.write(`ripplo: ${xe({projectId:e.projectId,serverUrl:e.ripploServerUrl})}
139
- `),process.exit(1))}function Kn(e){return e.includes("status 502")||e.includes("ECONNREFUSED")||e.includes("Failed to connect")||e.includes("fetch failed")}function Gn(){U({maxRuns:qr});let e=setInterval(()=>{U({maxRuns:qr})},En);return()=>{clearInterval(e)}}function zn(){process.on("unhandledRejection",e=>{s.error({err:e},"unhandledRejection in watch; continuing")}),process.on("uncaughtException",e=>{s.error({err:e},"uncaughtException in watch; continuing")})}var Jn=4;async function Qn(e){try{let o=(await y({config:e,document:Tn,variables:void 0})).currentUser?.maxLocalConcurrentRuns;if(o!=null)return I(o),o}catch(r){s.warn({err:r},"failed to fetch local concurrency setting; using default")}return Jn}function Vn(){let e=process.argv[1];if(e==null)throw new Error("cli entry unavailable");return e}export{Yi as runDaemon};