ripplo 0.7.55 → 0.7.57
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/{chunk-3JC4ZODN.js → chunk-L3IQRGAN.js} +3 -3
- package/dist/chunk-PHP2RNJ4.js +274 -0
- package/dist/{chunk-2AFQ4C6G.js → chunk-Q4US2KWY.js} +1 -1
- package/dist/{chunk-OUOQU2Q2.js → chunk-Z3EBCNXG.js} +27 -27
- package/dist/{daemon-MIKO7PSF.js → daemon-HW2TTEXZ.js} +1 -1
- package/dist/daemon-ZDKFGROH.js +139 -0
- package/dist/index.js +299 -256
- package/dist/{status-K7LW3M23.js → status-BRGXIPVJ.js} +1 -1
- package/package.json +5 -5
- package/dist/chunk-Q6NPLTSY.js +0 -274
- package/dist/daemon-4H2AMVM3.js +0 -139
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __ripploCreateRequire } from "node:module";
|
|
3
3
|
const require = globalThis.require ?? __ripploCreateRequire(import.meta.url);
|
|
4
|
-
import{ka as a,la as b,ma as c,na as d,oa as e,pa as f,qa as g,ra as h,sa as i,ta as j,ua as k,va as l}from"./chunk-
|
|
4
|
+
import{ka as a,la as b,ma as c,na as d,oa as e,pa as f,qa as g,ra as h,sa as i,ta as j,ua as k,va as l}from"./chunk-Z3EBCNXG.js";import"./chunk-63TU4VJ7.js";export{b as renderDaemonBindError,h as renderDaemonLockCompromised,f as renderDaemonLockHeld,e as renderDaemonReady,i as renderDaemonStatus,g as renderDaemonStopResult,k as renderDaemonVersionNote,j as renderExplorationProgress,d as renderNotSignedIn,c as renderProjectAccessDenied,a as renderTunnelProvisionFailed,l as wireOutcome};
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __ripploCreateRequire } from "node:module";
|
|
3
|
+
const require = globalThis.require ?? __ripploCreateRequire(import.meta.url);
|
|
4
|
+
import{A as Ae,B as De,D as b,E as I,F as He,G as _,H as qe,J as Ue,K as Me,L as C,N as _e,O as $e,P as Fe,Q as Oe,R as Ne,S as T,U as je,V as Be,W as Ke,Y as Ge,Z as ze,_ as $,b as Z,f as ie,i as v,n as ge,p as Se,r as he,u as be,v as Ie,w as Ce,x as Te,y as Le,z as We}from"./chunk-PHP2RNJ4.js";import{e as me,f as ye}from"./chunk-ZPCVY23H.js";import{a as ee,d as R,e as te,f as U,i as M,s as E,u as we}from"./chunk-L3IQRGAN.js";import{d as Y,e as y,f as s,g as q,h as X}from"./chunk-PXYDLKAG.js";import{$ as ue,X as le,Z as de,_ as ce,aa as pe,ba as fe,f as re,i as oe,l as ne,la as ve,ma as ke,na as xe,oa as Pe,pa as Re,ra as Ee,s as ae,w as se}from"./chunk-Z3EBCNXG.js";import"./chunk-63TU4VJ7.js";import wn from"path";import{createClient as hn}from"graphql-sse";import vn,{AbortError as kn}from"p-retry";import{graphql as Q}from"gql.tada";import{graphql as Kr}from"gql.tada";import{print as Gr}from"graphql";async function Je({config:e,cwd:r,headed:o,pool:n,runId:t,signal:i,testSlug:a,workClass:l,workflowSlug:d}){let u=await R(r);if(u.isErr())return await T(e,t,`lockfile:${u.error.kind}`),{kind:"dispatch-error",reason:{detail:`lockfile:${u.error.kind}`,type:"generic"}};let p=Br(u.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 c=await b({headed:o,workClass:l,task:()=>n.execute({headed:o,runId:t,testRef:p},i)});return!c.serverNotified&&c.outcome.kind==="error"&&await T(e,t,c.outcome.detail),c.outcome}function Br(e,{testSlug:r,workflowSlug:o}){let t=e.workflows.find(i=>ne(i.name)===o)?.tests.find(i=>i.slug===r);return t==null?void 0:ae(t)}var zr=6e4,Jr=Kr(`
|
|
5
|
+
subscription RunRequestedWatch($devSessionId: String!) {
|
|
6
|
+
runRequested(devSessionId: $devSessionId) {
|
|
7
|
+
runId
|
|
8
|
+
testSlug
|
|
9
|
+
workflowId
|
|
10
|
+
workflowSlug
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
`);async function Qe(e){let r=Math.min(1e3*2**e,zr)+Yr();await new Promise(o=>setTimeout(o,r))}function Ve({claim:e,cwd:r,devSessionId:o,onSubscriptionDead:n,pool:t,sseClient:i,sseHealth:a}){let l=new Set;return i.subscribe({query:Gr(Jr),variables:{devSessionId:o}},{complete:()=>{},error:d=>{let u=d instanceof Error?d.message:String(d);s.warn("runRequested SSE failed: %s; re-registering session",u),n(u)},next:d=>{Qr({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 Qr({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
|
+
`),Z(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=Vr(e(o.runId),o);a.started(),Je({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 Vr(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:$e(e.token),workClass:"p1-cli",finished:o=>{e.finished(r.runId,o)},started:()=>{e.started(r.runId)}}}function Yr(){return Math.floor(Math.random()*2700)+300}import{graphql as F}from"gql.tada";import{print as Xr}from"graphql";var Zr=F(`
|
|
15
|
+
subscription TeleportRequestedWatch($devSessionId: String!) {
|
|
16
|
+
teleportRequested(devSessionId: $devSessionId) {
|
|
17
|
+
runId
|
|
18
|
+
stepIndex
|
|
19
|
+
kind
|
|
20
|
+
testSlug
|
|
21
|
+
workflowSlug
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
`),eo=F(`
|
|
25
|
+
query TeleportRunRepro($id: String!) {
|
|
26
|
+
run(id: $id) {
|
|
27
|
+
id
|
|
28
|
+
reproJson
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
`),ro=F(`
|
|
32
|
+
mutation ReportTeleportResult($devSessionId: String!, $runId: String!, $status: String!) {
|
|
33
|
+
reportTeleportResult(devSessionId: $devSessionId, runId: $runId, status: $status)
|
|
34
|
+
}
|
|
35
|
+
`);function Ye({cwd:e,devSessionId:r,onSubscriptionDead:o,sseClient:n}){let t=new Set,i=n.subscribe({query:Xr(Zr),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=>{oo({cwd:e,devSessionId:r,event:a.data?.teleportRequested,running:t})}});return()=>{t.forEach(a=>{a.abort()}),t.clear(),i()}}function oo({cwd:e,devSessionId:r,event:o,running:n}){if(o==null)return;let t=new AbortController;n.add(t),no({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 no({cwd:e,devSessionId:r,event:o,signal:n}){let t=d=>to({cwd:e,devSessionId:r,runId:o.runId,status:d}),i=await io(e,o);if(i==null){s.warn({runId:o.runId},"teleport could not resolve target"),await t("unplannable");return}process.stdout.write(`ripplo: teleport ${so(o)} step ${String(o.stepIndex+1)}
|
|
36
|
+
`);let l=await Ge({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 to({cwd:e,devSessionId:r,runId:o,status:n}){let t=v(e).match(i=>i,()=>null);t!=null&&await y({config:t,document:ro,variables:{devSessionId:r,runId:o,status:n}}).catch(()=>null)}async function io(e,r){if(r.kind==="explore"){let o=await ao(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 ao(e,r){let o=v(e).match(t=>t,()=>null);if(o==null)return null;let n=await y({config:o,document:eo,variables:{id:r}}).catch(()=>null);return n?.run?.reproJson==null?null:de.parse(JSON.parse(n.run.reproJson))}function so(e){return e.kind==="explore"?"explore finding":`${String(e.workflowSlug)}/${String(e.testSlug)}`}function Xe(){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 lo from"fs";import or from"net";import{err as nr,ok as co}from"neverthrow";async function tr({cwd:e,onConnection:r}){X(e);let o=we(e),n=await Ze({onConnection:r,socketPath:o});return n.isOk()||n.error.kind!=="stale-candidate"?n.map(er(o)).mapErr(rr(o)):await uo(o)?nr({kind:"already-running",socketPath:o}):(ir(o),(await Ze({onConnection:r,socketPath:o})).map(er(o)).mapErr(rr(o)))}function uo(e){return new Promise(r=>{let o=or.connect(e);o.once("connect",()=>{o.destroy(),r(!0)}),o.once("error",()=>{r(!1)})})}async function Ze(e){let r=await po(e);return r.kind==="listening"?co(r.server):nr(r.error)}function po({onConnection:e,socketPath:r}){return new Promise(o=>{let n=or.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 er(e){return r=>({socketPath:e,close:()=>{r.close(),ir(e)}})}function ir(e){lo.rmSync(e,{force:!0})}function rr(e){return r=>r.kind==="stale-candidate"?{kind:"already-running",socketPath:e}:{kind:"bind-failed",message:r.message}}import{randomInt as fo,randomUUID as mo}from"crypto";function sr(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=O(e,r);return{priority:"p3",next:()=>ko(e,r),onResult:()=>{},ready:()=>o,status:()=>({attempts:r.attempts,findings:r.findings}),stop:()=>Promise.resolve()}}var yo=10;async function O(e,r){if(!r.preparing){r.preparing=!0;try{let o=await e.loadLockfile(),n=o==null?null:await go(o);if(n==null||o==null)return;r.lockfile=o.lockfile,r.prepared=n,N(r),e.notifyWork()}finally{r.preparing=!1}}}async function go({lockfile:e,rawHash:r}){let o=await ue(e);return o==null?null:{exploration:o,lockfileHashValue:r,strategy:le("even")}}var So=6,wo=3e4,ho=2e4;function N(e){e.consecutiveErrors=0,e.driverBackoffUntil=0,e.lastUnhealthyReportMs=0}async function vo(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 O(e,r)}finally{r.refreshing=!1}}}function ko(e,r){vo(e,r);let o=r.prepared;if(o==null||Date.now()<r.driverBackoffUntil)return null;let n=pe({lockfileHash:o.lockfileHashValue,prepared:o.exploration,random:xo,strategy:{...o.strategy,maxAttemptLength:e.maxTrailLength()}});if(n==null)return null;let t=n.baseStateTest.name;return{id:`explore:${mo()}`,label:t,run:i=>Po({assign:n,params:e,signal:i,state:r})}}var ar=2**31;function xo(){return fo(ar)/ar}async function Po({assign:e,params:r,signal:o,state:n}){if(!await r.probeApp()){lr({params:r,reason:"app-unreachable",state:n});return}let t=await r.executeTrail(e,o);if(t.kind==="aborted")return;if(t.kind==="error"){Eo({params:r,reason:t.reason,state:n});return}N(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>=yo&&Ro(n)}function Ro(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 Eo({params:e,reason:r,state:o}){if(r?.startsWith("lockfile:daemon-load-failed")===!0){bo(e,o);return}lr({params:e,reason:r,state:o})}function bo(e,r){r.preparing||(r.prepared=null,O(e,r))}function lr({params:e,reason:r,state:o}){let n=Co(r);if(n==="trail"){N(o);return}o.consecutiveErrors+=1,s.debug("exploration infra error: %s",r),!(o.consecutiveErrors<So)&&(n==="driver"&&(o.driverBackoffUntil=Date.now()+wo),Io({params:e,reason:r,state:o}))}function Io({params:e,reason:r,state:o}){let n=Date.now();n-o.lastUnhealthyReportMs<ho||(o.lastUnhealthyReportMs=n,s.warn("exploration unhealthy after %d consecutive infra errors (last: %s)",o.consecutiveErrors,r),e.reportUnhealthy())}function Co(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":se(r)?"infra":"trail"}return"trail"}function j(e){return{priority:e,next:()=>null,onResult:()=>{}}}function dr({config:e,executorIsLocal:r,pool:o}){return Wo({appUrl:e.appUrl,cwd:e.cwd,executorIsLocal:r,executeTrail:async(n,t)=>(await o).exploreTrail(n,t)})}function Wo({appUrl:e,cwd:r,executeTrail:o,executorIsLocal:n}){let t={concurrency:2,enabled:!1,maxTrailLength:12},i={notify:()=>{}},a={report:p=>{}},l={report:()=>{}},d=Ao({appUrl:e,cwd:r,executeTrail:o,maxTrailLength:()=>t.maxTrailLength,notifyWork:()=>{i.notify()},reportProgress:p=>{a.report(p)},reportUnhealthy:()=>{l.report()}}),u=he({now:Date.now,probe:Do,setTimer:Ho,sources:[j("p0"),j("p1"),d],execute:({job:p,priority:c,signal:f})=>b({headed:!1,workClass:qo(c),task:()=>p.run(f)}),exploreConcurrency:()=>t.concurrency,exploreEnabled:()=>t.enabled&&n()});return _(()=>{u.notifyQueueChange()}),i.notify=()=>{u.notifyQueueChange()},{notifyExecutorChanged:()=>{u.notifyQueueChange()},progress:()=>d.status(),setConcurrency:p=>{n()&&p!==t.concurrency&&s.info({workers:p},"explore local worker count changed"),t.concurrency=p,u.notifyQueueChange()},setEnabled:p=>{t.enabled=p,u.notifyQueueChange()},setMaxTrailLength:p=>{t.maxTrailLength=p},setReportProgress:p=>{a.report=p},setReportUnhealthy:p=>{l.report=p},status:()=>({explorer:t.enabled?"on":"off",exploring:u.explorationActive(),progress:d.status()}),stop:()=>{u.stop(),_(null),d.stop()}}}function Ao({appUrl:e,cwd:r,executeTrail:o,maxTrailLength:n,notifyWork:t,reportProgress:i,reportUnhealthy:a}){return sr({cwd:r,executeTrail:o,maxTrailLength:n,notifyWork:t,reportProgress:i,reportUnhealthy:a,loadLockfile:async()=>{let{fingerprint:l,result:d}=await te(r),u=await C(r);return u==null?null:d.match(async p=>({fingerprint:l,lockfile:await E(r,p),rawHash:u}),()=>Promise.resolve(null))},probeApp:async()=>await ge(e)==null})}function Do(){let e=He();return{headedActive:e.headedActive,interactiveActive:e.active,interactiveQueued:e.queued,poolSize:e.poolSize}}function Ho(e,r){let o=setTimeout(e,r);return()=>{clearTimeout(o)}}function qo(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 Yo}from"gql.tada";import{connect as Mo}from"net";import _o from"ssh2";import{WebSocket as ur,createWebSocketStream as $o}from"ws";var Uo="ripplo-";function B(e){return Object.entries(e).map(([r,o])=>`${Uo}${r}.${o}`)}var{Server:Fo,utils:cr}=_o;function pr(){let e=cr.generateKeyPairSync("ed25519"),r=cr.parseKey(e.private);if(r instanceof Error)throw r;return{fingerprint:r.getPublicSSH().toString("base64"),privateKey:e.private}}function fr(e){return new Promise((r,o)=>{let n={closers:new Set,stopped:!1},t=new ur(e.relayUrl,B({grant:e.grant,role:"daemon-control"}));t.on("open",()=>{s.info("cloud-executor relay control up"),r({stop:Oo(t,n)})}),t.on("message",i=>{No(e,n,i)}),t.on("close",(i,a)=>{n.stopped||s.warn({code:i,reason:a.toString()},"relay control closed"),Vo(e,n)}),t.on("error",i=>{o(i instanceof Error?i:new Error(String(i)))})})}function Oo(e,r){return()=>(r.stopped=!0,r.closers.forEach(o=>{o()}),e.close(),Promise.resolve())}function No(e,r,o){let n=jo(o);n!=null&&Ko(e,r,n.pipeId)}function jo(e){try{let r=JSON.parse(Bo(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 Bo(e){return Buffer.isBuffer(e)?e.toString("utf8"):Array.isArray(e)?Buffer.concat(e).toString("utf8"):Buffer.from(e).toString("utf8")}function Ko(e,r,o){if(r.stopped)return;let n=new ur(e.relayUrl,B({pipeId:o,role:"daemon-data"}));n.on("open",()=>{Go(e,r,n)}),n.on("error",t=>{s.warn({err:t},"cloud-executor relay data pipe error")})}function Go(e,r,o){let n=$o(o);n.on("error",()=>{});let t=new Fo({hostKeys:[e.hostKey.privateKey]},a=>{a.on("authentication",l=>{Jo(l,e.secret)}),a.on("ready",()=>{a.on("tcpip",(l,d,u)=>{Qo({accept:l,allowedPorts:e.allowedPorts,deny:d,destPort:u.destPort})})})}),i=()=>{o.close()};r.closers.add(i),o.on("close",()=>r.closers.delete(i)),zo(t,n)}function zo(e,r){e.injectSocket(r)}function Jo(e,r){if(e.method==="password"&&e.password===r){e.accept();return}if(e.method==="none"){e.reject(["password"]);return}e.reject()}function Qo({accept:e,allowedPorts:r,deny:o,destPort:n}){if(!r.includes(n)){o();return}let t=!1,i=Mo({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 Vo(e,r){r.stopped||(r.stopped=!0,r.closers.forEach(o=>{o()}),e.onFatal())}var Xo=Yo(`
|
|
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 K({config:e,devSessionId:r,onFatal:o}){let n=pr(),i=(await y({config:e,document:Xo,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 fr({allowedPorts:[...new Set([mr(e.appUrl),mr(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 mr(e){let r=new URL(e);return r.port.length>0?Number(r.port):r.protocol==="https:"?443:80}var Zo=[1e3,3e3,8e3,15e3];function yr({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 c=>{let f=o.devSessionId;if(!t()||f==null)return;let m=Zo[c];if(m==null){s.warn("tunnel connector gave up; reverting executor to local"),p("local"),$(e,"local");return}if(s.warn({attempt:c+1},"relay tunnel dropped; reconnecting"),await new Promise(w=>setTimeout(w,m)),!(!t()||o.tunnel!=null))try{let w=await K({config:e,devSessionId:f,onFatal:n});if(!t()){await w.stop();return}o.tunnel=w,s.info("relay tunnel reconnected")}catch{i(c+1)}},a=async c=>{let f=await K({config:e,devSessionId:c,onFatal:n});o.tunnel=f,o.mode="cloud",s.info("executor switched to cloud"),r()},l=async()=>{let c=o.tunnel;o.tunnel=void 0,o.mode="local",c!=null&&await c.stop(),s.info("executor switched to local"),r()},d=async c=>{let f=o.devSessionId;if(!(f==null||c===o.mode)){if(c==="cloud"){await a(f);return}await l()}},u=async c=>{s.warn({err:c},"executor switch failed; staying local"),await $(e,"local").catch(()=>{})},p=c=>{o.queue=o.queue.then(()=>d(c).catch(u))};return{request:p,connect:c=>{o.devSessionId=c},current:()=>o.mode,stop:async()=>{await o.queue.catch(()=>{}),await d("local")}}}import{readdir as en}from"fs/promises";import{existsSync as gr}from"fs";import G from"path";async function Sr({config:e,cwd:r}){let o=G.join(r,".ripplo","debug");await(await en(o,{withFileTypes:!0}).catch(()=>[])).filter(i=>i.isDirectory()).map(i=>i.name).filter(i=>!i.startsWith("replay-")&&!i.startsWith("explore-")&&!gr(G.join(o,i,Oe))&&gr(G.join(o,i,"behavior.jsonl"))).reduce((i,a)=>i.then(()=>Ne({config:e,debugDir:o,runId:a}).catch(()=>{})),Promise.resolve(void 0))}import{fork as rn}from"child_process";import wr from"os";import{CancellationTokenSource as hr,ResponseError as vr}from"vscode-jsonrpc/node";function kr(e,r){return()=>{let o=rn(e,["run-worker"],{cwd:r,detached:!0,stdio:["ignore","inherit","inherit","ipc"]});return{connection:De(o),kill:()=>{on(o)},onExit:n=>{o.once("exit",n)}}}}function xr(e){let r={closed:!1,devSessionId:e.devSessionId,lockfileProvider:e.lockfileProvider,nextId:0,size:e.initialSize,spawn:e.spawn,waiters:[],workers:[]};return br(r),{close:async()=>{r.closed=!0,await Promise.all([...r.workers].map(o=>z(o,r)))},execute:(o,n)=>tn(o,n,r),exploreTrail:(o,n)=>sn(o,n,r),routeSpan:(o,n)=>{let t=r.workers.find(i=>i.runId===o);t?.worker.connection.sendNotification(We,{runId:o,span:n})},setSize:o=>{dn(o,r)}}}function on(e){let r=e.pid;if(r!=null)try{process.kill(-r,"SIGKILL")}catch{e.kill("SIGKILL")}}var nn=1e4,Pr=-32800;async function tn(e,r,o){let n=await Rr(o);if(n.runId=e.runId,!n.alive)return W(n,o),{outcome:{detail:"worker-exit",kind:"error"},serverNotified:!1};let t=new hr,i=()=>{t.cancel()};r.aborted&&t.cancel(),r.addEventListener("abort",i,{once:!0});try{let a=await n.worker.connection.sendRequest(Ce,e,t.token),l=be.safeParse(a);return l.success?l.data:{outcome:{detail:"bad-outcome-frame",kind:"error"},serverNotified:!1}}catch(a){return an(a,n)}finally{r.removeEventListener("abort",i),t.dispose(),W(n,o)}}async function Rr(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=Er(e);return o.runId="pending",await o.ready,o}return new Promise(o=>{e.waiters.push(n=>{n.runId="pending",o(n)})})}function Er(e){let r=e.spawn(),o={resolve:()=>{}},n={alive:!0,id:e.nextId,ready:new Promise(t=>{o.resolve=t,r.connection.onNotification(Ie,t)}),runId:void 0,worker:r};return e.nextId+=1,r.connection.onRequest(Te,()=>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){z(e,r);return}let o=r.waiters.shift();o?.(e)}async function z(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(Ae).catch(()=>{});let n=setTimeout(()=>{e.worker.kill()},nn);await o,clearTimeout(n)}function an(e,r){return e instanceof vr&&e.code===Pr?{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 sn(e,r,o){let n=await Rr(o);if(n.runId="explore",!n.alive)return W(n,o),{kind:"error"};let t=new hr,i=()=>{t.cancel()};r.aborted&&t.cancel(),r.addEventListener("abort",i,{once:!0});try{let a=await n.worker.connection.sendRequest(Le,{assign:e,devSessionId:o.devSessionId},t.token),l=ce.safeParse(a);return l.success?l.data:{kind:"error"}}catch(a){return ln(a)}finally{r.removeEventListener("abort",i),t.dispose(),W(n,o)}}function ln(e){return e instanceof vr&&e.code===Pr?{kind:"aborted"}:{kind:"error",reason:`transport:${e instanceof Error?e.message.slice(0,120):"unknown"}`}}function dn(e,r){r.size=e,e>wr.availableParallelism()&&s.warn({cores:wr.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=>{z(t,r)}),br(r)}function br(e){e.closed||Array.from({length:Math.max(0,e.size-e.workers.length)}).forEach(()=>{Er(e)})}import A from"fs";import{graphql as x}from"gql.tada";import{print as D}from"graphql";var cn=x(`
|
|
66
|
+
query DaemonExploration($devSessionId: String!) {
|
|
67
|
+
exploration(devSessionId: $devSessionId) {
|
|
68
|
+
active
|
|
69
|
+
localWorkers
|
|
70
|
+
maxTrailLength
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
`),un=x(`
|
|
74
|
+
subscription WatchExplorationChanged($devSessionId: String!) {
|
|
75
|
+
explorationChanged(devSessionId: $devSessionId) {
|
|
76
|
+
exploration {
|
|
77
|
+
active
|
|
78
|
+
localWorkers
|
|
79
|
+
maxTrailLength
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
`);function Ir({config:e,devSessionId:r,machinery:o,sseClient:n}){return pn({config:e,devSessionId:r,machinery:o}),n.subscribe({query:D(un),variables:{devSessionId:r}},{complete:()=>{},error:t=>{s.error(t,"exploration subscription error")},next:t=>{Cr(o,t.data?.explorationChanged.exploration)}})}async function pn({config:e,devSessionId:r,machinery:o}){let n=await y({config:e,document:cn,variables:{devSessionId:r}});Cr(o,n.exploration)}function Cr(e,r){r!=null&&(e.setMaxTrailLength(r.maxTrailLength),e.setConcurrency(r.localWorkers),e.setEnabled(r.active))}function Tr({config:e,devSessionId:r,machinery:o}){o.setReportProgress(n=>{Be({attempts:n.attempts,config:e,devSessionId:r,findings:n.findings,trail:je(n.result)}).catch(t=>{s.warn({error:t},"exploration progress report failed")})}),o.setReportUnhealthy(()=>{Ke(e,r).catch(n=>{s.warn({error:n},"exploration unhealthy report failed")})})}var fn=x(`
|
|
84
|
+
subscription HooksPausedWatch($projectId: String!) {
|
|
85
|
+
hooksPausedRequested(projectId: $projectId) {
|
|
86
|
+
paused
|
|
87
|
+
projectId
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
`),mn=x(`
|
|
91
|
+
subscription WatchLocalConcurrencyChanged {
|
|
92
|
+
myMaxLocalConcurrentRunsChanged
|
|
93
|
+
}
|
|
94
|
+
`);function Lr({pool:e,sseClient:r}){return r.subscribe({query:D(mn)},{complete:()=>{},error:o=>{s.error(o,"localConcurrency subscription error")},next:o=>{let n=o.data?.myMaxLocalConcurrentRunsChanged;n!=null&&(I(n),e.setSize(n))}})}var yn=x(`
|
|
95
|
+
subscription WatchExecutorChangeRequested($devSessionId: String!) {
|
|
96
|
+
executorChangeRequested(devSessionId: $devSessionId) {
|
|
97
|
+
executor
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
`);function Wr({config:e,devSessionId:r,sseClient:o,switcher:n}){return n.connect(r),gn({config:e,switcher:n}),Sn({devSessionId:r,sseClient:o,switcher:n})}async function gn({config:e,switcher:r}){let o=await ze(e);if(o.isErr()){s.warn({error:o.error},"initial executor fetch failed, staying local");return}r.request(o.value)}function Sn({devSessionId:e,sseClient:r,switcher:o}){return r.subscribe({query:D(yn),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 Ar({cwd:e,projectId:r,sseClient:o}){return o.subscribe({query:D(fn),variables:{projectId:r}},{complete:()=>{},error:n=>{s.error(n,"hooksPaused subscription error")},next:n=>{let t=n.data?.hooksPausedRequested?.paused;t!=null&&J({cwd:e,paused:t})}})}function J({cwd:e,paused:r}){let o=Se(e);if(r&&!A.existsSync(o)){A.writeFileSync(o,"");return}!r&&A.existsSync(o)&&A.unlinkSync(o)}var xn=6e4,Dr=500,Pn=15e3,Hr=6e4,Rn=3,En=Q(`
|
|
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
|
+
`),bn=Q(`
|
|
113
|
+
query WatchLocalConcurrency {
|
|
114
|
+
currentUser {
|
|
115
|
+
id
|
|
116
|
+
maxLocalConcurrentRuns
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
`),In=Q(`
|
|
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 zi(){Bn();let e=Fn(process.cwd()),r=e.cwd,o=qn(r),{executorSwitch:n,exploration:t,poolGate:i}=Cn(e),a={handler:()=>{}},l=Mn(),d=Xe(),u=Fe({config:e,cwd:r,executor:n.current,explorationStatus:t.status,ready:l.promise,onShutdownRequest:()=>{a.handler()},sseHealth:()=>d.snapshot()}),p=await _n({cwd:r,ipc:u,releasePid:o}),c=await U(r);c.isErr()&&(process.stderr.write(`ripplo: ${M(c.error)}
|
|
132
|
+
`),process.exit(1));let f=c.value,m=await qr(()=>Me({config:e,cwd:r,lockfile:f}),{config:e,label:"initial sync"}),w=await C(r);w!=null&&_e(w);let P=await Gn(e);J({cwd:r,paused:m.hooksPaused});let g=qe(r);g!=null&&s.info("watching branch %s in %s",g,r);let S=hn({headers:{Authorization:`Bearer ${e.token}`},retry:Qe,retryAttempts:1/0,url:`${e.ripploServerUrl}/graphql`});Sr({config:e,cwd:r}).catch(()=>{});let h=Hn({cwd:r,devSessionId:m.devSessionId,initialConcurrency:P});i.provide(h);let H=await Tn({cwd:r,pool:h}),V=An({claim:u.claim,config:e,cwd:r,initialId:m.devSessionId,pool:h,sseClient:S,sseHealth:d}),Ur=Wr({config:e,devSessionId:m.devSessionId,sseClient:S,switcher:n}),Mr=Ar({cwd:r,projectId:e.projectId,sseClient:S}),_r=Lr({pool:h,sseClient:S}),$r=Ir({config:e,devSessionId:m.devSessionId,machinery:t,sseClient:S});Tr({config:e,devSessionId:m.devSessionId,machinery:t});let Fr=Wn({config:e,session:V}),Or=jn();l.resolve(),Ln(m.devSessionId);let Nr=async()=>{Fr(),Or(),t.stop(),p.close(),V.stop(),Ur(),Mr(),_r(),$r(),await h.close(),await n.stop(),await H.stop().catch(()=>{}),await Promise.race([y({config:e,document:In,variables:{cwd:e.cwd,projectId:e.projectId}}).catch(()=>{}),new Promise(jr=>setTimeout(jr,3e3))]),o()},k=()=>{Nr().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 Cn(e){let r={handler:()=>{}},o=yr({config:e,onChanged:()=>{r.handler()}}),n=$n(),t=dr({config:e,pool:n.pool,executorIsLocal:()=>o.current()==="local"});return r.handler=t.notifyExecutorChanged,{executorSwitch:o,exploration:t,poolGate:n}}function Tn({cwd:e,pool:r}){return fe({localDir:wn.join(e,".ripplo",".local"),writePortFile:!0,onRrwebBatch:()=>{},onSpan:o=>{let n=o.attributes["ripplo.run"];n!=null&&r.routeSpan(n,o)}})}function Ln(e){process.stdout.write(`${Pe({devSessionId:e,version:ee()})}
|
|
133
|
+
`)}function Wn({config:e,session:r}){let o=async()=>{try{let t=await y({config:e,document:En,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()},Pn);return()=>{clearInterval(n)}}function An({claim:e,config:r,cwd:o,initialId:n,pool:t,sseClient:i,sseHealth:a}){let l=n,d=null,u=0,p=0,c=g=>{P(g)},f=()=>{let g=Ve({claim:e,cwd:o,devSessionId:l,onSubscriptionDead:c,pool:t,sseClient:i,sseHealth:a}),S=Ye({cwd:o,devSessionId:l,onSubscriptionDead:c,sseClient:i});return()=>{g(),S()}},m=f(),w=async g=>{let S=Date.now();u=S-p>Hr*2?1:u+1,p=S,u>=Rn&&a.markUnhealthy(g),await Dn(Math.min(1e3*2**(u-1),Hr));let h=await U(o);if(h.isErr()){s.error("re-register: compile failed: %s",M(h.error));return}let H=await qr(()=>Ue({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 Dn(e){return new Promise(r=>setTimeout(r,e))}function Hn({cwd:e,devSessionId:r,initialConcurrency:o}){return xr({devSessionId:r,initialSize:o,spawn:kr(zn(),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:re(oe,t)}}})}function qn(e){try{return ye({cwd:e,onCompromised:Un})}catch(r){throw r instanceof me&&(process.stderr.write(`${Re({cwd:r.cwd,pid:r.pid})}
|
|
134
|
+
`),process.exit(1)),r}}function Un(){s.error("daemon lock compromised; shutting down"),process.stderr.write(`${Ee()}
|
|
135
|
+
`),process.exit(1)}function Mn(){let e={handler:()=>{}};return{promise:new Promise(o=>{e.handler=o}),resolve:()=>{e.handler()}}}async function _n({cwd:e,ipc:r,releasePid:o}){return(await tr({cwd:e,onConnection:r.handleConnection})).match(t=>t,t=>{process.stderr.write(`${ve(t)}
|
|
136
|
+
`),o(),process.exit(1)})}function $n(){let e={provide:()=>{}};return{pool:new Promise(o=>{e.provide=o}),provide:o=>{e.provide(o)}}}function Fn(e){return v(e).match(r=>r,r=>{process.stderr.write(`${ie(r)}
|
|
137
|
+
`),process.exit(1)})}function qr(e,{config:r,label:o}){let n=r.ripploServerUrl.includes("localhost")||r.ripploServerUrl.includes("127.0.0.1");return vn(async()=>{try{return await e()}catch(t){On({config:r,error:t});let i=t instanceof Error?t.message:String(t);throw Nn(i)?t:(s.error("%s failed: %s",o,i),new kn(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 On({config:e,error:r}){let o=Y(r);o==="UNAUTHENTICATED"&&(process.stderr.write(`ripplo: ${xe()}
|
|
138
|
+
`),process.exit(1)),o==="FORBIDDEN"&&(process.stderr.write(`ripplo: ${ke({projectId:e.projectId,serverUrl:e.ripploServerUrl})}
|
|
139
|
+
`),process.exit(1))}function Nn(e){return e.includes("status 502")||e.includes("ECONNREFUSED")||e.includes("Failed to connect")||e.includes("fetch failed")}function jn(){q({maxRuns:Dr});let e=setInterval(()=>{q({maxRuns:Dr})},xn);return()=>{clearInterval(e)}}function Bn(){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 Kn=4;async function Gn(e){try{let o=(await y({config:e,document:bn,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 Kn}function zn(){let e=process.argv[1];if(e==null)throw new Error("cli entry unavailable");return e}export{zi as runDaemon};
|