sootsim 0.1.244 → 0.1.246

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.
Files changed (142) hide show
  1. package/dist-cli/bin.js +4 -4
  2. package/dist-cli/chunks/{agent-JHD2EFVR.js → agent-B2XKHFH2.js} +2 -2
  3. package/dist-cli/chunks/{agent-wrapper-J2H5SHMV.js → agent-wrapper-UICUFJEJ.js} +2 -2
  4. package/dist-cli/chunks/{app-fonts-5GKCFKI5.js → app-fonts-3NXTOGC6.js} +2 -2
  5. package/dist-cli/chunks/{assert-QEJ27UYY.js → assert-6AX3MOLX.js} +2 -2
  6. package/dist-cli/chunks/{auth-HHF3YPTH.js → auth-MYFNB547.js} +2 -2
  7. package/dist-cli/chunks/beta-XSTWPVNL.js +2 -0
  8. package/dist-cli/chunks/{camera-WUKBXPW7.js → camera-7QKITKIQ.js} +2 -2
  9. package/dist-cli/chunks/{chunk-3D6IXEES.js → chunk-2NAUITBE.js} +2 -2
  10. package/dist-cli/chunks/{chunk-YULJQBOJ.js → chunk-3CXN2CRU.js} +1 -1
  11. package/dist-cli/chunks/{chunk-5ESYYH63.js → chunk-3MWRVAIS.js} +2 -2
  12. package/dist-cli/chunks/chunk-3QLXLX55.js +1 -0
  13. package/dist-cli/chunks/{chunk-2D62IZA6.js → chunk-3S3JZR2C.js} +2 -2
  14. package/dist-cli/chunks/{chunk-WM6FZGUL.js → chunk-3SVLVFLE.js} +2 -2
  15. package/dist-cli/chunks/{chunk-R2DSJS7L.js → chunk-6EQOR5WW.js} +2 -2
  16. package/dist-cli/chunks/{chunk-LRSVGYTU.js → chunk-B6QHV35G.js} +1 -1
  17. package/dist-cli/chunks/{chunk-G5F4MWYF.js → chunk-B7LILV2Q.js} +1 -1
  18. package/dist-cli/chunks/{chunk-UEHOXLFD.js → chunk-CFVKQHZA.js} +6 -6
  19. package/dist-cli/chunks/{chunk-HH5BFXN5.js → chunk-CY2RNPJB.js} +2 -2
  20. package/dist-cli/chunks/{chunk-QRQRHX3L.js → chunk-D4JXR3AG.js} +2 -2
  21. package/dist-cli/chunks/chunk-D4XZ5NEJ.js +1 -0
  22. package/dist-cli/chunks/{chunk-CAAFEEFM.js → chunk-E64QZM6K.js} +3 -3
  23. package/dist-cli/chunks/{chunk-JM7KI2DG.js → chunk-EJMHVFJ6.js} +2 -2
  24. package/dist-cli/chunks/{chunk-67ZCDTCV.js → chunk-EKYPPHQ6.js} +1 -1
  25. package/dist-cli/chunks/{chunk-MZWAGLVV.js → chunk-F5BJD6Z5.js} +2 -2
  26. package/dist-cli/chunks/{chunk-PWDCBXRI.js → chunk-FZF3UW6C.js} +2 -2
  27. package/dist-cli/chunks/{chunk-WR36BYQG.js → chunk-HR5I5I3F.js} +2 -2
  28. package/dist-cli/chunks/{chunk-JEQXLBYH.js → chunk-HST7SYF5.js} +1 -1
  29. package/dist-cli/chunks/{chunk-DL3M4AVQ.js → chunk-HYHHQXLJ.js} +1 -1
  30. package/dist-cli/chunks/{chunk-TL5J6UCV.js → chunk-J7KMGE4S.js} +1 -1
  31. package/dist-cli/chunks/{chunk-CW6ZDGC2.js → chunk-K7JYLDUZ.js} +1 -1
  32. package/dist-cli/chunks/{chunk-K375R6PR.js → chunk-KUHWG5A3.js} +2 -2
  33. package/dist-cli/chunks/{chunk-MG2NFJOU.js → chunk-MJDIZUU2.js} +1 -1
  34. package/dist-cli/chunks/{chunk-PLVKGUKI.js → chunk-N3JXF26I.js} +2 -2
  35. package/dist-cli/chunks/{chunk-6BB55GST.js → chunk-NUJBILY7.js} +1 -1
  36. package/dist-cli/chunks/{chunk-WGU7SGOZ.js → chunk-NZLTTSKI.js} +2 -2
  37. package/dist-cli/chunks/{chunk-G6O6YSIV.js → chunk-ODGON2JD.js} +2 -2
  38. package/dist-cli/chunks/{chunk-QDSYYPBW.js → chunk-PK3IUSQE.js} +1 -1
  39. package/dist-cli/chunks/{chunk-D5ZQSHVC.js → chunk-PZ3WING3.js} +3 -3
  40. package/dist-cli/chunks/{chunk-SEW3SBFZ.js → chunk-RQIX3DGK.js} +2 -2
  41. package/dist-cli/chunks/{chunk-2OPBDHZC.js → chunk-S3Z2QPNE.js} +2 -2
  42. package/dist-cli/chunks/{chunk-I5L4NSXA.js → chunk-SEQG3JCB.js} +3 -3
  43. package/dist-cli/chunks/{chunk-5MSFB4LE.js → chunk-SG737QIC.js} +1 -1
  44. package/dist-cli/chunks/{chunk-OTHI65BB.js → chunk-SRRNKOGW.js} +1 -1
  45. package/dist-cli/chunks/{chunk-7YLGDFKU.js → chunk-SYR5I5FQ.js} +2 -2
  46. package/dist-cli/chunks/{chunk-Y2KQOMYR.js → chunk-T3U2KTTT.js} +3 -3
  47. package/dist-cli/chunks/{chunk-VJYSRAHZ.js → chunk-W7NCZBX7.js} +2 -2
  48. package/dist-cli/chunks/{chunk-DOSHBZMI.js → chunk-XFVWTZ23.js} +2 -2
  49. package/dist-cli/chunks/{chunk-S4KDO7C5.js → chunk-XIF34IJ4.js} +1 -1
  50. package/dist-cli/chunks/{chunk-LJTFFZX3.js → chunk-Y34GLBNG.js} +1 -1
  51. package/dist-cli/chunks/{chunk-SIKHCBXV.js → chunk-ZFSRTTOK.js} +2 -2
  52. package/dist-cli/chunks/{chunk-XVEN5M47.js → chunk-ZNESHNGU.js} +1 -1
  53. package/dist-cli/chunks/cli-version-B6VBZEC3.js +2 -0
  54. package/dist-cli/chunks/{compat-FGJWV5EA.js → compat-RXZRDAOP.js} +3 -3
  55. package/dist-cli/chunks/{config-NYQSNDVQ.js → config-VT2IFXU3.js} +2 -2
  56. package/dist-cli/chunks/{control-UDPDWRBU.js → control-ZGVBXUKX.js} +2 -2
  57. package/dist-cli/chunks/daemon-ZNA3KPVC.js +2 -0
  58. package/dist-cli/chunks/{debug-IPQI54AY.js → debug-DMGFVLVY.js} +3 -3
  59. package/dist-cli/chunks/{desktop-GSMA5PJQ.js → desktop-X7AIXTSV.js} +3 -3
  60. package/dist-cli/chunks/{detox-4ZNSSEAR.js → detox-MACOPSN4.js} +2 -2
  61. package/dist-cli/chunks/{device-HYTTW3OU.js → device-26UCIQR6.js} +2 -2
  62. package/dist-cli/chunks/{diagnose-XQ74L3KW.js → diagnose-AEMWNDXK.js} +2 -2
  63. package/dist-cli/chunks/drivers-32VZDOVK.js +2 -0
  64. package/dist-cli/chunks/{film-WOJZUOFM.js → film-TOAWKS2S.js} +3 -3
  65. package/dist-cli/chunks/flow-WDPJS4XN.js +2 -0
  66. package/dist-cli/chunks/help-YJJVDAWG.js +2 -0
  67. package/dist-cli/chunks/{hidden-runtime-alias-C5LGEAKX.js → hidden-runtime-alias-6NMYXNDI.js} +2 -2
  68. package/dist-cli/chunks/{home-paths-RXADRYAC.js → home-paths-LAXFFU5H.js} +2 -2
  69. package/dist-cli/chunks/inspect-NNFBJJ6S.js +2 -0
  70. package/dist-cli/chunks/install-desktop-D2T7YBDG.js +2 -0
  71. package/dist-cli/chunks/{login-6TAIMXBQ.js → login-IALPZ4N3.js} +4 -4
  72. package/dist-cli/chunks/{logout-JKPUYSSG.js → logout-QGEZCNKH.js} +2 -2
  73. package/dist-cli/chunks/{maestro-GI6ZTN3M.js → maestro-HCUHTM7Q.js} +3 -3
  74. package/dist-cli/chunks/{maestro-generate-LGAIYEDS.js → maestro-generate-BTY3GXPW.js} +3 -3
  75. package/dist-cli/chunks/{mode-24IUHOZN.js → mode-E757X6CB.js} +2 -2
  76. package/dist-cli/chunks/optional-demo-registry-LQ5PVY7F.js +2 -0
  77. package/dist-cli/chunks/{perf-OKN7B352.js → perf-HR7HIYOC.js} +2 -2
  78. package/dist-cli/chunks/{record-UDMEZBYE.js → record-KETNZERF.js} +3 -3
  79. package/dist-cli/chunks/runtime-EHXI3CKI.js +2 -0
  80. package/dist-cli/chunks/{screenshot-command-HCPVVXHF.js → screenshot-command-Y453MLOW.js} +3 -3
  81. package/dist-cli/chunks/{screenshots-capture-EE64JRBF.js → screenshots-capture-UIG4IPUM.js} +2 -2
  82. package/dist-cli/chunks/{serve-U2YX7JT3.js → serve-DCU6T775.js} +13 -13
  83. package/dist-cli/chunks/{setup-C7UXZ3EU.js → setup-JJVYORE2.js} +3 -3
  84. package/dist-cli/chunks/{skills-4BH6IQLH.js → skills-KXAIFXHH.js} +2 -2
  85. package/dist-cli/chunks/{storage-SOJGFOLK.js → storage-C6Y3VROY.js} +2 -2
  86. package/dist-cli/chunks/store-6DZRG5UR.js +2 -0
  87. package/dist-cli/chunks/telemetry-QR7MMV7W.js +2 -0
  88. package/dist-cli/chunks/{timeline-BTQDQ7GF.js → timeline-C2YWWW2G.js} +2 -2
  89. package/dist-cli/chunks/{upgrade-4WPELESU.js → upgrade-5MQWHLVS.js} +2 -2
  90. package/dist-cli/chunks/upload-3TTQ7WQM.js +2 -0
  91. package/dist-cli/chunks/{version-6TAD2HKX.js → version-REDCHLR4.js} +2 -2
  92. package/dist-cli/chunks/{web-F3TBVSMC.js → web-MMLEB6FJ.js} +2 -2
  93. package/dist-cli/chunks/{what-happened-OICHDCFR.js → what-happened-AEUYMR3B.js} +2 -2
  94. package/dist-lib/agent-daemon-client.cjs +1 -1
  95. package/dist-lib/agent-events.cjs +1 -1
  96. package/dist-lib/agent-identity.cjs +1 -1
  97. package/dist-lib/agent-sessions.cjs +1 -1
  98. package/dist-lib/attached-projects.cjs +1 -1
  99. package/dist-lib/auth/shared-session.cjs +1 -1
  100. package/dist-lib/backend-origin.cjs +1 -1
  101. package/dist-lib/beta.cjs +1 -1
  102. package/dist-lib/beta.mjs +1 -1
  103. package/dist-lib/bridge-constants.cjs +1 -1
  104. package/dist-lib/cli-constants.cjs +1 -1
  105. package/dist-lib/config.cjs +1 -1
  106. package/dist-lib/detox/index.cjs +1 -1
  107. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  108. package/dist-lib/home-paths.cjs +1 -1
  109. package/dist-lib/host/bridge-host.cjs +11 -3
  110. package/dist-lib/host/fetch-proxy-handler.cjs +11 -3
  111. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  112. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  113. package/dist-lib/host/websocket-proxy.cjs +1 -1
  114. package/dist-lib/index.cjs +1 -1
  115. package/dist-lib/jump-to-source-babel.cjs +1 -1
  116. package/dist-lib/menu.cjs +1 -1
  117. package/dist-lib/menu.mjs +1 -1
  118. package/dist-lib/metro.cjs +1 -1
  119. package/dist-lib/profiles.cjs +1 -1
  120. package/dist-lib/render-mode.cjs +1 -1
  121. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  122. package/dist-lib/sdk.cjs +1 -1
  123. package/dist-lib/sdk.mjs +1 -1
  124. package/dist-lib/skills.cjs +11 -3
  125. package/dist-lib/vite.cjs +1 -1
  126. package/package.json +1 -1
  127. package/src/host/fetch-proxy-handler.ts +15 -0
  128. package/dist-cli/chunks/beta-G5FZ5RSW.js +0 -2
  129. package/dist-cli/chunks/chunk-HAAUOADL.js +0 -1
  130. package/dist-cli/chunks/chunk-MKA7IFWN.js +0 -1
  131. package/dist-cli/chunks/cli-version-XDAICYFB.js +0 -2
  132. package/dist-cli/chunks/daemon-2J4DKNYN.js +0 -2
  133. package/dist-cli/chunks/drivers-ONFQAFOU.js +0 -2
  134. package/dist-cli/chunks/flow-LVERPR3B.js +0 -2
  135. package/dist-cli/chunks/help-EMMS3CAK.js +0 -2
  136. package/dist-cli/chunks/inspect-SSNBQY3F.js +0 -2
  137. package/dist-cli/chunks/install-desktop-UYHELYFF.js +0 -2
  138. package/dist-cli/chunks/optional-demo-registry-UQEDFVFZ.js +0 -2
  139. package/dist-cli/chunks/runtime-VSCBA7IR.js +0 -2
  140. package/dist-cli/chunks/store-4HP2JT7J.js +0 -2
  141. package/dist-cli/chunks/telemetry-KGIV6FY7.js +0 -2
  142. package/dist-cli/chunks/upload-D22GTV4Y.js +0 -2
@@ -1,25 +1,25 @@
1
- /*! sootsim v0.1.244 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{b as pe,c as $,d as me,e as j,f as he,h as fe,i as E,j as ge,k as Se,l as ye,p as ve,s as k,t as be,u as we,v as Ae,w as ke}from"./chunk-WGU7SGOZ.js";import"./chunk-JEQXLBYH.js";import{e as ue}from"./chunk-K375R6PR.js";import"./chunk-WM6FZGUL.js";import{h as de}from"./chunk-MZWAGLVV.js";import{f as _,g as ce}from"./chunk-7YLGDFKU.js";import"./chunk-DL3M4AVQ.js";import"./chunk-XVEN5M47.js";import{d as le}from"./chunk-CW6ZDGC2.js";import"./chunk-6BB55GST.js";import"./chunk-R2DSJS7L.js";import{a as re,b as ne}from"./chunk-PLVKGUKI.js";import"./chunk-PWDCBXRI.js";import{a as oe,b as ae}from"./chunk-OTHI65BB.js";import"./chunk-S4KDO7C5.js";import{E as q,G as O,H as U,I as z,J as F,L as X,M as Y,O as Z,Q,R as ee,S as te,T as W,U as ie,h as G,y as H,z as V}from"./chunk-LJTFFZX3.js";import{a as se}from"./chunk-MG2NFJOU.js";import"./chunk-QDSYYPBW.js";import{spawn as mt}from"child_process";import T from"fs";import{createServer as ht}from"http";import w from"path";import{WebSocket as h,WebSocketServer as ft}from"ws";import Ee from"node:fs";import x from"node:path";import{spawn as Ue}from"node:child_process";import Fe from"node:fs";import We from"node:os";import $e from"node:path";var Ie=/^[A-Za-z0-9._:-]{1,160}$/;function J(o){if(!o?.startsWith("AGENTBUS_SESSION:"))return null;let e=o.slice(17).trim();return Ie.test(e)?e:null}function Ce(o){return Ie.test(o)}function je(o){return typeof o.text=="string"?o.text.trim():""}function Je(o){let e=o?.trim();if(e)return e;let t=process.env.AGENTBUS_COMMAND?.trim();if(t)return t;let i=$e.join(We.homedir(),".local","bin","agentbus");return Fe.existsSync(i)?i:"agentbus"}async function Te(o){let e=o.sessionId.trim();if(!Ce(e))throw new Error(`invalid agentbus session id: ${e||"<empty>"}`);let t=je(o.prompt);if(!t)throw new Error("prompt text is empty");let i=Je(o.command),s=o.timeoutMs??15e3;await new Promise((n,a)=>{let r=Ue(i,["send",e,t],{stdio:["ignore","ignore","pipe"],env:process.env}),c="",l=setTimeout(()=>{try{r.kill("SIGTERM")}catch{}a(new Error(`agentbus send timed out after ${Math.round(s/1e3)}s`))},s);r.stderr?.setEncoding("utf8"),r.stderr?.on("data",d=>{c.length<4e3&&(c+=String(d))}),r.on("error",d=>{clearTimeout(l),a(d)}),r.on("exit",(d,u)=>{if(clearTimeout(l),d===0){n();return}let m=c.trim();a(new Error(m||`agentbus send exited with ${u?`signal ${u}`:`code ${d??"unknown"}`}`))})})}var L=1;function Ke(){return[Number(process.env.VITE_PORT_WEB||process.env.PORT||3e3),Number(process.env.VITE_PORT_ZERO||7849),Number(process.env.VITE_PORT_R2||9500)].filter(o=>Number.isFinite(o)&&o>0)}var B=class{subscriptions=new Map;sessionsBySocket=new Map;allSockets=new Set;pendingPromptEchoes=new Map;pendingTurns=new Map;opts;constructor(e={}){this.opts=e}registerSocket(e){this.allSockets.add(e)}unregisterSocket(e){let t=this.sessionsBySocket.get(e);if(t){for(let i of t)this.decrementSubscription(i);this.sessionsBySocket.delete(e)}this.allSockets.delete(e)}async handleMessage(e,t){let i=t?.type;if(typeof i!="string"||!i.startsWith("agent:"))return!1;let s=t.id;try{let n=await this.dispatch(e,i,t);this.respond(e,s,n)}catch(n){n instanceof k?this.respondError(e,s,n.message,n.code):this.respondError(e,s,n instanceof Error?n.message:String(n))}return!0}async seedOnBoot(){try{await ye()}catch(e){process.stderr.write(`[sootsim-agent] seedFromDemoAppRegistry failed: ${e instanceof Error?e.message:String(e)}
3
- `)}}close(){for(let e of this.subscriptions.values())try{e.unsubscribe()}catch{}this.subscriptions.clear(),this.sessionsBySocket.clear(),this.allSockets.clear()}async dispatch(e,t,i){switch(t){case"agent:list-projects":return j();case"agent:upsert-project":return $(i.input??{});case"agent:delete-project":return fe(String(i.projectId)),{ok:!0};case"agent:auto-attach-for-url":return this.autoAttachForUrl(i.input??{});case"agent:list-sessions":return ge(i.projectId?String(i.projectId):void 0);case"agent:start-session":return this.doStartSession(i.input??{});case"agent:send-claimed-prompt":return this.sendClaimedPrompt(i);case"agent:send-prompt":{let n=String(i.sessionId),a=E(n);if(!a)throw new k("NO_SESSION",`no session: ${n}`);let r=this.normalizePromptEnvelope(i);return await we(n,r),this.notePromptAccepted(n,r,a.status==="working")}case"agent:end-session":this.dropSessionFanout(String(i.sessionId)),await Ae(String(i.sessionId));let s=E(String(i.sessionId));return s&&this.broadcastSessionStatus(s),{ok:!0};case"agent:get-transcript":return this.getTranscript(String(i.sessionId));case"agent:get-paths":return this.getPaths();case"agent:subscribe-events":return this.subscribeSocket(e,String(i.sessionId));case"agent:unsubscribe-events":return this.unsubscribeSocket(e,String(i.sessionId));default:throw new k("UNKNOWN_AGENT_MSG",`unknown agent message: ${t}`)}}async sendClaimedPrompt(e){let t=typeof e.simId=="string"?e.simId.trim():"";if(!t)throw new k("NO_SIM","agent:send-claimed-prompt requires simId");let i=this.opts.resolveCliLease?.(t)??null;if(!i||i.kind!=="cli"||i.expiresAt<=Date.now())throw new k("NO_CLAIM",`sim ${t} has no active CLI claim`);let s=J(i.cliIdentityKey);if(!s)throw new k("UNSUPPORTED_CLAIM",`sim ${t} is claimed by a CLI identity that is not promptable`);return await Te({sessionId:s,prompt:this.normalizePromptEnvelope(e)}),{ok:!0,routed:"agentbus",sessionId:s}}async doStartSession(e){if(!me(e.projectId))throw new k("NO_PROJECT",`no project: ${e.projectId}`);let i=await be(e);return this.broadcastSessionStatus(i.session),i}async autoAttachForUrl(e){let t=e.bundleUrl??"",i=(()=>{try{return new URL(t).port||null}catch{return null}})();if(!i)return{project:null};let s=this.opts.getExcludePorts?.()??Ke(),a=(await _({excludePorts:s})).find(d=>String(d.port)===i);if(!a||!a.cwd)return{project:null};let r=j().find(d=>d.cwd===a.cwd)??null,c=Array.from(new Set([...r?.knownBundleUrls??[],a.bundleUrl,t]));return{project:$({cwd:a.cwd,name:a.projectName??x.basename(a.cwd),preferredProvider:e.provider??r?.preferredProvider,sourceRoots:r?.sourceRoots??[a.cwd],knownBundleUrls:c,framework:r?.framework??Ge(a.framework),bundleId:a.bundleId??r?.bundleId})}}getTranscript(e){let t=ve(e);return Ee.existsSync(t)?Ee.readFileSync(t,"utf8"):{error:"transcript not found",code:"NO_TRANSCRIPT"}}getPaths(){let e=pe();return{userDataDir:e,storeFile:x.join(e,"attached-projects.json"),sessionsDir:x.join(e,"sessions"),transcriptsDir:x.join(e,"transcripts")}}subscribeSocket(e,t){let i=this.sessionsBySocket.get(e);if(i||(i=new Set,this.sessionsBySocket.set(e,i)),i.has(t))return{ok:!0,refCount:this.subscriptions.get(t)?.refCount??1};i.add(t);let s=this.subscriptions.get(t);if(s)return s.refCount++,{ok:!0,refCount:s.refCount};let n=ke(t,a=>{let r=this.coalescePromptEcho(t,a);if(r&&(this.applySessionEvent(t,r),this.fanOutEvent(t,r)),a.type==="turn-completed"){let c=E(t);if(c)try{he(c.projectId,{usd:a.costUsd,ts:a.ts})}catch(l){process.stderr.write(`[sootsim-agent] recordTurnTelemetry failed: ${l instanceof Error?l.message:String(l)}
4
- `)}}});return this.subscriptions.set(t,{unsubscribe:n,refCount:1}),{ok:!0,refCount:1}}unsubscribeSocket(e,t){let i=this.sessionsBySocket.get(e);return!i||!i.has(t)?{ok:!0,refCount:0}:(i.delete(t),this.decrementSubscription(t))}decrementSubscription(e){let t=this.subscriptions.get(e);if(!t)return{ok:!0,refCount:0};if(t.refCount--,t.refCount<=0){try{t.unsubscribe()}catch{}return this.subscriptions.delete(e),{ok:!0,refCount:0}}return{ok:!0,refCount:t.refCount}}dropSessionFanout(e){let t=this.subscriptions.get(e);if(t){try{t.unsubscribe()}catch{}this.subscriptions.delete(e)}for(let i of this.sessionsBySocket.values())i.delete(e);this.clearPromptTracking(e)}normalizePromptEnvelope(e){if(e?.prompt&&typeof e.prompt=="object"){let t=e.prompt;return{text:String(t.text??""),...typeof t.displayText=="string"?{displayText:t.displayText}:{},...typeof t.inspectSummary=="string"?{inspectSummary:t.inspectSummary}:{},...typeof t.inspectTrace=="string"?{inspectTrace:t.inspectTrace}:{}}}return{text:String(e?.text??""),...typeof e?.displayText=="string"?{displayText:e.displayText}:{},...typeof e?.inspectSummary=="string"?{inspectSummary:e.inspectSummary}:{},...typeof e?.inspectTrace=="string"?{inspectTrace:e.inspectTrace}:{}}}notePromptAccepted(e,t,i){let s=Date.now(),n=this.pendingPromptEchoes.get(e)??[];n.push({sentAt:s}),this.pendingPromptEchoes.set(e,n);let a=Math.max(this.pendingTurns.get(e)??0,i?1:0)+1;this.pendingTurns.set(e,a);let r=t.displayText??t.text;return this.patchSession(e,{lastPrompt:r,status:"working",needsAttention:!1}),this.fanOutEvent(e,{type:"prompt-received",text:r,...t.inspectSummary?{inspectSummary:t.inspectSummary}:{},...t.inspectTrace?{inspectTrace:t.inspectTrace}:{},ts:s}),{ok:!0,queued:a>1,pendingTurns:a,queueDepth:Math.max(0,a-1)}}applySessionEvent(e,t){switch(t.type){case"prompt-received":case"turn-started":this.patchSession(e,{status:"working",needsAttention:!1});return;case"turn-completed":{let i=this.consumeSettledTurn(e);this.patchSession(e,{status:i>0?"working":"idle",needsAttention:!1,lastTurnFiles:t.filesTouched,currentlyEditing:void 0});return}case"approval-needed":this.patchSession(e,{status:"needs-attention",needsAttention:!0});return;case"error":{let i=this.consumeSettledTurn(e);this.patchSession(e,{status:i>0?"working":"needs-attention",needsAttention:i<=0,currentlyEditing:void 0});return}case"exited":this.clearPromptTracking(e),this.patchSession(e,{status:"ended",needsAttention:!1,wrapperPid:void 0,currentlyEditing:void 0});return;case"ready":case"turn-reasoning":case"turn-message":case"turn-plan":case"tool-call":case"file-edited":case"file-diff-delta":return}}patchSession(e,t){Se(e,t);let i=E(e);i&&this.broadcastSessionStatus(i)}coalescePromptEcho(e,t){if(t.type!=="prompt-received")return t;let i=this.pendingPromptEchoes.get(e);if(!i||i.length===0)return t;for(;i.length>0&&Date.now()-i[0].sentAt>15e3;)i.shift();return i.length===0?(this.pendingPromptEchoes.delete(e),t):(i.shift(),i.length===0?this.pendingPromptEchoes.delete(e):this.pendingPromptEchoes.set(e,i),null)}consumeSettledTurn(e){let t=Math.max(0,(this.pendingTurns.get(e)??1)-1);return t>0?this.pendingTurns.set(e,t):this.pendingTurns.delete(e),t}clearPromptTracking(e){this.pendingPromptEchoes.delete(e),this.pendingTurns.delete(e)}fanOutEvent(e,t){let i=JSON.stringify({type:"agent:event",sessionId:e,event:t});for(let[s,n]of this.sessionsBySocket)if(n.has(e)&&s.readyState===L)try{s.send(i)}catch{}}broadcastSessionStatus(e){let t=JSON.stringify({type:"agent:session-status",session:e});for(let i of this.allSockets)if(i.readyState===L)try{i.send(t)}catch{}}respond(e,t,i){if(e.readyState===L)try{e.send(JSON.stringify({id:t,result:i}))}catch{}}respondError(e,t,i,s){if(e.readyState===L)try{e.send(JSON.stringify({id:t,error:i,...s?{code:s}:{}}))}catch{}}};function Ge(o){return o==="expo"?"expo":o==="one"||o==="vxrn"?"one":"unknown"}import Re from"http";import Oe from"https";import{finished as ze,pipeline as Xe}from"stream/promises";var K="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36",Ve=[{hostSuffix:"uniswap.org",headers:{origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/"},suppressBrowserUserAgent:!0}];function qe(o){let e=o.toLowerCase();for(let t of Ve)if(e===t.hostSuffix||e.endsWith(`.${t.hostSuffix}`))return t}function Pe(o){let e=qe(o.hostname);return{"accept-encoding":"identity",...e?.suppressBrowserUserAgent?{}:{"user-agent":K},...e?.headers}}var Ye=new Set(["host","origin","referer","user-agent","accept-encoding","cookie","connection","keep-alive","transfer-encoding","upgrade","content-length","sec-fetch-site","sec-fetch-mode","sec-fetch-dest","sec-ch-ua","sec-ch-ua-mobile","sec-ch-ua-platform"]),Ze={"access-control-allow-origin":"*","access-control-allow-methods":"GET,POST,PUT,DELETE,PATCH,OPTIONS","access-control-allow-headers":"*","access-control-expose-headers":"*","access-control-max-age":"3600"},Qe=new Set(["host","origin","referer","sec-fetch-site","sec-fetch-mode","sec-fetch-dest"]);function P(o){for(let[e,t]of Object.entries(Ze))o.setHeader(e,t)}function et(o,e){let t=[],i=e;i?.code&&t.push(i.code),i?.message&&t.push(i.message),i?.cause?.code&&t.push(i.cause.code),i?.cause?.message&&t.push(i.cause.message);let n=[...new Set(t.filter(Boolean))].join(" | ")||String(e);return o.includes("stored-in-.env.local")?`${n} | upstream url still contains placeholder env values`:n}function tt(o,e){let t={};for(let[i,s]of Object.entries(o))s&&(Ye.has(i.toLowerCase())||(t[i]=Array.isArray(s)?s.join(", "):s));return Object.assign(t,e?Pe(e):{"user-agent":K}),t}function it(o,e){let t={};for(let[i,s]of Object.entries(o))s&&(Qe.has(i.toLowerCase())||(t[i]=s));return t.host=e.host,t.origin=e.origin,t.referer=`${e.origin}/`,t}function _e(o){return o?.startsWith("/__fetch-proxy?")||o?.startsWith("/__proxy?")||!1}function xe(o){return o?!!(o.startsWith("/__app-api?")||o.startsWith("/__app-api/")):!1}async function Le(o,e){if(o.method==="OPTIONS"){P(e),e.writeHead(204),e.end();return}let i=new URLSearchParams((o.url||"").split("?")[1]||"").get("url");if(!i){P(e),e.writeHead(400,{"Content-Type":"text/plain"}),e.end("missing url param");return}let s;try{s=new URL(i)}catch{P(e),e.writeHead(400,{"Content-Type":"text/plain"}),e.end("invalid url param");return}let n;if(o.method!=="GET"&&o.method!=="HEAD"){let c=[];for await(let l of o)c.push(Buffer.isBuffer(l)?l:Buffer.from(l));c.length>0&&(n=Buffer.concat(c))}let a=o.method||"GET",r=async(c,l,d,u)=>{let m=c.protocol==="https:"?Oe:Re,p=tt(o.headers,c);c.origin!==s.origin&&(delete p.authorization,delete p["proxy-authorization"]),l==="GET"||l==="HEAD"?(delete p["content-length"],delete p["content-type"]):d&&(p["content-length"]=String(d.byteLength));let f=await new Promise((v,A)=>{let y=m.request({hostname:c.hostname,port:c.port||(c.protocol==="https:"?443:80),path:c.pathname+c.search,method:l,headers:p},v),R=()=>y.destroy(new Error("fetch proxy client disconnected"));o.once("aborted",R),y.once("close",()=>o.off("aborted",R)),y.once("error",A),d===void 0?y.end():y.end(d)}),S=f.statusCode??502,g=f.headers.location;if(g&&(S===301||S===302||S===303||S===307||S===308)){if(u>=10)throw f.destroy(),new Error("too many redirects");let v=(S===301||S===302)&&l==="POST"||S===303&&l!=="GET"&&l!=="HEAD",A=new URL(g,c);f.resume(),await ze(f),await r(A,v?"GET":l,v?void 0:d,u+1);return}for(let[v,A]of Object.entries(f.headers)){let y=v.toLowerCase();A===void 0||y==="set-cookie"||y==="connection"||y==="keep-alive"||y==="proxy-authenticate"||y==="proxy-authorization"||y==="te"||y==="trailer"||y==="transfer-encoding"||y==="upgrade"||y.startsWith("access-control-")||e.setHeader(v,A)}P(e);let b=f.headers["set-cookie"]??[];b.length>0&&e.setHeader("x-sootsim-set-cookie",(Array.isArray(b)?b:[b]).join(", ")),e.statusCode=S,await Xe(f,e)};try{await r(s,a,n,0)}catch(c){if(e.headersSent){e.destroy(c instanceof Error?c:new Error(String(c)));return}P(e),e.writeHead(502,{"Content-Type":"text/plain"}),e.end(`fetch proxy error: ${et(s.href,c)}`)}}function Be(o,e){let t=o.url||"",i="",s="";if(t.startsWith("/__app-api?")){let l=new URL(t,"http://sootsim.local");i=l.searchParams.get("path")||"",s=l.searchParams.get("origin")?.trim()||""}else if(t.startsWith("/__app-api/"))i=t.slice(10);else return!1;if(!s)return e.writeHead(400,{"Content-Type":"text/plain"}),e.end("app-api: missing origin query param"),!0;if(o.method==="OPTIONS")return e.writeHead(204,{"Access-Control-Allow-Origin":o.headers.origin||"*","Access-Control-Allow-Methods":"GET,POST,PUT,PATCH,DELETE,OPTIONS","Access-Control-Allow-Headers":o.headers["access-control-request-headers"]||"*","Access-Control-Allow-Credentials":"true","Access-Control-Max-Age":"86400"}),e.end(),!0;let n;try{n=new URL(i,s)}catch{return e.writeHead(400,{"Content-Type":"text/plain"}),e.end("app-api: invalid origin or path"),!0}let a=n.protocol==="https:"?Oe:Re,r=it(o.headers,n),c=a.request({hostname:n.hostname,port:n.port||(n.protocol==="https:"?443:80),path:n.pathname+n.search,method:o.method,headers:r},l=>{let d=Object.keys(l.headers).filter(u=>{let m=u.toLowerCase();return!m.startsWith("access-control-")&&m!=="set-cookie"}).join(", ");e.writeHead(l.statusCode??502,{...l.headers,"access-control-allow-origin":o.headers.origin||"*","access-control-allow-credentials":"true","access-control-expose-headers":d}),l.pipe(e)});return c.on("error",l=>{e.statusCode=502,e.end(`app proxy error: ${l.message}`)}),o.pipe(c),!0}import{WebSocket as I,WebSocketServer as rt}from"ws";var nt="/__websocket-proxy",st=new Set(["host","connection","upgrade","transfer-encoding","content-length","sec-websocket-accept","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version"]);function C(o,e,t){try{o.write(`HTTP/1.1 ${e} ${t}\r
1
+ /*! sootsim v0.1.246 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{b as pe,c as $,d as me,e as j,f as he,h as fe,i as E,j as ge,k as Se,l as ye,p as ve,s as k,t as be,u as we,v as Ae,w as ke}from"./chunk-NZLTTSKI.js";import"./chunk-HST7SYF5.js";import{e as ue}from"./chunk-KUHWG5A3.js";import"./chunk-3SVLVFLE.js";import{h as de}from"./chunk-F5BJD6Z5.js";import{f as _,g as ce}from"./chunk-SYR5I5FQ.js";import"./chunk-HYHHQXLJ.js";import"./chunk-ZNESHNGU.js";import{d as le}from"./chunk-K7JYLDUZ.js";import"./chunk-NUJBILY7.js";import"./chunk-6EQOR5WW.js";import{a as re,b as ne}from"./chunk-N3JXF26I.js";import"./chunk-FZF3UW6C.js";import{a as oe,b as ae}from"./chunk-SRRNKOGW.js";import"./chunk-XIF34IJ4.js";import{E as q,G as O,H as U,I as z,J as F,L as X,M as Y,O as Z,Q,R as ee,S as te,T as W,U as ie,h as G,y as H,z as V}from"./chunk-Y34GLBNG.js";import{a as se}from"./chunk-MJDIZUU2.js";import"./chunk-PK3IUSQE.js";import{spawn as ht}from"child_process";import C from"fs";import{createServer as ft}from"http";import w from"path";import{WebSocket as h,WebSocketServer as gt}from"ws";import Ee from"node:fs";import x from"node:path";import{spawn as Fe}from"node:child_process";import We from"node:fs";import $e from"node:os";import je from"node:path";var Ie=/^[A-Za-z0-9._:-]{1,160}$/;function J(o){if(!o?.startsWith("AGENTBUS_SESSION:"))return null;let e=o.slice(17).trim();return Ie.test(e)?e:null}function Te(o){return Ie.test(o)}function Je(o){return typeof o.text=="string"?o.text.trim():""}function Ke(o){let e=o?.trim();if(e)return e;let t=process.env.AGENTBUS_COMMAND?.trim();if(t)return t;let i=je.join($e.homedir(),".local","bin","agentbus");return We.existsSync(i)?i:"agentbus"}async function Ce(o){let e=o.sessionId.trim();if(!Te(e))throw new Error(`invalid agentbus session id: ${e||"<empty>"}`);let t=Je(o.prompt);if(!t)throw new Error("prompt text is empty");let i=Ke(o.command),s=o.timeoutMs??15e3;await new Promise((n,a)=>{let r=Fe(i,["send",e,t],{stdio:["ignore","ignore","pipe"],env:process.env}),c="",l=setTimeout(()=>{try{r.kill("SIGTERM")}catch{}a(new Error(`agentbus send timed out after ${Math.round(s/1e3)}s`))},s);r.stderr?.setEncoding("utf8"),r.stderr?.on("data",d=>{c.length<4e3&&(c+=String(d))}),r.on("error",d=>{clearTimeout(l),a(d)}),r.on("exit",(d,u)=>{if(clearTimeout(l),d===0){n();return}let m=c.trim();a(new Error(m||`agentbus send exited with ${u?`signal ${u}`:`code ${d??"unknown"}`}`))})})}var L=1;function Ge(){return[Number(process.env.VITE_PORT_WEB||process.env.PORT||3e3),Number(process.env.VITE_PORT_ZERO||7849),Number(process.env.VITE_PORT_R2||9500)].filter(o=>Number.isFinite(o)&&o>0)}var B=class{subscriptions=new Map;sessionsBySocket=new Map;allSockets=new Set;pendingPromptEchoes=new Map;pendingTurns=new Map;opts;constructor(e={}){this.opts=e}registerSocket(e){this.allSockets.add(e)}unregisterSocket(e){let t=this.sessionsBySocket.get(e);if(t){for(let i of t)this.decrementSubscription(i);this.sessionsBySocket.delete(e)}this.allSockets.delete(e)}async handleMessage(e,t){let i=t?.type;if(typeof i!="string"||!i.startsWith("agent:"))return!1;let s=t.id;try{let n=await this.dispatch(e,i,t);this.respond(e,s,n)}catch(n){n instanceof k?this.respondError(e,s,n.message,n.code):this.respondError(e,s,n instanceof Error?n.message:String(n))}return!0}async seedOnBoot(){try{await ye()}catch(e){process.stderr.write(`[sootsim-agent] seedFromDemoAppRegistry failed: ${e instanceof Error?e.message:String(e)}
3
+ `)}}close(){for(let e of this.subscriptions.values())try{e.unsubscribe()}catch{}this.subscriptions.clear(),this.sessionsBySocket.clear(),this.allSockets.clear()}async dispatch(e,t,i){switch(t){case"agent:list-projects":return j();case"agent:upsert-project":return $(i.input??{});case"agent:delete-project":return fe(String(i.projectId)),{ok:!0};case"agent:auto-attach-for-url":return this.autoAttachForUrl(i.input??{});case"agent:list-sessions":return ge(i.projectId?String(i.projectId):void 0);case"agent:start-session":return this.doStartSession(i.input??{});case"agent:send-claimed-prompt":return this.sendClaimedPrompt(i);case"agent:send-prompt":{let n=String(i.sessionId),a=E(n);if(!a)throw new k("NO_SESSION",`no session: ${n}`);let r=this.normalizePromptEnvelope(i);return await we(n,r),this.notePromptAccepted(n,r,a.status==="working")}case"agent:end-session":this.dropSessionFanout(String(i.sessionId)),await Ae(String(i.sessionId));let s=E(String(i.sessionId));return s&&this.broadcastSessionStatus(s),{ok:!0};case"agent:get-transcript":return this.getTranscript(String(i.sessionId));case"agent:get-paths":return this.getPaths();case"agent:subscribe-events":return this.subscribeSocket(e,String(i.sessionId));case"agent:unsubscribe-events":return this.unsubscribeSocket(e,String(i.sessionId));default:throw new k("UNKNOWN_AGENT_MSG",`unknown agent message: ${t}`)}}async sendClaimedPrompt(e){let t=typeof e.simId=="string"?e.simId.trim():"";if(!t)throw new k("NO_SIM","agent:send-claimed-prompt requires simId");let i=this.opts.resolveCliLease?.(t)??null;if(!i||i.kind!=="cli"||i.expiresAt<=Date.now())throw new k("NO_CLAIM",`sim ${t} has no active CLI claim`);let s=J(i.cliIdentityKey);if(!s)throw new k("UNSUPPORTED_CLAIM",`sim ${t} is claimed by a CLI identity that is not promptable`);return await Ce({sessionId:s,prompt:this.normalizePromptEnvelope(e)}),{ok:!0,routed:"agentbus",sessionId:s}}async doStartSession(e){if(!me(e.projectId))throw new k("NO_PROJECT",`no project: ${e.projectId}`);let i=await be(e);return this.broadcastSessionStatus(i.session),i}async autoAttachForUrl(e){let t=e.bundleUrl??"",i=(()=>{try{return new URL(t).port||null}catch{return null}})();if(!i)return{project:null};let s=this.opts.getExcludePorts?.()??Ge(),a=(await _({excludePorts:s})).find(d=>String(d.port)===i);if(!a||!a.cwd)return{project:null};let r=j().find(d=>d.cwd===a.cwd)??null,c=Array.from(new Set([...r?.knownBundleUrls??[],a.bundleUrl,t]));return{project:$({cwd:a.cwd,name:a.projectName??x.basename(a.cwd),preferredProvider:e.provider??r?.preferredProvider,sourceRoots:r?.sourceRoots??[a.cwd],knownBundleUrls:c,framework:r?.framework??Ve(a.framework),bundleId:a.bundleId??r?.bundleId})}}getTranscript(e){let t=ve(e);return Ee.existsSync(t)?Ee.readFileSync(t,"utf8"):{error:"transcript not found",code:"NO_TRANSCRIPT"}}getPaths(){let e=pe();return{userDataDir:e,storeFile:x.join(e,"attached-projects.json"),sessionsDir:x.join(e,"sessions"),transcriptsDir:x.join(e,"transcripts")}}subscribeSocket(e,t){let i=this.sessionsBySocket.get(e);if(i||(i=new Set,this.sessionsBySocket.set(e,i)),i.has(t))return{ok:!0,refCount:this.subscriptions.get(t)?.refCount??1};i.add(t);let s=this.subscriptions.get(t);if(s)return s.refCount++,{ok:!0,refCount:s.refCount};let n=ke(t,a=>{let r=this.coalescePromptEcho(t,a);if(r&&(this.applySessionEvent(t,r),this.fanOutEvent(t,r)),a.type==="turn-completed"){let c=E(t);if(c)try{he(c.projectId,{usd:a.costUsd,ts:a.ts})}catch(l){process.stderr.write(`[sootsim-agent] recordTurnTelemetry failed: ${l instanceof Error?l.message:String(l)}
4
+ `)}}});return this.subscriptions.set(t,{unsubscribe:n,refCount:1}),{ok:!0,refCount:1}}unsubscribeSocket(e,t){let i=this.sessionsBySocket.get(e);return!i||!i.has(t)?{ok:!0,refCount:0}:(i.delete(t),this.decrementSubscription(t))}decrementSubscription(e){let t=this.subscriptions.get(e);if(!t)return{ok:!0,refCount:0};if(t.refCount--,t.refCount<=0){try{t.unsubscribe()}catch{}return this.subscriptions.delete(e),{ok:!0,refCount:0}}return{ok:!0,refCount:t.refCount}}dropSessionFanout(e){let t=this.subscriptions.get(e);if(t){try{t.unsubscribe()}catch{}this.subscriptions.delete(e)}for(let i of this.sessionsBySocket.values())i.delete(e);this.clearPromptTracking(e)}normalizePromptEnvelope(e){if(e?.prompt&&typeof e.prompt=="object"){let t=e.prompt;return{text:String(t.text??""),...typeof t.displayText=="string"?{displayText:t.displayText}:{},...typeof t.inspectSummary=="string"?{inspectSummary:t.inspectSummary}:{},...typeof t.inspectTrace=="string"?{inspectTrace:t.inspectTrace}:{}}}return{text:String(e?.text??""),...typeof e?.displayText=="string"?{displayText:e.displayText}:{},...typeof e?.inspectSummary=="string"?{inspectSummary:e.inspectSummary}:{},...typeof e?.inspectTrace=="string"?{inspectTrace:e.inspectTrace}:{}}}notePromptAccepted(e,t,i){let s=Date.now(),n=this.pendingPromptEchoes.get(e)??[];n.push({sentAt:s}),this.pendingPromptEchoes.set(e,n);let a=Math.max(this.pendingTurns.get(e)??0,i?1:0)+1;this.pendingTurns.set(e,a);let r=t.displayText??t.text;return this.patchSession(e,{lastPrompt:r,status:"working",needsAttention:!1}),this.fanOutEvent(e,{type:"prompt-received",text:r,...t.inspectSummary?{inspectSummary:t.inspectSummary}:{},...t.inspectTrace?{inspectTrace:t.inspectTrace}:{},ts:s}),{ok:!0,queued:a>1,pendingTurns:a,queueDepth:Math.max(0,a-1)}}applySessionEvent(e,t){switch(t.type){case"prompt-received":case"turn-started":this.patchSession(e,{status:"working",needsAttention:!1});return;case"turn-completed":{let i=this.consumeSettledTurn(e);this.patchSession(e,{status:i>0?"working":"idle",needsAttention:!1,lastTurnFiles:t.filesTouched,currentlyEditing:void 0});return}case"approval-needed":this.patchSession(e,{status:"needs-attention",needsAttention:!0});return;case"error":{let i=this.consumeSettledTurn(e);this.patchSession(e,{status:i>0?"working":"needs-attention",needsAttention:i<=0,currentlyEditing:void 0});return}case"exited":this.clearPromptTracking(e),this.patchSession(e,{status:"ended",needsAttention:!1,wrapperPid:void 0,currentlyEditing:void 0});return;case"ready":case"turn-reasoning":case"turn-message":case"turn-plan":case"tool-call":case"file-edited":case"file-diff-delta":return}}patchSession(e,t){Se(e,t);let i=E(e);i&&this.broadcastSessionStatus(i)}coalescePromptEcho(e,t){if(t.type!=="prompt-received")return t;let i=this.pendingPromptEchoes.get(e);if(!i||i.length===0)return t;for(;i.length>0&&Date.now()-i[0].sentAt>15e3;)i.shift();return i.length===0?(this.pendingPromptEchoes.delete(e),t):(i.shift(),i.length===0?this.pendingPromptEchoes.delete(e):this.pendingPromptEchoes.set(e,i),null)}consumeSettledTurn(e){let t=Math.max(0,(this.pendingTurns.get(e)??1)-1);return t>0?this.pendingTurns.set(e,t):this.pendingTurns.delete(e),t}clearPromptTracking(e){this.pendingPromptEchoes.delete(e),this.pendingTurns.delete(e)}fanOutEvent(e,t){let i=JSON.stringify({type:"agent:event",sessionId:e,event:t});for(let[s,n]of this.sessionsBySocket)if(n.has(e)&&s.readyState===L)try{s.send(i)}catch{}}broadcastSessionStatus(e){let t=JSON.stringify({type:"agent:session-status",session:e});for(let i of this.allSockets)if(i.readyState===L)try{i.send(t)}catch{}}respond(e,t,i){if(e.readyState===L)try{e.send(JSON.stringify({id:t,result:i}))}catch{}}respondError(e,t,i,s){if(e.readyState===L)try{e.send(JSON.stringify({id:t,error:i,...s?{code:s}:{}}))}catch{}}};function Ve(o){return o==="expo"?"expo":o==="one"||o==="vxrn"?"one":"unknown"}import Re from"http";import Oe from"https";import{finished as Xe,pipeline as Ye}from"stream/promises";var K="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36",qe=[{hostSuffix:"uniswap.org",headers:{origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/"},suppressBrowserUserAgent:!0}];function ze(o){let e=o.toLowerCase();for(let t of qe)if(e===t.hostSuffix||e.endsWith(`.${t.hostSuffix}`))return t}function Pe(o){let e=ze(o.hostname);return{"accept-encoding":"identity",...e?.suppressBrowserUserAgent?{}:{"user-agent":K},...e?.headers}}var Ze=new Set(["host","origin","referer","user-agent","accept-encoding","cookie","connection","keep-alive","transfer-encoding","upgrade","content-length","sec-fetch-site","sec-fetch-mode","sec-fetch-dest","sec-ch-ua","sec-ch-ua-mobile","sec-ch-ua-platform"]),Qe={"access-control-allow-origin":"*","access-control-allow-methods":"GET,POST,PUT,DELETE,PATCH,OPTIONS","access-control-allow-headers":"*","access-control-expose-headers":"*","access-control-max-age":"3600"},et=new Set(["host","origin","referer","sec-fetch-site","sec-fetch-mode","sec-fetch-dest"]);function _e(o){if(o.protocol!=="https:")return{};let e=o.hostname;return e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="[::1]"?{rejectUnauthorized:!1}:{}}function P(o){for(let[e,t]of Object.entries(Qe))o.setHeader(e,t)}function tt(o,e){let t=[],i=e;i?.code&&t.push(i.code),i?.message&&t.push(i.message),i?.cause?.code&&t.push(i.cause.code),i?.cause?.message&&t.push(i.cause.message);let n=[...new Set(t.filter(Boolean))].join(" | ")||String(e);return o.includes("stored-in-.env.local")?`${n} | upstream url still contains placeholder env values`:n}function it(o,e){let t={};for(let[i,s]of Object.entries(o))s&&(Ze.has(i.toLowerCase())||(t[i]=Array.isArray(s)?s.join(", "):s));return Object.assign(t,e?Pe(e):{"user-agent":K}),t}function rt(o,e){let t={};for(let[i,s]of Object.entries(o))s&&(et.has(i.toLowerCase())||(t[i]=s));return t.host=e.host,t.origin=e.origin,t.referer=`${e.origin}/`,t}function xe(o){return o?.startsWith("/__fetch-proxy?")||o?.startsWith("/__proxy?")||!1}function Le(o){return o?!!(o.startsWith("/__app-api?")||o.startsWith("/__app-api/")):!1}async function Be(o,e){if(o.method==="OPTIONS"){P(e),e.writeHead(204),e.end();return}let i=new URLSearchParams((o.url||"").split("?")[1]||"").get("url");if(!i){P(e),e.writeHead(400,{"Content-Type":"text/plain"}),e.end("missing url param");return}let s;try{s=new URL(i)}catch{P(e),e.writeHead(400,{"Content-Type":"text/plain"}),e.end("invalid url param");return}let n;if(o.method!=="GET"&&o.method!=="HEAD"){let c=[];for await(let l of o)c.push(Buffer.isBuffer(l)?l:Buffer.from(l));c.length>0&&(n=Buffer.concat(c))}let a=o.method||"GET",r=async(c,l,d,u)=>{let m=c.protocol==="https:"?Oe:Re,p=it(o.headers,c);c.origin!==s.origin&&(delete p.authorization,delete p["proxy-authorization"]),l==="GET"||l==="HEAD"?(delete p["content-length"],delete p["content-type"]):d&&(p["content-length"]=String(d.byteLength));let f=await new Promise((v,A)=>{let y=m.request({hostname:c.hostname,port:c.port||(c.protocol==="https:"?443:80),path:c.pathname+c.search,method:l,headers:p,..._e(c)},v),R=()=>y.destroy(new Error("fetch proxy client disconnected"));o.once("aborted",R),y.once("close",()=>o.off("aborted",R)),y.once("error",A),d===void 0?y.end():y.end(d)}),S=f.statusCode??502,g=f.headers.location;if(g&&(S===301||S===302||S===303||S===307||S===308)){if(u>=10)throw f.destroy(),new Error("too many redirects");let v=(S===301||S===302)&&l==="POST"||S===303&&l!=="GET"&&l!=="HEAD",A=new URL(g,c);f.resume(),await Xe(f),await r(A,v?"GET":l,v?void 0:d,u+1);return}for(let[v,A]of Object.entries(f.headers)){let y=v.toLowerCase();A===void 0||y==="set-cookie"||y==="connection"||y==="keep-alive"||y==="proxy-authenticate"||y==="proxy-authorization"||y==="te"||y==="trailer"||y==="transfer-encoding"||y==="upgrade"||y.startsWith("access-control-")||e.setHeader(v,A)}P(e);let b=f.headers["set-cookie"]??[];b.length>0&&e.setHeader("x-sootsim-set-cookie",(Array.isArray(b)?b:[b]).join(", ")),e.statusCode=S,await Ye(f,e)};try{await r(s,a,n,0)}catch(c){if(e.headersSent){e.destroy(c instanceof Error?c:new Error(String(c)));return}P(e),e.writeHead(502,{"Content-Type":"text/plain"}),e.end(`fetch proxy error: ${tt(s.href,c)}`)}}function Me(o,e){let t=o.url||"",i="",s="";if(t.startsWith("/__app-api?")){let l=new URL(t,"http://sootsim.local");i=l.searchParams.get("path")||"",s=l.searchParams.get("origin")?.trim()||""}else if(t.startsWith("/__app-api/"))i=t.slice(10);else return!1;if(!s)return e.writeHead(400,{"Content-Type":"text/plain"}),e.end("app-api: missing origin query param"),!0;if(o.method==="OPTIONS")return e.writeHead(204,{"Access-Control-Allow-Origin":o.headers.origin||"*","Access-Control-Allow-Methods":"GET,POST,PUT,PATCH,DELETE,OPTIONS","Access-Control-Allow-Headers":o.headers["access-control-request-headers"]||"*","Access-Control-Allow-Credentials":"true","Access-Control-Max-Age":"86400"}),e.end(),!0;let n;try{n=new URL(i,s)}catch{return e.writeHead(400,{"Content-Type":"text/plain"}),e.end("app-api: invalid origin or path"),!0}let a=n.protocol==="https:"?Oe:Re,r=rt(o.headers,n),c=a.request({hostname:n.hostname,port:n.port||(n.protocol==="https:"?443:80),path:n.pathname+n.search,method:o.method,headers:r,..._e(n)},l=>{let d=Object.keys(l.headers).filter(u=>{let m=u.toLowerCase();return!m.startsWith("access-control-")&&m!=="set-cookie"}).join(", ");e.writeHead(l.statusCode??502,{...l.headers,"access-control-allow-origin":o.headers.origin||"*","access-control-allow-credentials":"true","access-control-expose-headers":d}),l.pipe(e)});return c.on("error",l=>{e.statusCode=502,e.end(`app proxy error: ${l.message}`)}),o.pipe(c),!0}import{WebSocket as I,WebSocketServer as nt}from"ws";var st="/__websocket-proxy",ot=new Set(["host","connection","upgrade","transfer-encoding","content-length","sec-websocket-accept","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version"]);function T(o,e,t){try{o.write(`HTTP/1.1 ${e} ${t}\r
5
5
  Connection: close\r
6
6
  Content-Type: text/plain\r
7
7
  Content-Length: ${t.length}\r
8
8
  \r
9
- ${t}`)}catch{}o.destroy()}function ot(o){let e=o.headers.origin,t=o.headers.host;if(!e||!t)return!1;try{return new URL(e).host===t}catch{return!1}}function at(o){if(!o)return{};let e=o.replace(/-/g,"+").replace(/_/g,"/"),t=e+"=".repeat((4-e.length%4)%4),i=JSON.parse(Buffer.from(t,"base64").toString("utf8"));if(!i||typeof i!="object"||Array.isArray(i))return{};let s={};for(let[n,a]of Object.entries(i))a!=null&&(st.has(n.toLowerCase())||(s[n]=Array.isArray(a)?a.join(", "):String(a)));return s}function ct(o){let e=new URL(o.href);return e.protocol=o.protocol==="wss:"?"https:":"http:",e.origin}function lt(o){let e=o.headers["sec-websocket-protocol"];return(Array.isArray(e)?e.join(","):e||"").split(",").map(i=>i.trim()).filter(Boolean)}function M(o,e,t){if(!(o.readyState===I.CLOSED||o.readyState===I.CLOSING))try{o.close(e,t)}catch{o.terminate()}}function dt(o,e){let t=!1,i=(s,n,a,r)=>{t||(t=!0,M(n,a,r.toString()),s.readyState===I.OPEN&&M(s,a,r.toString()))};o.on("message",(s,n)=>{e.readyState===I.OPEN&&e.send(s,{binary:n})}),e.on("message",(s,n)=>{o.readyState===I.OPEN&&o.send(s,{binary:n})}),o.on("close",(s,n)=>i(o,e,s,n)),e.on("close",(s,n)=>i(e,o,s,n)),o.on("error",()=>M(e,1011,"proxy client error")),e.on("error",()=>M(o,1011,"upstream websocket error"))}function ut(o,e,t,i){let s={...t},n=Object.keys(s).filter(a=>a.toLowerCase()==="origin");if(i&&n.length===0)s.origin=ct(o);else if(!i)for(let a of n)delete s[a];return Object.keys(s).length===0?new I(o.href,e):new I(o.href,e,{headers:s})}function pt(o){if(!o)return!1;try{return new URL(o,"http://localhost").pathname===nt}catch{return!1}}function Me(o,e,t,i=!0){if(!pt(o.url))return!1;if(!ot(o))return C(e,403,"forbidden websocket proxy origin"),!0;let s,n;try{let l=new URL(o.url||"/","http://localhost"),d=l.searchParams.get("url");if(!d)return C(e,400,"missing websocket proxy url"),!0;if(s=new URL(d),s.protocol!=="ws:"&&s.protocol!=="wss:")return C(e,400,"invalid websocket proxy protocol"),!0;n=at(l.searchParams.get("headers"))}catch{return C(e,400,"invalid websocket proxy request"),!0}let a=lt(o),r=ut(s,a,n,i),c=!1;return e.once("close",()=>{c||r.terminate()}),r.once("open",()=>{if(c)return;c=!0;let l=r.protocol;new rt({noServer:!0,clientTracking:!1,handleProtocols(u){return l||u.values().next().value||!1}}).handleUpgrade(o,e,t,u=>{dt(u,r)})}),r.once("error",()=>{c||(c=!0,C(e,502,"upstream websocket error"))}),r.once("close",()=>{c||(c=!0,C(e,502,"upstream websocket closed"))}),!0}var gt="require-corp",St=new Set(["tap","keyboard"]),yt=2e3,vt=1e3;function bt(o){return!o||typeof o.type!="string"?!1:o.acquireLock===!0?!0:o.readOnly===!0?!1:St.has(o.type)}var Ne=5e3,wt=3600*1e3,At="SOOTSIM_RUNTIME_UPDATE_INTERVAL_MS",kt={".html":"text/html; charset=utf-8",".js":"application/javascript",".cjs":"application/javascript",".mjs":"application/javascript",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp",".avif":"image/avif",".ico":"image/x-icon",".wasm":"application/wasm",".ttf":"font/ttf",".otf":"font/otf",".woff":"font/woff",".woff2":"font/woff2",".map":"application/json",".txt":"text/plain; charset=utf-8"};function De(o,e,t){let i;try{let c=H();i=JSON.stringify(c)}catch{i="{}"}let s=e>0?`window.__sootsimBridgePort=${e};`:"",n=t?`window.__sootsimContrastOrigin=${JSON.stringify(t)};`:"",a=`<script>window.__sootsimSharedConfig=${i};`+s+n+`window.__sootsimCliVersion=${JSON.stringify(se())};</script>`,r=o.toString("utf8");return r.includes("<head>")?r.replace("<head>",`<head>${a}`):r.includes("</head>")?r.replace("</head>",a+"</head>"):r.includes("</body>")?r.replace("</body>",a+"</body>"):a+r}function He(o){typeof o=="object"&&o!==null&&"unref"in o&&o.unref()}var N=class o{port;openUrlHandler;httpServer=null;wss=null;nextCommandId=1;nextSimNumber=161;sims=new Map;primarySimId=null;pendingCommands=new Map;cliBySentId=new Map;cliSimBySocket=new Map;cliLastCommandAt=new Map;cliIdentityKeyBySocket=new Map;cliLabelBySocket=new Map;restorableSims=new Map;nextCliFallbackId=1;cliIdleTimer=null;agentHost;static CLI_IDLE_TIMEOUT_MS=6e4;static CLI_LEASE_TTL_MS=6e5;static USER_ACTIVE_LEASE_TTL_MS=8e3;static USER_BOOT_LEASE_TTL_MS=6e4;static SIM_RECONNECT_TTL_MS=3e4;static SIM_IDLE_REAP_TTL_MS=30*6e4;static AUTOMATION_SIM_IDLE_REAP_TTL_MS=10*6e4;static MAX_CONCURRENT_AUTOMATION_SIMS=6;static AUTOMATION_SIM_ACTIVE_GRACE_MS=6e4;preferredPort;portFallbackCount;simIdleReapTtlMs;automationSimIdleReapTtlMs;maxConcurrentAutomationSims;automationSimActiveGraceMs;shouldWriteLockfile;shouldWriteDevLockfile;getShellPort;contrastOrigin=null;effectivePort=0;startedAt=0;heartbeatTimer=null;devHeartbeatTimer=null;wsHeartbeatTimer=null;wsIsAlive=new WeakMap;static WS_HEARTBEAT_INTERVAL_MS=3e4;runtimeUpdateTimer=null;runtimeUpdateInFlight=null;activeRuntimeVersion=null;activeRuntimeDirPath=null;scanCache=null;scanCacheAt=0;inflightScan=null;static SCAN_FRESH_MS=2e3;constructor(e={}){this.preferredPort=e.port||7668,this.port=this.preferredPort,this.shouldWriteLockfile=e.writeLockfile===!0,this.shouldWriteDevLockfile=e.writeDevLockfile===!0,this.getShellPort=e.getShellPort??null,this.portFallbackCount=Math.max(1,e.portFallbackCount??10),this.openUrlHandler=e.openUrl,this.agentHost=new B({getExcludePorts:e.agentScanExcludes,resolveCliLease:t=>{let i=this.sims.get(t),s=i?this.getActiveLease(i):null;return s?{kind:s.kind,cliIdentityKey:s.cliIdentityKey,expiresAt:s.expiresAt}:null}}),this.contrastOrigin=e.contrastOrigin?.replace(/\/$/,"")||null,this.simIdleReapTtlMs=e.simIdleReapTtlMs??o.SIM_IDLE_REAP_TTL_MS,this.automationSimIdleReapTtlMs=e.automationSimIdleReapTtlMs??o.AUTOMATION_SIM_IDLE_REAP_TTL_MS,this.maxConcurrentAutomationSims=e.maxConcurrentAutomationSims??o.MAX_CONCURRENT_AUTOMATION_SIMS,this.automationSimActiveGraceMs=e.automationSimActiveGraceMs??o.AUTOMATION_SIM_ACTIVE_GRACE_MS}getAgentHost(){return this.agentHost}reapIdleSimsForTest(e=Date.now()){this.reapIdleSims(e)}start(e){this.startAsync(e)}async startAsync(e){if(this.httpServer||this.wss)return this.effectivePort;this.refreshActiveRuntime();for(let t=0;t<this.portFallbackCount;t++){let i=this.preferredPort+t;try{return await this.bindOnce(i,e?.silent===!0),this.effectivePort=i,this.port=i,this.startedAt=Date.now(),t>0&&!e?.silent&&process.stderr.write(`ws bridge bound to port ${i} (preferred ${this.preferredPort} was taken)
9
+ ${t}`)}catch{}o.destroy()}function at(o){let e=o.headers.origin,t=o.headers.host;if(!e||!t)return!1;try{return new URL(e).host===t}catch{return!1}}function ct(o){if(!o)return{};let e=o.replace(/-/g,"+").replace(/_/g,"/"),t=e+"=".repeat((4-e.length%4)%4),i=JSON.parse(Buffer.from(t,"base64").toString("utf8"));if(!i||typeof i!="object"||Array.isArray(i))return{};let s={};for(let[n,a]of Object.entries(i))a!=null&&(ot.has(n.toLowerCase())||(s[n]=Array.isArray(a)?a.join(", "):String(a)));return s}function lt(o){let e=new URL(o.href);return e.protocol=o.protocol==="wss:"?"https:":"http:",e.origin}function dt(o){let e=o.headers["sec-websocket-protocol"];return(Array.isArray(e)?e.join(","):e||"").split(",").map(i=>i.trim()).filter(Boolean)}function M(o,e,t){if(!(o.readyState===I.CLOSED||o.readyState===I.CLOSING))try{o.close(e,t)}catch{o.terminate()}}function ut(o,e){let t=!1,i=(s,n,a,r)=>{t||(t=!0,M(n,a,r.toString()),s.readyState===I.OPEN&&M(s,a,r.toString()))};o.on("message",(s,n)=>{e.readyState===I.OPEN&&e.send(s,{binary:n})}),e.on("message",(s,n)=>{o.readyState===I.OPEN&&o.send(s,{binary:n})}),o.on("close",(s,n)=>i(o,e,s,n)),e.on("close",(s,n)=>i(e,o,s,n)),o.on("error",()=>M(e,1011,"proxy client error")),e.on("error",()=>M(o,1011,"upstream websocket error"))}function pt(o,e,t,i){let s={...t},n=Object.keys(s).filter(a=>a.toLowerCase()==="origin");if(i&&n.length===0)s.origin=lt(o);else if(!i)for(let a of n)delete s[a];return Object.keys(s).length===0?new I(o.href,e):new I(o.href,e,{headers:s})}function mt(o){if(!o)return!1;try{return new URL(o,"http://localhost").pathname===st}catch{return!1}}function Ne(o,e,t,i=!0){if(!mt(o.url))return!1;if(!at(o))return T(e,403,"forbidden websocket proxy origin"),!0;let s,n;try{let l=new URL(o.url||"/","http://localhost"),d=l.searchParams.get("url");if(!d)return T(e,400,"missing websocket proxy url"),!0;if(s=new URL(d),s.protocol!=="ws:"&&s.protocol!=="wss:")return T(e,400,"invalid websocket proxy protocol"),!0;n=ct(l.searchParams.get("headers"))}catch{return T(e,400,"invalid websocket proxy request"),!0}let a=dt(o),r=pt(s,a,n,i),c=!1;return e.once("close",()=>{c||r.terminate()}),r.once("open",()=>{if(c)return;c=!0;let l=r.protocol;new nt({noServer:!0,clientTracking:!1,handleProtocols(u){return l||u.values().next().value||!1}}).handleUpgrade(o,e,t,u=>{ut(u,r)})}),r.once("error",()=>{c||(c=!0,T(e,502,"upstream websocket error"))}),r.once("close",()=>{c||(c=!0,T(e,502,"upstream websocket closed"))}),!0}var St="require-corp",yt=new Set(["tap","keyboard"]),vt=2e3,bt=1e3;function wt(o){return!o||typeof o.type!="string"?!1:o.acquireLock===!0?!0:o.readOnly===!0?!1:yt.has(o.type)}var De=5e3,At=3600*1e3,kt="SOOTSIM_RUNTIME_UPDATE_INTERVAL_MS",It={".html":"text/html; charset=utf-8",".js":"application/javascript",".cjs":"application/javascript",".mjs":"application/javascript",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp",".avif":"image/avif",".ico":"image/x-icon",".wasm":"application/wasm",".ttf":"font/ttf",".otf":"font/otf",".woff":"font/woff",".woff2":"font/woff2",".map":"application/json",".txt":"text/plain; charset=utf-8"};function He(o,e,t){let i;try{let c=H();i=JSON.stringify(c)}catch{i="{}"}let s=e>0?`window.__sootsimBridgePort=${e};`:"",n=t?`window.__sootsimContrastOrigin=${JSON.stringify(t)};`:"",a=`<script>window.__sootsimSharedConfig=${i};`+s+n+`window.__sootsimCliVersion=${JSON.stringify(se())};</script>`,r=o.toString("utf8");return r.includes("<head>")?r.replace("<head>",`<head>${a}`):r.includes("</head>")?r.replace("</head>",a+"</head>"):r.includes("</body>")?r.replace("</body>",a+"</body>"):a+r}function Ue(o){typeof o=="object"&&o!==null&&"unref"in o&&o.unref()}var N=class o{port;openUrlHandler;httpServer=null;wss=null;nextCommandId=1;nextSimNumber=161;sims=new Map;primarySimId=null;pendingCommands=new Map;cliBySentId=new Map;cliSimBySocket=new Map;cliLastCommandAt=new Map;cliIdentityKeyBySocket=new Map;cliLabelBySocket=new Map;restorableSims=new Map;nextCliFallbackId=1;cliIdleTimer=null;agentHost;static CLI_IDLE_TIMEOUT_MS=6e4;static CLI_LEASE_TTL_MS=6e5;static USER_ACTIVE_LEASE_TTL_MS=8e3;static USER_BOOT_LEASE_TTL_MS=6e4;static SIM_RECONNECT_TTL_MS=3e4;static SIM_IDLE_REAP_TTL_MS=30*6e4;static AUTOMATION_SIM_IDLE_REAP_TTL_MS=10*6e4;static MAX_CONCURRENT_AUTOMATION_SIMS=6;static AUTOMATION_SIM_ACTIVE_GRACE_MS=6e4;preferredPort;portFallbackCount;simIdleReapTtlMs;automationSimIdleReapTtlMs;maxConcurrentAutomationSims;automationSimActiveGraceMs;shouldWriteLockfile;shouldWriteDevLockfile;getShellPort;contrastOrigin=null;effectivePort=0;startedAt=0;heartbeatTimer=null;devHeartbeatTimer=null;wsHeartbeatTimer=null;wsIsAlive=new WeakMap;static WS_HEARTBEAT_INTERVAL_MS=3e4;runtimeUpdateTimer=null;runtimeUpdateInFlight=null;activeRuntimeVersion=null;activeRuntimeDirPath=null;scanCache=null;scanCacheAt=0;inflightScan=null;static SCAN_FRESH_MS=2e3;constructor(e={}){this.preferredPort=e.port||7668,this.port=this.preferredPort,this.shouldWriteLockfile=e.writeLockfile===!0,this.shouldWriteDevLockfile=e.writeDevLockfile===!0,this.getShellPort=e.getShellPort??null,this.portFallbackCount=Math.max(1,e.portFallbackCount??10),this.openUrlHandler=e.openUrl,this.agentHost=new B({getExcludePorts:e.agentScanExcludes,resolveCliLease:t=>{let i=this.sims.get(t),s=i?this.getActiveLease(i):null;return s?{kind:s.kind,cliIdentityKey:s.cliIdentityKey,expiresAt:s.expiresAt}:null}}),this.contrastOrigin=e.contrastOrigin?.replace(/\/$/,"")||null,this.simIdleReapTtlMs=e.simIdleReapTtlMs??o.SIM_IDLE_REAP_TTL_MS,this.automationSimIdleReapTtlMs=e.automationSimIdleReapTtlMs??o.AUTOMATION_SIM_IDLE_REAP_TTL_MS,this.maxConcurrentAutomationSims=e.maxConcurrentAutomationSims??o.MAX_CONCURRENT_AUTOMATION_SIMS,this.automationSimActiveGraceMs=e.automationSimActiveGraceMs??o.AUTOMATION_SIM_ACTIVE_GRACE_MS}getAgentHost(){return this.agentHost}reapIdleSimsForTest(e=Date.now()){this.reapIdleSims(e)}start(e){this.startAsync(e)}async startAsync(e){if(this.httpServer||this.wss)return this.effectivePort;this.refreshActiveRuntime();for(let t=0;t<this.portFallbackCount;t++){let i=this.preferredPort+t;try{return await this.bindOnce(i,e?.silent===!0),this.effectivePort=i,this.port=i,this.startedAt=Date.now(),t>0&&!e?.silent&&process.stderr.write(`ws bridge bound to port ${i} (preferred ${this.preferredPort} was taken)
10
10
  `),this.afterBind(),i}catch(s){if(s?.code!=="EADDRINUSE")throw s;e?.silent||process.stderr.write(`ws bridge port ${i} already in use, trying ${i+1}
11
- `)}}throw new Error(`could not bind ws bridge after ${this.portFallbackCount} attempts starting at ${this.preferredPort}`)}bindOnce(e,t){return new Promise((i,s)=>{let n=ht((c,l)=>this.handleHttpRequest(c,l)),a=!1,r=c=>{if(!a){a=!0;try{n.close()}catch{}this.httpServer=null,this.wss=null,s(c)}};n.once("error",r),n.listen(e,"127.0.0.1",()=>{a||(a=!0,n.removeListener("error",r),n.on("error",c=>{process.stderr.write(`ws bridge http error: ${String(c)}
12
- `)}),this.httpServer=n,this.wss=new ft({noServer:!0}),this.wireWebSocketServer(),n.on("upgrade",(c,l,d)=>{Me(c,l,d)||this.wss?.handleUpgrade(c,l,d,u=>{this.wss?.emit("connection",u,c)})}),i())})})}wireWebSocketServer(){this.wss&&this.wss.on("connection",(e,t)=>{let i=t.headers.origin,s=i?"sim":"cli",n=null;if(e.on("error",()=>{}),this.wsIsAlive.set(e,!0),e.on("pong",()=>{this.wsIsAlive.set(e,!0)}),this.agentHost.registerSocket(e),s==="sim")n={id:this.allocateSimId(),ws:e,origin:i,connectedAt:Date.now(),lastSeenAt:Date.now(),lastActiveAt:0,recentActions:[]},this.sims.set(n.id,n),this.shouldPromoteSim(n)&&(this.primarySimId=n.id),this.broadcastSimAssignments(),this.broadcastSimClientStates();else{let a=`ws-${this.nextCliFallbackId++}`;this.cliIdentityKeyBySocket.set(e,a)}e.on("message",a=>{let r;try{r=JSON.parse(a.toString())}catch{return}if(!(!r||typeof r!="object")){if(typeof r.type=="string"&&r.type.startsWith("agent:")){this.agentHost.handleMessage(e,r);return}if(r.type==="runtime:list"){let c=F(),l=this.getActiveRuntime(),d={type:"runtime:list:ok",id:r.id,installed:c,active:l.version,activeRuntimeDir:l.runtimeDir};try{e.send(JSON.stringify(d))}catch{}return}if(r.type==="runtime:use"){let c=typeof r.version=="string"?r.version:"";if(!F().includes(c)){try{e.send(JSON.stringify({type:"runtime:use:error",id:r.id,error:`runtime ${c||"(missing)"} is not installed`}))}catch{}return}let d=this.setActiveRuntime(c);try{e.send(JSON.stringify({type:"runtime:use:ok",id:r.id,version:d.version,runtimeDir:d.runtimeDir}))}catch{}return}if(r.type==="runtime:get"){let c=this.getActiveRuntime();try{e.send(JSON.stringify({type:"runtime:get:ok",id:r.id,active:c.version,activeRuntimeDir:c.runtimeDir}))}catch{}return}if(s==="sim"&&r.type==="bridge:hello"&&n&&!n.url){let c=n.id;this.sims.delete(c),this.primarySimId===c&&(this.primarySimId=this.getOpenSim()?.id??null),n=null,s="cli",this.cliIdentityKeyBySocket.set(e,`ws-${this.nextCliFallbackId++}`),this.broadcastSimAssignments(),this.broadcastSimClientStates()}if(s==="sim"){if(n&&(n.lastSeenAt=Date.now()),r.type==="bridge:register"&&n){let d=r,u=this.tryRestoreSimId(n,d.simId);n.url=d.url,n.title=d.title,n.userAgent=d.userAgent,typeof d.kind=="string"&&d.kind.trim()&&(n.kind=d.kind.trim()),d.meta&&typeof d.meta=="object"&&(n.meta=d.meta);let m=this.primarySimId!==n.id&&this.shouldPromoteSim(n);m&&(this.primarySimId=n.id),(u||m)&&(this.broadcastSimAssignments(),this.broadcastSimClientStates());return}if(r.type==="bridge:user-focus-state"&&n){let d=r;this.updateUserFocusLease(n,d);return}if(r.type==="bridge:user-interact"&&n){this.updateUserActivity(n);return}if(r.type==="bridge:write-shared-config"){let d=r.patch&&typeof r.patch=="object"?r.patch:null;if(!d)return;let u;try{u=V(d)}catch(p){process.stderr.write(`sootsim: bridge:write-shared-config failed: ${p instanceof Error?p.message:String(p)}
11
+ `)}}throw new Error(`could not bind ws bridge after ${this.portFallbackCount} attempts starting at ${this.preferredPort}`)}bindOnce(e,t){return new Promise((i,s)=>{let n=ft((c,l)=>this.handleHttpRequest(c,l)),a=!1,r=c=>{if(!a){a=!0;try{n.close()}catch{}this.httpServer=null,this.wss=null,s(c)}};n.once("error",r),n.listen(e,"127.0.0.1",()=>{a||(a=!0,n.removeListener("error",r),n.on("error",c=>{process.stderr.write(`ws bridge http error: ${String(c)}
12
+ `)}),this.httpServer=n,this.wss=new gt({noServer:!0}),this.wireWebSocketServer(),n.on("upgrade",(c,l,d)=>{Ne(c,l,d)||this.wss?.handleUpgrade(c,l,d,u=>{this.wss?.emit("connection",u,c)})}),i())})})}wireWebSocketServer(){this.wss&&this.wss.on("connection",(e,t)=>{let i=t.headers.origin,s=i?"sim":"cli",n=null;if(e.on("error",()=>{}),this.wsIsAlive.set(e,!0),e.on("pong",()=>{this.wsIsAlive.set(e,!0)}),this.agentHost.registerSocket(e),s==="sim")n={id:this.allocateSimId(),ws:e,origin:i,connectedAt:Date.now(),lastSeenAt:Date.now(),lastActiveAt:0,recentActions:[]},this.sims.set(n.id,n),this.shouldPromoteSim(n)&&(this.primarySimId=n.id),this.broadcastSimAssignments(),this.broadcastSimClientStates();else{let a=`ws-${this.nextCliFallbackId++}`;this.cliIdentityKeyBySocket.set(e,a)}e.on("message",a=>{let r;try{r=JSON.parse(a.toString())}catch{return}if(!(!r||typeof r!="object")){if(typeof r.type=="string"&&r.type.startsWith("agent:")){this.agentHost.handleMessage(e,r);return}if(r.type==="runtime:list"){let c=F(),l=this.getActiveRuntime(),d={type:"runtime:list:ok",id:r.id,installed:c,active:l.version,activeRuntimeDir:l.runtimeDir};try{e.send(JSON.stringify(d))}catch{}return}if(r.type==="runtime:use"){let c=typeof r.version=="string"?r.version:"";if(!F().includes(c)){try{e.send(JSON.stringify({type:"runtime:use:error",id:r.id,error:`runtime ${c||"(missing)"} is not installed`}))}catch{}return}let d=this.setActiveRuntime(c);try{e.send(JSON.stringify({type:"runtime:use:ok",id:r.id,version:d.version,runtimeDir:d.runtimeDir}))}catch{}return}if(r.type==="runtime:get"){let c=this.getActiveRuntime();try{e.send(JSON.stringify({type:"runtime:get:ok",id:r.id,active:c.version,activeRuntimeDir:c.runtimeDir}))}catch{}return}if(s==="sim"&&r.type==="bridge:hello"&&n&&!n.url){let c=n.id;this.sims.delete(c),this.primarySimId===c&&(this.primarySimId=this.getOpenSim()?.id??null),n=null,s="cli",this.cliIdentityKeyBySocket.set(e,`ws-${this.nextCliFallbackId++}`),this.broadcastSimAssignments(),this.broadcastSimClientStates()}if(s==="sim"){if(n&&(n.lastSeenAt=Date.now()),r.type==="bridge:register"&&n){let d=r,u=this.tryRestoreSimId(n,d.simId);n.url=d.url,n.title=d.title,n.userAgent=d.userAgent,typeof d.kind=="string"&&d.kind.trim()&&(n.kind=d.kind.trim()),d.meta&&typeof d.meta=="object"&&(n.meta=d.meta);let m=this.primarySimId!==n.id&&this.shouldPromoteSim(n);m&&(this.primarySimId=n.id),(u||m)&&(this.broadcastSimAssignments(),this.broadcastSimClientStates());return}if(r.type==="bridge:user-focus-state"&&n){let d=r;this.updateUserFocusLease(n,d);return}if(r.type==="bridge:user-interact"&&n){this.updateUserActivity(n);return}if(r.type==="bridge:write-shared-config"){let d=r.patch&&typeof r.patch=="object"?r.patch:null;if(!d)return;let u;try{u=V(d)}catch(p){process.stderr.write(`sootsim: bridge:write-shared-config failed: ${p instanceof Error?p.message:String(p)}
13
13
  `);return}let m=JSON.stringify({type:"bridge:shared-config-changed",config:u});for(let p of this.sims.values())if(p.ws.readyState===h.OPEN)try{p.ws.send(m)}catch{}return}if(r.type==="bridge:open-path"){let d=typeof r.path=="string"?r.path:"",u=typeof r.line=="number"&&Number.isFinite(r.line)?r.line:void 0,m=typeof r.column=="number"&&Number.isFinite(r.column)?r.column:void 0;d&&this.openPathInEditor(d,u,m);return}if(r.type==="bridge:boot-clients"&&n){let d=[];for(let[m,p]of this.cliSimBySocket)p===n.id&&d.push(m);for(let m of d){this.cliSimBySocket.delete(m);try{m.close(1e3,"booted by sim")}catch{}}let u=!!n.cliLease;n.cliLease={kind:"user-active",cliIdentityKey:"__user-active__",cliLabel:"active user",expiresAt:Date.now()+o.USER_BOOT_LEASE_TTL_MS},process.stderr.write(`sootsim booted ${d.length} cli client(s)${u?" (overrode prior lease)":""}; held sim for user [${n.id}]
14
- `),this.recordSimAction(n.id,"sim booted cli clients"),this.broadcastSimClientStates();return}let c=this.pendingCommands.get(r.id);if(c){this.pendingCommands.delete(r.id),r.error?c.reject(new Error(r.error)):c.resolve(r.result);return}let l=this.cliBySentId.get(r.id);if(l&&(this.cliBySentId.delete(r.id),l.ws.readyState===h.OPEN)){let d=this.getOtherCliIdentityCount(l.ws,l.simId),u=d>0?{...r,id:l.originalId,_otherCliCount:d}:{...r,id:l.originalId};l.ws.send(JSON.stringify(u))}return}(async()=>{this.cliLastCommandAt.set(e,Date.now());try{if(r.type==="bridge:bye"){let m=this.cliSimBySocket.delete(e);this.cliLastCommandAt.delete(e),this.cliIdentityKeyBySocket.delete(e),this.cliLabelBySocket.delete(e);for(let[p,f]of this.cliBySentId)f.ws===e&&this.cliBySentId.delete(p);m&&this.broadcastSimClientStates();return}if(r.type==="bridge:hello"){let m=typeof r.cliIdentityKey=="string"&&r.cliIdentityKey.trim()?r.cliIdentityKey.trim():this.cliIdentityKeyBySocket.get(e)||`ws-${this.nextCliFallbackId++}`;this.cliIdentityKeyBySocket.set(e,m),typeof r.cliLabel=="string"&&r.cliLabel.trim()&&this.cliLabelBySocket.set(e,r.cliLabel.trim()),e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,result:{cliIdentityKey:m,leaseTtlMs:o.CLI_LEASE_TTL_MS,leasing:!0}}));return}if(r.type==="bridge:list-sims"){e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,result:this.listSims()}));return}if(r.type==="bridge:open"){if(typeof r.url!="string"||!r.url)throw new Error("bridge:open requires a url");await this.openUrl(r.url,{newWindow:r.newWindow===!0}),e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,result:{ok:!0,url:r.url}}));return}if(r.type==="bridge:claim"){let m=await this.waitForSim(r.simId),p=this.tryAcquireLease(e,m,{force:r.force===!0});if(!p.granted){e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,error:`sim ${m.id} is locked by another cli`,_locked:p.lock}));return}this.setCliSimTarget(e,m.id),this.recordSimAction(m.id,p.bootedCount>0?`cli force-claimed sim (booted ${p.bootedCount})`:"cli claimed sim"),e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,result:{simId:m.id,lockedBy:p.lease.cliIdentityKey,lockExpiresAt:p.lease.expiresAt,bootedCount:p.bootedCount}}));return}let c=await this.waitForSim(r.simId);if(bt(r)){let m=this.tryAcquireLease(e,c);if(!m.granted){e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,error:`sim ${c.id} is locked by another cli \u2014 use \`sootsim claim ${c.id} --force\` or \`sootsim open --new\``,_locked:m.lock}));return}}else this.ensureCliIdentityKey(e);this.setCliSimTarget(e,c.id),this.recordSimAction(c.id,this.describeForwardedCommand(r));let l=this.nextCommandId++;this.cliBySentId.set(l,{simId:c.id,ws:e,originalId:r.id});let{simId:d,...u}=r;if(c.ws.send(JSON.stringify({...u,id:l})),u.type==="close"){this.cliBySentId.delete(l),e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,result:{requested:!0,simId:c.id}}));let m=c.ws,p=setTimeout(()=>{this.closeSimSocketFromHost(m)},yt);He(p)}}catch(c){e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,error:c instanceof Error?c.message:String(c)}))}})()}}),e.on("close",()=>{if(this.agentHost.unregisterSocket(e),s==="sim"&&n){this.rememberDisconnectedSim(n),this.primarySimId===n.id&&(this.primarySimId=this.getOpenSim()?.id??null);for(let[a,r]of this.pendingCommands)r.simId===n.id&&(r.reject(new Error("sim disconnected")),this.pendingCommands.delete(a));for(let[a,r]of this.cliBySentId)r.simId===n.id&&(r.ws.readyState===h.OPEN&&r.ws.send(JSON.stringify({id:r.originalId,error:"sim disconnected before responding"})),this.cliBySentId.delete(a));this.broadcastSimAssignments(),this.broadcastSimClientStates()}else if(s==="cli"){let a=this.cliSimBySocket.delete(e);this.cliLastCommandAt.delete(e),this.cliIdentityKeyBySocket.delete(e),this.cliLabelBySocket.delete(e);for(let[r,c]of this.cliBySentId)c.ws===e&&this.cliBySentId.delete(r);a&&this.broadcastSimClientStates()}})})}afterBind(){if(process.stderr.write(`ws bridge listening on port ${this.port}
14
+ `),this.recordSimAction(n.id,"sim booted cli clients"),this.broadcastSimClientStates();return}let c=this.pendingCommands.get(r.id);if(c){this.pendingCommands.delete(r.id),r.error?c.reject(new Error(r.error)):c.resolve(r.result);return}let l=this.cliBySentId.get(r.id);if(l&&(this.cliBySentId.delete(r.id),l.ws.readyState===h.OPEN)){let d=this.getOtherCliIdentityCount(l.ws,l.simId),u=d>0?{...r,id:l.originalId,_otherCliCount:d}:{...r,id:l.originalId};l.ws.send(JSON.stringify(u))}return}(async()=>{this.cliLastCommandAt.set(e,Date.now());try{if(r.type==="bridge:bye"){let m=this.cliSimBySocket.delete(e);this.cliLastCommandAt.delete(e),this.cliIdentityKeyBySocket.delete(e),this.cliLabelBySocket.delete(e);for(let[p,f]of this.cliBySentId)f.ws===e&&this.cliBySentId.delete(p);m&&this.broadcastSimClientStates();return}if(r.type==="bridge:hello"){let m=typeof r.cliIdentityKey=="string"&&r.cliIdentityKey.trim()?r.cliIdentityKey.trim():this.cliIdentityKeyBySocket.get(e)||`ws-${this.nextCliFallbackId++}`;this.cliIdentityKeyBySocket.set(e,m),typeof r.cliLabel=="string"&&r.cliLabel.trim()&&this.cliLabelBySocket.set(e,r.cliLabel.trim()),e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,result:{cliIdentityKey:m,leaseTtlMs:o.CLI_LEASE_TTL_MS,leasing:!0}}));return}if(r.type==="bridge:list-sims"){e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,result:this.listSims()}));return}if(r.type==="bridge:open"){if(typeof r.url!="string"||!r.url)throw new Error("bridge:open requires a url");await this.openUrl(r.url,{newWindow:r.newWindow===!0}),e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,result:{ok:!0,url:r.url}}));return}if(r.type==="bridge:claim"){let m=await this.waitForSim(r.simId),p=this.tryAcquireLease(e,m,{force:r.force===!0});if(!p.granted){e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,error:`sim ${m.id} is locked by another cli`,_locked:p.lock}));return}this.setCliSimTarget(e,m.id),this.recordSimAction(m.id,p.bootedCount>0?`cli force-claimed sim (booted ${p.bootedCount})`:"cli claimed sim"),e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,result:{simId:m.id,lockedBy:p.lease.cliIdentityKey,lockExpiresAt:p.lease.expiresAt,bootedCount:p.bootedCount}}));return}let c=await this.waitForSim(r.simId);if(wt(r)){let m=this.tryAcquireLease(e,c);if(!m.granted){e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,error:`sim ${c.id} is locked by another cli \u2014 use \`sootsim claim ${c.id} --force\` or \`sootsim open --new\``,_locked:m.lock}));return}}else this.ensureCliIdentityKey(e);this.setCliSimTarget(e,c.id),this.recordSimAction(c.id,this.describeForwardedCommand(r));let l=this.nextCommandId++;this.cliBySentId.set(l,{simId:c.id,ws:e,originalId:r.id});let{simId:d,...u}=r;if(c.ws.send(JSON.stringify({...u,id:l})),u.type==="close"){this.cliBySentId.delete(l),e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,result:{requested:!0,simId:c.id}}));let m=c.ws,p=setTimeout(()=>{this.closeSimSocketFromHost(m)},vt);Ue(p)}}catch(c){e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,error:c instanceof Error?c.message:String(c)}))}})()}}),e.on("close",()=>{if(this.agentHost.unregisterSocket(e),s==="sim"&&n){this.rememberDisconnectedSim(n),this.primarySimId===n.id&&(this.primarySimId=this.getOpenSim()?.id??null);for(let[a,r]of this.pendingCommands)r.simId===n.id&&(r.reject(new Error("sim disconnected")),this.pendingCommands.delete(a));for(let[a,r]of this.cliBySentId)r.simId===n.id&&(r.ws.readyState===h.OPEN&&r.ws.send(JSON.stringify({id:r.originalId,error:"sim disconnected before responding"})),this.cliBySentId.delete(a));this.broadcastSimAssignments(),this.broadcastSimClientStates()}else if(s==="cli"){let a=this.cliSimBySocket.delete(e);this.cliLastCommandAt.delete(e),this.cliIdentityKeyBySocket.delete(e),this.cliLabelBySocket.delete(e);for(let[r,c]of this.cliBySentId)c.ws===e&&this.cliBySentId.delete(r);a&&this.broadcastSimClientStates()}})})}afterBind(){if(process.stderr.write(`ws bridge listening on port ${this.port}
15
15
  `),this.cliIdleTimer=setInterval(()=>this.sweepIdleCliClients(),3e4),this.cliIdleTimer.unref(),this.wsHeartbeatTimer=setInterval(()=>this.sweepDeadWebSockets(),o.WS_HEARTBEAT_INTERVAL_MS),this.wsHeartbeatTimer.unref(),this.shouldWriteLockfile){try{if(O(),!te(this.buildLockfileSnapshot()))throw new Error("another sootsim daemon wrote the lockfile during startup \u2014 aborting")}catch(e){throw process.stderr.write(`ws bridge failed to claim daemon lockfile: ${String(e)}
16
- `),e}this.heartbeatTimer=setInterval(()=>{try{this.writeLockfileSnapshot()}catch{}},Ne),this.heartbeatTimer.unref(),this.startRuntimeUpdater()}if(this.shouldWriteDevLockfile){try{this.writeDevLockfileSnapshot()}catch(e){process.stderr.write(`ws bridge failed to write dev bridge lockfile: ${String(e)}
17
- `)}this.devHeartbeatTimer=setInterval(()=>{try{this.writeDevLockfileSnapshot()}catch{}},Ne),this.devHeartbeatTimer.unref()}this.agentHost.seedOnBoot()}bootstrapping=!0;buildLockfileSnapshot(){return{schema:1,pid:process.pid,platform:process.platform,bridgePort:this.effectivePort,runtimePort:this.effectivePort,activeRuntime:this.activeRuntimeVersion,activeRuntimeDir:this.activeRuntimeDirPath,startedAt:this.startedAt,heartbeatAt:Date.now(),bootstrapping:this.bootstrapping}}buildDevLockfileSnapshot(){let e=this.getShellPort?.()??null;return{schema:1,pid:process.pid,platform:process.platform,bridgePort:this.effectivePort,runtimePort:this.effectivePort,...e&&e>0?{shellPort:e}:{},cwd:process.cwd(),startedAt:this.startedAt,heartbeatAt:Date.now(),source:"vite-dev"}}writeLockfileSnapshot(){Q(this.buildLockfileSnapshot())}writeDevLockfileSnapshot(){ee(this.buildDevLockfileSnapshot())}refreshActiveRuntime(){this.activeRuntimeVersion=U(),this.activeRuntimeDirPath=ce()??X()}runServerScan(){if(this.inflightScan)return this.inflightScan;let e=this.effectivePort>0?[this.effectivePort]:[];return this.inflightScan=_({excludePorts:e,buildIconProxyUrl:t=>`/__bundle-proxy?url=${encodeURIComponent(t)}`}).then(t=>(this.scanCache=t,this.scanCacheAt=Date.now(),t)).catch(t=>{let i=t instanceof Error?t.message:String(t);return console.error("[sootsim] /__server-scan failed:",i),this.scanCache??[]}).finally(()=>{this.inflightScan=null}),this.inflightScan}handleServerScan(e){let t=s=>{e.writeHead(200,{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}),e.end(JSON.stringify(s))},i=Date.now()-this.scanCacheAt;if(this.scanCache&&i<o.SCAN_FRESH_MS){t(this.scanCache);return}if(this.scanCache){t(this.scanCache),this.runServerScan().catch(()=>{});return}this.runServerScan().then(s=>t(s))}resolveRuntimeUpdateIntervalMs(){let e=Number(process.env[At]);return Number.isFinite(e)&&e>0?Math.max(100,Math.round(e)):wt}startRuntimeUpdater(){if(!this.shouldWriteLockfile||this.runtimeUpdateTimer||process.env.SOOTSIM_HOME&&G()&&!U())return;this.runRuntimeUpdate("startup");let e=this.resolveRuntimeUpdateIntervalMs();this.runtimeUpdateTimer=setInterval(()=>{this.runRuntimeUpdate("periodic")},e),this.runtimeUpdateTimer.unref()}runRuntimeUpdate(e){return this.runtimeUpdateInFlight?this.runtimeUpdateInFlight:(this.runtimeUpdateInFlight=(async()=>{try{e==="startup"&&process.stderr.write(`sootsim: checking for runtime updates\u2026
16
+ `),e}this.heartbeatTimer=setInterval(()=>{try{this.writeLockfileSnapshot()}catch{}},De),this.heartbeatTimer.unref(),this.startRuntimeUpdater()}if(this.shouldWriteDevLockfile){try{this.writeDevLockfileSnapshot()}catch(e){process.stderr.write(`ws bridge failed to write dev bridge lockfile: ${String(e)}
17
+ `)}this.devHeartbeatTimer=setInterval(()=>{try{this.writeDevLockfileSnapshot()}catch{}},De),this.devHeartbeatTimer.unref()}this.agentHost.seedOnBoot()}bootstrapping=!0;buildLockfileSnapshot(){return{schema:1,pid:process.pid,platform:process.platform,bridgePort:this.effectivePort,runtimePort:this.effectivePort,activeRuntime:this.activeRuntimeVersion,activeRuntimeDir:this.activeRuntimeDirPath,startedAt:this.startedAt,heartbeatAt:Date.now(),bootstrapping:this.bootstrapping}}buildDevLockfileSnapshot(){let e=this.getShellPort?.()??null;return{schema:1,pid:process.pid,platform:process.platform,bridgePort:this.effectivePort,runtimePort:this.effectivePort,...e&&e>0?{shellPort:e}:{},cwd:process.cwd(),startedAt:this.startedAt,heartbeatAt:Date.now(),source:"vite-dev"}}writeLockfileSnapshot(){Q(this.buildLockfileSnapshot())}writeDevLockfileSnapshot(){ee(this.buildDevLockfileSnapshot())}refreshActiveRuntime(){this.activeRuntimeVersion=U(),this.activeRuntimeDirPath=ce()??X()}runServerScan(){if(this.inflightScan)return this.inflightScan;let e=this.effectivePort>0?[this.effectivePort]:[];return this.inflightScan=_({excludePorts:e,buildIconProxyUrl:t=>`/__bundle-proxy?url=${encodeURIComponent(t)}`}).then(t=>(this.scanCache=t,this.scanCacheAt=Date.now(),t)).catch(t=>{let i=t instanceof Error?t.message:String(t);return console.error("[sootsim] /__server-scan failed:",i),this.scanCache??[]}).finally(()=>{this.inflightScan=null}),this.inflightScan}handleServerScan(e){let t=s=>{e.writeHead(200,{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}),e.end(JSON.stringify(s))},i=Date.now()-this.scanCacheAt;if(this.scanCache&&i<o.SCAN_FRESH_MS){t(this.scanCache);return}if(this.scanCache){t(this.scanCache),this.runServerScan().catch(()=>{});return}this.runServerScan().then(s=>t(s))}resolveRuntimeUpdateIntervalMs(){let e=Number(process.env[kt]);return Number.isFinite(e)&&e>0?Math.max(100,Math.round(e)):At}startRuntimeUpdater(){if(!this.shouldWriteLockfile||this.runtimeUpdateTimer||process.env.SOOTSIM_HOME&&G()&&!U())return;this.runRuntimeUpdate("startup");let e=this.resolveRuntimeUpdateIntervalMs();this.runtimeUpdateTimer=setInterval(()=>{this.runRuntimeUpdate("periodic")},e),this.runtimeUpdateTimer.unref()}runRuntimeUpdate(e){return this.runtimeUpdateInFlight?this.runtimeUpdateInFlight:(this.runtimeUpdateInFlight=(async()=>{try{e==="startup"&&process.stderr.write(`sootsim: checking for runtime updates\u2026
18
18
  `);let t=await de();if(!t.updated||!t.latestVersion){e==="startup"&&process.stderr.write(`sootsim: runtime ${this.activeRuntimeVersion??"(none)"} is current
19
19
  `);return}let i=this.activeRuntimeVersion,s=this.setActiveRuntime(t.latestVersion);process.stderr.write(`sootsim runtime updated to ${s.version} (${e})
20
20
  `);try{q({from:i,to:s.version,at:Date.now()})}catch{}}catch(t){process.stderr.write(`sootsim runtime update failed (${e}): ${t instanceof Error?t.message:String(t)}
21
21
  `)}finally{if(this.runtimeUpdateInFlight=null,e==="startup"&&this.bootstrapping){if(this.bootstrapping=!1,this.shouldWriteLockfile&&this.httpServer)try{this.writeLockfileSnapshot()}catch{}process.stderr.write(`sootsim: ready
22
- `)}}})(),this.runtimeUpdateInFlight)}setActiveRuntime(e){if(z(e),this.refreshActiveRuntime(),this.shouldWriteLockfile&&this.httpServer)try{this.writeLockfileSnapshot()}catch{}let t=JSON.stringify({type:"runtime:changed",version:e,runtimeDir:this.activeRuntimeDirPath});for(let i of this.sims.values())if(i.ws.readyState===h.OPEN)try{i.ws.send(t)}catch{}return{version:e,runtimeDir:this.activeRuntimeDirPath}}getActiveRuntime(){return{version:this.activeRuntimeVersion,runtimeDir:this.activeRuntimeDirPath}}removeLockfile(){if(this.shouldWriteLockfile)try{W()}catch{}}handleHttpRequest(e,t){if(t.setHeader("Cross-Origin-Opener-Policy","same-origin"),t.setHeader("Cross-Origin-Embedder-Policy",gt),t.setHeader("Cross-Origin-Resource-Policy","cross-origin"),t.setHeader("Document-Policy","js-profiling"),_e(e.url)){Le(e,t);return}if(xe(e.url)&&Be(e,t))return;let i=(e.method||"GET").toUpperCase();if(i!=="GET"&&i!=="HEAD"){t.writeHead(405,{Allow:"GET, HEAD"}),t.end("method not allowed");return}let s=new URL(e.url||"/","http://localhost");if(s.pathname==="/__bundle-proxy"){let l=s.searchParams.get("url");if(!l){t.writeHead(400,{"Content-Type":"text/plain"}),t.end("bundle-proxy: missing url query param");return}let d;try{d=new URL(l)}catch{t.writeHead(400,{"Content-Type":"text/plain"}),t.end("bundle-proxy: invalid url");return}let u=d.hostname;if(!(u==="localhost"||u==="127.0.0.1"||u==="::1"||u.endsWith(".localhost"))){t.writeHead(403,{"Content-Type":"text/plain"}),t.end("bundle-proxy: only loopback targets allowed");return}(async()=>{try{let p=await fetch(d.toString(),{redirect:"follow"}),f={},S=p.headers.get("content-type");if(S&&(f["Content-Type"]=S),f["Cache-Control"]="no-store",t.writeHead(p.status,f),!p.body){t.end();return}let g=p.body.getReader();for(;;){let{done:b,value:v}=await g.read();if(b)break;t.write(Buffer.from(v))}t.end()}catch(p){t.writeHead(502,{"Content-Type":"text/plain"}),t.end(`bundle-proxy: upstream fetch failed: ${p instanceof Error?p.message:String(p)}`)}})();return}if(s.pathname==="/__server-scan"){this.handleServerScan(t);return}if(s.pathname==="/healthz"){t.writeHead(200,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify({ok:!0,pid:process.pid,platform:process.platform,bridgePort:this.effectivePort,runtimePort:this.effectivePort,activeRuntime:this.activeRuntimeVersion,bridgeSource:this.shouldWriteDevLockfile?"vite-dev":this.shouldWriteLockfile?"daemon":"embedded",startedAt:this.startedAt,uptimeMs:this.startedAt>0?Date.now()-this.startedAt:0}));return}if(s.pathname==="/__sootsim/shared-config"){if(t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Cache-Control","no-store"),i==="GET"||i==="HEAD"){let l="{}";try{l=JSON.stringify(H())}catch{}t.writeHead(200,{"Content-Type":"application/json"}),i==="HEAD"?t.end():t.end(l);return}t.writeHead(405,{Allow:"GET, HEAD"}),t.end("method not allowed (use the bridge over WS for writes)");return}this.refreshActiveRuntime();let n=this.activeRuntimeDirPath;if(!n){t.writeHead(503,{"Content-Type":"text/plain; charset=utf-8"}),t.end("sootsim: no active runtime installed. run `sootsim runtime install` to fetch one.");return}let a=s.pathname;if(a==="/runtime"||a==="/runtime/"?a="/":a.startsWith("/runtime/")?a=a.slice(8):a==="/sootsim"||a==="/sootsim/"?a="/":a.startsWith("/sootsim/")&&(a=a.slice(8)),(a===""||a==="/")&&(a="/index.html"),a.includes("\0")){t.writeHead(400),t.end("bad request");return}if(process.platform!=="win32"&&a.includes("\\")){t.writeHead(400),t.end("bad request");return}for(let l of a.split("/"))if(l===".."){t.writeHead(403),t.end("forbidden");return}let r=w.resolve(n,"."+a),c=n.endsWith(w.sep)?n:n+w.sep;if(!r.startsWith(c)&&r!==n){t.writeHead(403),t.end("forbidden");return}T.realpath(r,(l,d)=>{let u=l?r:d,m=u.endsWith(w.sep)?u:u+w.sep;if(!l){let p=(()=>{try{let f=T.realpathSync(n);return f.endsWith(w.sep)?f:f+w.sep}catch{return c}})();if(!m.startsWith(p)&&u+w.sep!==p){t.writeHead(403),t.end("forbidden");return}}T.stat(u,(p,f)=>{if(p||!f?.isFile()){let v=w.extname(a).toLowerCase();if(v&&v!==".html"){t.writeHead(404),t.end("not found");return}if(a.startsWith("/__")||a.startsWith("/api/")||a==="/api"){t.writeHead(404,{"Content-Type":"text/plain; charset=utf-8"}),t.end("not found");return}let A=w.join(n,"index.html");T.readFile(A,(y,R)=>{if(y){t.writeHead(404),t.end("not found");return}if(t.writeHead(200,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}),i==="HEAD"){t.end();return}t.end(De(R,this.effectivePort,this.contrastOrigin))});return}let S=w.extname(u).toLowerCase(),g=kt[S]||"application/octet-stream";if(t.writeHead(200,{"Content-Type":g,"Cache-Control":"no-store"}),i==="HEAD"){t.end();return}if(S===".html"){T.readFile(u,(v,A)=>{if(v){try{t.end()}catch{}return}t.end(De(A,this.effectivePort,this.contrastOrigin))});return}let b=T.createReadStream(u);b.pipe(t),b.on("error",()=>{try{t.end()}catch{}})})})}sweepIdleCliClients(){let e=Date.now(),t=!1;for(let[i,s]of this.cliSimBySocket){let n=this.cliLastCommandAt.get(i)??0;if(e-n<o.CLI_IDLE_TIMEOUT_MS)continue;let a=!1;for(let r of this.cliBySentId.values())if(r.ws===i){a=!0;break}if(!a){this.cliSimBySocket.delete(i),this.cliLastCommandAt.delete(i);for(let[r,c]of this.cliBySentId)c.ws===i&&this.cliBySentId.delete(r);try{i.close(1e3,"idle timeout")}catch{}t=!0}}t&&this.broadcastSimClientStates(),this.sweepRestorableSims(e),this.reapIdleSims(e)}isAutomationSim(e){return e.meta?.sootsimHostDriver==="playwright"}automationSimOwnerAlive(e){let t=Number(e.meta?.sootsimHostPid);if(!Number.isInteger(t)||t<=1||t===process.pid)return!1;try{return process.kill(t,0),!0}catch(i){return i.code==="EPERM"}}reapIdleSims(e=Date.now()){let t=new Set(this.cliSimBySocket.values()),i=[];for(let n of this.sims.values()){if(n.id===this.primarySimId||t.has(n.id)||this.getActiveLease(n))continue;let a=Math.max(n.lastActiveAt,n.connectedAt),r=e-a,c=this.isAutomationSim(n);if(c&&this.automationSimOwnerAlive(n))continue;let l=c?this.automationSimIdleReapTtlMs:this.simIdleReapTtlMs;if(r>=l){this.closeSimSocketFromHost(n.ws);continue}c&&i.push({sim:n,idleMs:r})}let s=this.maxConcurrentAutomationSims;if(i.length>s){i.sort((n,a)=>a.idleMs-n.idleMs);for(let{sim:n,idleMs:a}of i.slice(0,i.length-s))a<this.automationSimActiveGraceMs||this.closeSimSocketFromHost(n.ws)}}sweepDeadWebSockets(){if(this.wss)for(let e of this.wss.clients){if(e.readyState!==h.OPEN)continue;if(this.wsIsAlive.get(e)===!1){try{e.terminate()}catch{}continue}this.wsIsAlive.set(e,!1);try{e.ping()}catch{try{e.terminate()}catch{}}}}closeSimSocketFromHost(e){if(e.readyState!==h.OPEN)return;try{e.close(oe,ae)}catch{try{e.terminate()}catch{}return}let t=setTimeout(()=>{if(e.readyState!==h.CLOSED)try{e.terminate()}catch{}},vt);He(t)}listSims(){return Array.from(this.sims.values()).sort((e,t)=>e.id===this.primarySimId?-1:t.id===this.primarySimId?1:e.connectedAt-t.connectedAt).map(e=>this.describeSim(e))}async sendCommand(e){let t=await this.waitForSim(e.simId),i=this.nextCommandId++;return new Promise((s,n)=>{let a=setTimeout(()=>{this.pendingCommands.delete(i),this.broadcastSimClientStates(),n(new Error("command timed out after 30s"))},3e4);this.pendingCommands.set(i,{simId:t.id,resolve:l=>{clearTimeout(a),this.pendingCommands.delete(i),this.broadcastSimClientStates(),s(l)},reject:l=>{clearTimeout(a),this.pendingCommands.delete(i),this.broadcastSimClientStates(),n(l)}}),this.broadcastSimClientStates();let{simId:r,...c}=e;t.ws.send(JSON.stringify({...c,id:i}))})}async evaluate(e,t){return this.sendCommand({type:"evaluate",code:e,simId:t})}async focusSim(e){return this.sendCommand({type:"focus",simId:e})}async closeSim(e){return this.sendCommand({type:"close",simId:e})}async openPathInEditor(e,t,i){let s=t!=null?`:${t}${i!=null?`:${i}`:""}`:"",n=`${e}${s}`,a=(c,l)=>new Promise(d=>{try{let u=mt(c,l,{detached:!0,stdio:"ignore"}),m=!1;u.on("error",()=>{m||(m=!0,d(!1))}),u.on("spawn",()=>{m||(m=!0,u.unref(),d(!0))})}catch{d(!1)}}),r=process.env.REACT_EDITOR||process.env.EDITOR;if(r){let c=r.split(" ").filter(Boolean);if(c.length&&await a(c[0],[...c.slice(1),"-g",n]))return}await a("cursor",["-g",n])||await a("code",["-g",n])||await this.openUrl(e)}async openUrl(e,t={}){if(this.openUrlHandler){await this.openUrlHandler(e,t);return}await le(e,t)}async close(){if(this.cliIdleTimer&&(clearInterval(this.cliIdleTimer),this.cliIdleTimer=null),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.devHeartbeatTimer&&(clearInterval(this.devHeartbeatTimer),this.devHeartbeatTimer=null),this.wsHeartbeatTimer&&(clearInterval(this.wsHeartbeatTimer),this.wsHeartbeatTimer=null),this.runtimeUpdateTimer&&(clearInterval(this.runtimeUpdateTimer),this.runtimeUpdateTimer=null),this.shouldWriteLockfile)try{W()}catch{}if(this.shouldWriteDevLockfile)try{ie()}catch{}this.effectivePort=0,this.startedAt=0,this.agentHost.close();for(let[i,s]of this.pendingCommands)s.reject(new Error("server closing")),this.pendingCommands.delete(i);for(let i of this.sims.values())i.ws.close();this.sims.clear(),this.primarySimId=null;let e=this.wss,t=this.httpServer;if(this.wss=null,this.httpServer=null,e)try{e.close()}catch{}if(t)try{t.close()}catch{}}describeSim(e){let t;try{t=e.ws.readyState}catch{t=h.CLOSED}let i=this.getActiveLease(e);return{id:e.id,origin:e.origin,url:e.url,title:e.title,userAgent:e.userAgent,connectedAt:e.connectedAt,lastSeenAt:e.lastSeenAt,lastActiveAt:e.lastActiveAt||void 0,isPrimary:e.id===this.primarySimId,readyState:t===h.OPEN?"open":t===h.CLOSING?"closing":"closed",attachedCliCount:this.getAttachedCliCount(e.id),lockedBy:i?i.cliLabel||i.cliIdentityKey:void 0,lockedByKind:i?i.kind:void 0,lockExpiresAt:i?i.expiresAt:void 0,userFocused:e.userFocused||void 0,userVisible:e.userVisible,visibilityState:e.visibilityState,documentFocused:e.documentFocused,kind:e.kind,meta:e.meta}}getActiveLease(e){let t=e.cliLease;return t?Date.now()>=t.expiresAt?(e.cliLease=void 0,null):t:null}tryAcquireLease(e,t,i={}){let s=this.cliIdentityKeyBySocket.get(e)??(()=>{let u=`ws-${this.nextCliFallbackId++}`;return this.cliIdentityKeyBySocket.set(e,u),u})(),n=this.cliLabelBySocket.get(e),a=Date.now(),r=this.getActiveLease(t),c=r&&r.cliIdentityKey===s,l=0;if(r&&!c&&!i.force)return{granted:!1,lease:r,lock:{by:r.cliLabel||r.cliIdentityKey,expiresInMs:Math.max(0,r.expiresAt-a)},bootedCount:0};if(r&&!c&&i.force)for(let[u,m]of this.cliSimBySocket){if(m!==t.id)continue;let p=this.cliIdentityKeyBySocket.get(u);if(p&&p!==s){this.cliSimBySocket.delete(u);try{u.close(1e3,"lease claimed by another cli")}catch{}l++}}let d={kind:"cli",cliIdentityKey:s,cliLabel:n,expiresAt:a+o.CLI_LEASE_TTL_MS};return t.cliLease=d,{granted:!0,lease:d,bootedCount:l}}updateUserFocusLease(e,t){let i=t.focused===!0,s=typeof t.visible=="boolean"?t.visible:void 0,n=typeof t.visibilityState=="string"?t.visibilityState:void 0,a=typeof t.documentFocused=="boolean"?t.documentFocused:void 0;e.userFocused===i&&e.userVisible===s&&e.visibilityState===n&&e.documentFocused===a||(e.userFocused=i,e.userVisible=s,e.visibilityState=n,e.documentFocused=a,this.broadcastSimClientStates())}updateUserActivity(e){let t=this.getActiveLease(e);if(t&&t.kind==="cli")return;let s=Date.now()+o.USER_ACTIVE_LEASE_TTL_MS,n=t&&t.kind==="user-active"?Math.max(t.expiresAt,s):s;e.cliLease={kind:"user-active",cliIdentityKey:"__user-active__",cliLabel:"active user",expiresAt:n},this.broadcastSimClientStates()}ensureCliIdentityKey(e){let t=this.cliIdentityKeyBySocket.get(e);if(t)return t;let i=`ws-${this.nextCliFallbackId++}`;return this.cliIdentityKeyBySocket.set(e,i),i}getOpenSim(e){if(e){let s=this.sims.get(e);return s?.ws.readyState===h.OPEN?s:null}let t=this.primarySimId!=null?this.sims.get(this.primarySimId):null;if(t?.ws.readyState===h.OPEN&&t.url)return t;let i=null;for(let s of this.sims.values())if(s.ws.readyState===h.OPEN){if(s.url)return s;i??=s}return t?.ws.readyState===h.OPEN?t:i}async waitForSim(e,t={}){let i=t.attempts??10,s=t.intervalMs??200;for(let n=0;n<i;n++){let a=this.getOpenSim(e);if(a)return a;await new Promise(r=>setTimeout(r,s))}throw new Error(e?`no sim connected with id ${e}`:"no sim connected")}shouldPromoteSim(e){let t=this.primarySimId?this.sims.get(this.primarySimId):null;if(!e.url)return!t;let i=t?.ws.readyState===h.OPEN;if(!t||!i||!t.url)return!0;let s=e.origin?.includes(":5173"),n=t.origin?.includes(":5173");return!!s||!n}broadcastSimAssignments(){for(let e of this.sims.values())e.ws.readyState===h.OPEN&&e.ws.send(JSON.stringify({type:"bridge:welcome",simId:e.id,isPrimary:e.id===this.primarySimId}))}broadcastSimClientStates(){for(let e of this.sims.values()){if(e.ws.readyState!==h.OPEN)continue;let t=this.getActiveLease(e),i={type:"bridge:client-state",attachedCliCount:this.getAttachedCliCount(e.id),activeAgentCommandCount:this.getActiveAgentCommandCount(e.id),recentActions:e.recentActions,lockedBy:t?t.cliLabel||t.cliIdentityKey:void 0,lockedByKind:t?t.kind:void 0,lockExpiresAt:t?t.expiresAt:void 0,userFocused:e.userFocused||void 0,userVisible:e.userVisible,visibilityState:e.visibilityState,documentFocused:e.documentFocused};e.ws.send(JSON.stringify(i))}}setCliSimTarget(e,t){let i=this.cliSimBySocket.get(e);i!==t&&(this.cliSimBySocket.set(e,t),this.recordSimAction(t,i?"cli switched sims":"cli connected",!1),this.broadcastSimClientStates())}recordSimAction(e,t,i=!0){let s=t?.trim();if(!s)return;let n=this.sims.get(e);if(!n)return;let a=Date.now();n.lastActiveAt=a,n.recentActions=[{label:s,at:a},...n.recentActions.filter(r=>r.label!==s)].slice(0,4),i&&this.broadcastSimClientStates()}describeForwardedCommand(e){switch(e?.type){case"evaluate":return"evaluated page state";case"screenshot":return"captured screenshot";case"tap":return"sent tap event";case"keyboard":return e?.action==="type"?"typed text":"used keyboard";case"tree":return"dumped tree";case"focus":return"focused sim";case"close":return"requested close";default:return typeof e?.type=="string"?e.type:null}}getAttachedCliCount(e){let t=new Set;for(let[i,s]of this.cliSimBySocket){if(s!==e||i.readyState!==h.OPEN)continue;let n=this.cliIdentityKeyBySocket.get(i);t.add(n??`ws-unknown-${t.size}`)}return t.size}getOtherCliIdentityCount(e,t){let i=this.cliIdentityKeyBySocket.get(e),s=new Set;for(let[n,a]of this.cliSimBySocket){if(a!==t||n.readyState!==h.OPEN)continue;let r=this.cliIdentityKeyBySocket.get(n);r&&r===i||s.add(r??`ws-unknown-${s.size}`)}return s.size}getActiveAgentCommandCount(e){let t=0;for(let i of this.pendingCommands.values())i.simId===e&&t++;return t}allocateSimId(){for(;;){let e=this.nextSimNumber.toString(16);if(this.nextSimNumber++,!this.sims.has(e)&&!this.restorableSims.has(e))return e}}tryRestoreSimId(e,t){let i=t?.trim();if(!i||i===e.id)return!1;let s=this.sims.get(i);if(s&&s!==e&&s.ws.readyState===h.OPEN)return!1;let n=this.getRestorableSimState(i),a=e.id;this.sims.delete(a),e.id=i,n&&(e.recentActions=n.recentActions.map(r=>({...r})),e.lastActiveAt=n.lastActiveAt,e.cliLease=n.cliLease?{...n.cliLease}:void 0,this.restorableSims.delete(i)),this.sims.set(e.id,e),this.primarySimId===a&&(this.primarySimId=e.id);for(let[r,c]of this.cliSimBySocket)c===a&&this.cliSimBySocket.set(r,e.id);return!0}rememberDisconnectedSim(e){let t=this.getActiveLease(e);this.restorableSims.set(e.id,{recentActions:e.recentActions.map(i=>({...i})),lastActiveAt:e.lastActiveAt,cliLease:t&&t.kind==="cli"?{...t}:void 0,expiresAt:Date.now()+o.SIM_RECONNECT_TTL_MS}),this.sims.delete(e.id)}getRestorableSimState(e){let t=this.restorableSims.get(e);return t?t.expiresAt<=Date.now()?(this.restorableSims.delete(e),null):(t.cliLease&&t.cliLease.expiresAt<=Date.now()&&(t.cliLease=void 0),t):null}sweepRestorableSims(e=Date.now()){for(let[t,i]of this.restorableSims)if(!(i.expiresAt>e)){this.restorableSims.delete(t);for(let[s,n]of this.cliSimBySocket)n===t&&this.cliSimBySocket.delete(s)}}resetServerState(){this.cliIdleTimer&&(clearInterval(this.cliIdleTimer),this.cliIdleTimer=null),this.wsHeartbeatTimer&&(clearInterval(this.wsHeartbeatTimer),this.wsHeartbeatTimer=null),this.runtimeUpdateTimer&&(clearInterval(this.runtimeUpdateTimer),this.runtimeUpdateTimer=null);let e=this.wss,t=this.httpServer;if(this.wss=null,this.httpServer=null,e)try{e.close()}catch{}if(t)try{t.close()}catch{}}};function It(){return!!((process.env.XPC_SERVICE_NAME||"").includes("dev.sootsim.daemon")||process.env.INVOCATION_ID)}async function gi(o,e={}){(o.includes("--help")||o.includes("-h"))&&(console.log(`
22
+ `)}}})(),this.runtimeUpdateInFlight)}setActiveRuntime(e){if(z(e),this.refreshActiveRuntime(),this.shouldWriteLockfile&&this.httpServer)try{this.writeLockfileSnapshot()}catch{}let t=JSON.stringify({type:"runtime:changed",version:e,runtimeDir:this.activeRuntimeDirPath});for(let i of this.sims.values())if(i.ws.readyState===h.OPEN)try{i.ws.send(t)}catch{}return{version:e,runtimeDir:this.activeRuntimeDirPath}}getActiveRuntime(){return{version:this.activeRuntimeVersion,runtimeDir:this.activeRuntimeDirPath}}removeLockfile(){if(this.shouldWriteLockfile)try{W()}catch{}}handleHttpRequest(e,t){if(t.setHeader("Cross-Origin-Opener-Policy","same-origin"),t.setHeader("Cross-Origin-Embedder-Policy",St),t.setHeader("Cross-Origin-Resource-Policy","cross-origin"),t.setHeader("Document-Policy","js-profiling"),xe(e.url)){Be(e,t);return}if(Le(e.url)&&Me(e,t))return;let i=(e.method||"GET").toUpperCase();if(i!=="GET"&&i!=="HEAD"){t.writeHead(405,{Allow:"GET, HEAD"}),t.end("method not allowed");return}let s=new URL(e.url||"/","http://localhost");if(s.pathname==="/__bundle-proxy"){let l=s.searchParams.get("url");if(!l){t.writeHead(400,{"Content-Type":"text/plain"}),t.end("bundle-proxy: missing url query param");return}let d;try{d=new URL(l)}catch{t.writeHead(400,{"Content-Type":"text/plain"}),t.end("bundle-proxy: invalid url");return}let u=d.hostname;if(!(u==="localhost"||u==="127.0.0.1"||u==="::1"||u.endsWith(".localhost"))){t.writeHead(403,{"Content-Type":"text/plain"}),t.end("bundle-proxy: only loopback targets allowed");return}(async()=>{try{let p=await fetch(d.toString(),{redirect:"follow"}),f={},S=p.headers.get("content-type");if(S&&(f["Content-Type"]=S),f["Cache-Control"]="no-store",t.writeHead(p.status,f),!p.body){t.end();return}let g=p.body.getReader();for(;;){let{done:b,value:v}=await g.read();if(b)break;t.write(Buffer.from(v))}t.end()}catch(p){t.writeHead(502,{"Content-Type":"text/plain"}),t.end(`bundle-proxy: upstream fetch failed: ${p instanceof Error?p.message:String(p)}`)}})();return}if(s.pathname==="/__server-scan"){this.handleServerScan(t);return}if(s.pathname==="/healthz"){t.writeHead(200,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify({ok:!0,pid:process.pid,platform:process.platform,bridgePort:this.effectivePort,runtimePort:this.effectivePort,activeRuntime:this.activeRuntimeVersion,bridgeSource:this.shouldWriteDevLockfile?"vite-dev":this.shouldWriteLockfile?"daemon":"embedded",startedAt:this.startedAt,uptimeMs:this.startedAt>0?Date.now()-this.startedAt:0}));return}if(s.pathname==="/__sootsim/shared-config"){if(t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Cache-Control","no-store"),i==="GET"||i==="HEAD"){let l="{}";try{l=JSON.stringify(H())}catch{}t.writeHead(200,{"Content-Type":"application/json"}),i==="HEAD"?t.end():t.end(l);return}t.writeHead(405,{Allow:"GET, HEAD"}),t.end("method not allowed (use the bridge over WS for writes)");return}this.refreshActiveRuntime();let n=this.activeRuntimeDirPath;if(!n){t.writeHead(503,{"Content-Type":"text/plain; charset=utf-8"}),t.end("sootsim: no active runtime installed. run `sootsim runtime install` to fetch one.");return}let a=s.pathname;if(a==="/runtime"||a==="/runtime/"?a="/":a.startsWith("/runtime/")?a=a.slice(8):a==="/sootsim"||a==="/sootsim/"?a="/":a.startsWith("/sootsim/")&&(a=a.slice(8)),(a===""||a==="/")&&(a="/index.html"),a.includes("\0")){t.writeHead(400),t.end("bad request");return}if(process.platform!=="win32"&&a.includes("\\")){t.writeHead(400),t.end("bad request");return}for(let l of a.split("/"))if(l===".."){t.writeHead(403),t.end("forbidden");return}let r=w.resolve(n,"."+a),c=n.endsWith(w.sep)?n:n+w.sep;if(!r.startsWith(c)&&r!==n){t.writeHead(403),t.end("forbidden");return}C.realpath(r,(l,d)=>{let u=l?r:d,m=u.endsWith(w.sep)?u:u+w.sep;if(!l){let p=(()=>{try{let f=C.realpathSync(n);return f.endsWith(w.sep)?f:f+w.sep}catch{return c}})();if(!m.startsWith(p)&&u+w.sep!==p){t.writeHead(403),t.end("forbidden");return}}C.stat(u,(p,f)=>{if(p||!f?.isFile()){let v=w.extname(a).toLowerCase();if(v&&v!==".html"){t.writeHead(404),t.end("not found");return}if(a.startsWith("/__")||a.startsWith("/api/")||a==="/api"){t.writeHead(404,{"Content-Type":"text/plain; charset=utf-8"}),t.end("not found");return}let A=w.join(n,"index.html");C.readFile(A,(y,R)=>{if(y){t.writeHead(404),t.end("not found");return}if(t.writeHead(200,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}),i==="HEAD"){t.end();return}t.end(He(R,this.effectivePort,this.contrastOrigin))});return}let S=w.extname(u).toLowerCase(),g=It[S]||"application/octet-stream";if(t.writeHead(200,{"Content-Type":g,"Cache-Control":"no-store"}),i==="HEAD"){t.end();return}if(S===".html"){C.readFile(u,(v,A)=>{if(v){try{t.end()}catch{}return}t.end(He(A,this.effectivePort,this.contrastOrigin))});return}let b=C.createReadStream(u);b.pipe(t),b.on("error",()=>{try{t.end()}catch{}})})})}sweepIdleCliClients(){let e=Date.now(),t=!1;for(let[i,s]of this.cliSimBySocket){let n=this.cliLastCommandAt.get(i)??0;if(e-n<o.CLI_IDLE_TIMEOUT_MS)continue;let a=!1;for(let r of this.cliBySentId.values())if(r.ws===i){a=!0;break}if(!a){this.cliSimBySocket.delete(i),this.cliLastCommandAt.delete(i);for(let[r,c]of this.cliBySentId)c.ws===i&&this.cliBySentId.delete(r);try{i.close(1e3,"idle timeout")}catch{}t=!0}}t&&this.broadcastSimClientStates(),this.sweepRestorableSims(e),this.reapIdleSims(e)}isAutomationSim(e){return e.meta?.sootsimHostDriver==="playwright"}automationSimOwnerAlive(e){let t=Number(e.meta?.sootsimHostPid);if(!Number.isInteger(t)||t<=1||t===process.pid)return!1;try{return process.kill(t,0),!0}catch(i){return i.code==="EPERM"}}reapIdleSims(e=Date.now()){let t=new Set(this.cliSimBySocket.values()),i=[];for(let n of this.sims.values()){if(n.id===this.primarySimId||t.has(n.id)||this.getActiveLease(n))continue;let a=Math.max(n.lastActiveAt,n.connectedAt),r=e-a,c=this.isAutomationSim(n);if(c&&this.automationSimOwnerAlive(n))continue;let l=c?this.automationSimIdleReapTtlMs:this.simIdleReapTtlMs;if(r>=l){this.closeSimSocketFromHost(n.ws);continue}c&&i.push({sim:n,idleMs:r})}let s=this.maxConcurrentAutomationSims;if(i.length>s){i.sort((n,a)=>a.idleMs-n.idleMs);for(let{sim:n,idleMs:a}of i.slice(0,i.length-s))a<this.automationSimActiveGraceMs||this.closeSimSocketFromHost(n.ws)}}sweepDeadWebSockets(){if(this.wss)for(let e of this.wss.clients){if(e.readyState!==h.OPEN)continue;if(this.wsIsAlive.get(e)===!1){try{e.terminate()}catch{}continue}this.wsIsAlive.set(e,!1);try{e.ping()}catch{try{e.terminate()}catch{}}}}closeSimSocketFromHost(e){if(e.readyState!==h.OPEN)return;try{e.close(oe,ae)}catch{try{e.terminate()}catch{}return}let t=setTimeout(()=>{if(e.readyState!==h.CLOSED)try{e.terminate()}catch{}},bt);Ue(t)}listSims(){return Array.from(this.sims.values()).sort((e,t)=>e.id===this.primarySimId?-1:t.id===this.primarySimId?1:e.connectedAt-t.connectedAt).map(e=>this.describeSim(e))}async sendCommand(e){let t=await this.waitForSim(e.simId),i=this.nextCommandId++;return new Promise((s,n)=>{let a=setTimeout(()=>{this.pendingCommands.delete(i),this.broadcastSimClientStates(),n(new Error("command timed out after 30s"))},3e4);this.pendingCommands.set(i,{simId:t.id,resolve:l=>{clearTimeout(a),this.pendingCommands.delete(i),this.broadcastSimClientStates(),s(l)},reject:l=>{clearTimeout(a),this.pendingCommands.delete(i),this.broadcastSimClientStates(),n(l)}}),this.broadcastSimClientStates();let{simId:r,...c}=e;t.ws.send(JSON.stringify({...c,id:i}))})}async evaluate(e,t){return this.sendCommand({type:"evaluate",code:e,simId:t})}async focusSim(e){return this.sendCommand({type:"focus",simId:e})}async closeSim(e){return this.sendCommand({type:"close",simId:e})}async openPathInEditor(e,t,i){let s=t!=null?`:${t}${i!=null?`:${i}`:""}`:"",n=`${e}${s}`,a=(c,l)=>new Promise(d=>{try{let u=ht(c,l,{detached:!0,stdio:"ignore"}),m=!1;u.on("error",()=>{m||(m=!0,d(!1))}),u.on("spawn",()=>{m||(m=!0,u.unref(),d(!0))})}catch{d(!1)}}),r=process.env.REACT_EDITOR||process.env.EDITOR;if(r){let c=r.split(" ").filter(Boolean);if(c.length&&await a(c[0],[...c.slice(1),"-g",n]))return}await a("cursor",["-g",n])||await a("code",["-g",n])||await this.openUrl(e)}async openUrl(e,t={}){if(this.openUrlHandler){await this.openUrlHandler(e,t);return}await le(e,t)}async close(){if(this.cliIdleTimer&&(clearInterval(this.cliIdleTimer),this.cliIdleTimer=null),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.devHeartbeatTimer&&(clearInterval(this.devHeartbeatTimer),this.devHeartbeatTimer=null),this.wsHeartbeatTimer&&(clearInterval(this.wsHeartbeatTimer),this.wsHeartbeatTimer=null),this.runtimeUpdateTimer&&(clearInterval(this.runtimeUpdateTimer),this.runtimeUpdateTimer=null),this.shouldWriteLockfile)try{W()}catch{}if(this.shouldWriteDevLockfile)try{ie()}catch{}this.effectivePort=0,this.startedAt=0,this.agentHost.close();for(let[i,s]of this.pendingCommands)s.reject(new Error("server closing")),this.pendingCommands.delete(i);for(let i of this.sims.values())i.ws.close();this.sims.clear(),this.primarySimId=null;let e=this.wss,t=this.httpServer;if(this.wss=null,this.httpServer=null,e)try{e.close()}catch{}if(t)try{t.close()}catch{}}describeSim(e){let t;try{t=e.ws.readyState}catch{t=h.CLOSED}let i=this.getActiveLease(e);return{id:e.id,origin:e.origin,url:e.url,title:e.title,userAgent:e.userAgent,connectedAt:e.connectedAt,lastSeenAt:e.lastSeenAt,lastActiveAt:e.lastActiveAt||void 0,isPrimary:e.id===this.primarySimId,readyState:t===h.OPEN?"open":t===h.CLOSING?"closing":"closed",attachedCliCount:this.getAttachedCliCount(e.id),lockedBy:i?i.cliLabel||i.cliIdentityKey:void 0,lockedByKind:i?i.kind:void 0,lockExpiresAt:i?i.expiresAt:void 0,userFocused:e.userFocused||void 0,userVisible:e.userVisible,visibilityState:e.visibilityState,documentFocused:e.documentFocused,kind:e.kind,meta:e.meta}}getActiveLease(e){let t=e.cliLease;return t?Date.now()>=t.expiresAt?(e.cliLease=void 0,null):t:null}tryAcquireLease(e,t,i={}){let s=this.cliIdentityKeyBySocket.get(e)??(()=>{let u=`ws-${this.nextCliFallbackId++}`;return this.cliIdentityKeyBySocket.set(e,u),u})(),n=this.cliLabelBySocket.get(e),a=Date.now(),r=this.getActiveLease(t),c=r&&r.cliIdentityKey===s,l=0;if(r&&!c&&!i.force)return{granted:!1,lease:r,lock:{by:r.cliLabel||r.cliIdentityKey,expiresInMs:Math.max(0,r.expiresAt-a)},bootedCount:0};if(r&&!c&&i.force)for(let[u,m]of this.cliSimBySocket){if(m!==t.id)continue;let p=this.cliIdentityKeyBySocket.get(u);if(p&&p!==s){this.cliSimBySocket.delete(u);try{u.close(1e3,"lease claimed by another cli")}catch{}l++}}let d={kind:"cli",cliIdentityKey:s,cliLabel:n,expiresAt:a+o.CLI_LEASE_TTL_MS};return t.cliLease=d,{granted:!0,lease:d,bootedCount:l}}updateUserFocusLease(e,t){let i=t.focused===!0,s=typeof t.visible=="boolean"?t.visible:void 0,n=typeof t.visibilityState=="string"?t.visibilityState:void 0,a=typeof t.documentFocused=="boolean"?t.documentFocused:void 0;e.userFocused===i&&e.userVisible===s&&e.visibilityState===n&&e.documentFocused===a||(e.userFocused=i,e.userVisible=s,e.visibilityState=n,e.documentFocused=a,this.broadcastSimClientStates())}updateUserActivity(e){let t=this.getActiveLease(e);if(t&&t.kind==="cli")return;let s=Date.now()+o.USER_ACTIVE_LEASE_TTL_MS,n=t&&t.kind==="user-active"?Math.max(t.expiresAt,s):s;e.cliLease={kind:"user-active",cliIdentityKey:"__user-active__",cliLabel:"active user",expiresAt:n},this.broadcastSimClientStates()}ensureCliIdentityKey(e){let t=this.cliIdentityKeyBySocket.get(e);if(t)return t;let i=`ws-${this.nextCliFallbackId++}`;return this.cliIdentityKeyBySocket.set(e,i),i}getOpenSim(e){if(e){let s=this.sims.get(e);return s?.ws.readyState===h.OPEN?s:null}let t=this.primarySimId!=null?this.sims.get(this.primarySimId):null;if(t?.ws.readyState===h.OPEN&&t.url)return t;let i=null;for(let s of this.sims.values())if(s.ws.readyState===h.OPEN){if(s.url)return s;i??=s}return t?.ws.readyState===h.OPEN?t:i}async waitForSim(e,t={}){let i=t.attempts??10,s=t.intervalMs??200;for(let n=0;n<i;n++){let a=this.getOpenSim(e);if(a)return a;await new Promise(r=>setTimeout(r,s))}throw new Error(e?`no sim connected with id ${e}`:"no sim connected")}shouldPromoteSim(e){let t=this.primarySimId?this.sims.get(this.primarySimId):null;if(!e.url)return!t;let i=t?.ws.readyState===h.OPEN;if(!t||!i||!t.url)return!0;let s=e.origin?.includes(":5173"),n=t.origin?.includes(":5173");return!!s||!n}broadcastSimAssignments(){for(let e of this.sims.values())e.ws.readyState===h.OPEN&&e.ws.send(JSON.stringify({type:"bridge:welcome",simId:e.id,isPrimary:e.id===this.primarySimId}))}broadcastSimClientStates(){for(let e of this.sims.values()){if(e.ws.readyState!==h.OPEN)continue;let t=this.getActiveLease(e),i={type:"bridge:client-state",attachedCliCount:this.getAttachedCliCount(e.id),activeAgentCommandCount:this.getActiveAgentCommandCount(e.id),recentActions:e.recentActions,lockedBy:t?t.cliLabel||t.cliIdentityKey:void 0,lockedByKind:t?t.kind:void 0,lockExpiresAt:t?t.expiresAt:void 0,userFocused:e.userFocused||void 0,userVisible:e.userVisible,visibilityState:e.visibilityState,documentFocused:e.documentFocused};e.ws.send(JSON.stringify(i))}}setCliSimTarget(e,t){let i=this.cliSimBySocket.get(e);i!==t&&(this.cliSimBySocket.set(e,t),this.recordSimAction(t,i?"cli switched sims":"cli connected",!1),this.broadcastSimClientStates())}recordSimAction(e,t,i=!0){let s=t?.trim();if(!s)return;let n=this.sims.get(e);if(!n)return;let a=Date.now();n.lastActiveAt=a,n.recentActions=[{label:s,at:a},...n.recentActions.filter(r=>r.label!==s)].slice(0,4),i&&this.broadcastSimClientStates()}describeForwardedCommand(e){switch(e?.type){case"evaluate":return"evaluated page state";case"screenshot":return"captured screenshot";case"tap":return"sent tap event";case"keyboard":return e?.action==="type"?"typed text":"used keyboard";case"tree":return"dumped tree";case"focus":return"focused sim";case"close":return"requested close";default:return typeof e?.type=="string"?e.type:null}}getAttachedCliCount(e){let t=new Set;for(let[i,s]of this.cliSimBySocket){if(s!==e||i.readyState!==h.OPEN)continue;let n=this.cliIdentityKeyBySocket.get(i);t.add(n??`ws-unknown-${t.size}`)}return t.size}getOtherCliIdentityCount(e,t){let i=this.cliIdentityKeyBySocket.get(e),s=new Set;for(let[n,a]of this.cliSimBySocket){if(a!==t||n.readyState!==h.OPEN)continue;let r=this.cliIdentityKeyBySocket.get(n);r&&r===i||s.add(r??`ws-unknown-${s.size}`)}return s.size}getActiveAgentCommandCount(e){let t=0;for(let i of this.pendingCommands.values())i.simId===e&&t++;return t}allocateSimId(){for(;;){let e=this.nextSimNumber.toString(16);if(this.nextSimNumber++,!this.sims.has(e)&&!this.restorableSims.has(e))return e}}tryRestoreSimId(e,t){let i=t?.trim();if(!i||i===e.id)return!1;let s=this.sims.get(i);if(s&&s!==e&&s.ws.readyState===h.OPEN)return!1;let n=this.getRestorableSimState(i),a=e.id;this.sims.delete(a),e.id=i,n&&(e.recentActions=n.recentActions.map(r=>({...r})),e.lastActiveAt=n.lastActiveAt,e.cliLease=n.cliLease?{...n.cliLease}:void 0,this.restorableSims.delete(i)),this.sims.set(e.id,e),this.primarySimId===a&&(this.primarySimId=e.id);for(let[r,c]of this.cliSimBySocket)c===a&&this.cliSimBySocket.set(r,e.id);return!0}rememberDisconnectedSim(e){let t=this.getActiveLease(e);this.restorableSims.set(e.id,{recentActions:e.recentActions.map(i=>({...i})),lastActiveAt:e.lastActiveAt,cliLease:t&&t.kind==="cli"?{...t}:void 0,expiresAt:Date.now()+o.SIM_RECONNECT_TTL_MS}),this.sims.delete(e.id)}getRestorableSimState(e){let t=this.restorableSims.get(e);return t?t.expiresAt<=Date.now()?(this.restorableSims.delete(e),null):(t.cliLease&&t.cliLease.expiresAt<=Date.now()&&(t.cliLease=void 0),t):null}sweepRestorableSims(e=Date.now()){for(let[t,i]of this.restorableSims)if(!(i.expiresAt>e)){this.restorableSims.delete(t);for(let[s,n]of this.cliSimBySocket)n===t&&this.cliSimBySocket.delete(s)}}resetServerState(){this.cliIdleTimer&&(clearInterval(this.cliIdleTimer),this.cliIdleTimer=null),this.wsHeartbeatTimer&&(clearInterval(this.wsHeartbeatTimer),this.wsHeartbeatTimer=null),this.runtimeUpdateTimer&&(clearInterval(this.runtimeUpdateTimer),this.runtimeUpdateTimer=null);let e=this.wss,t=this.httpServer;if(this.wss=null,this.httpServer=null,e)try{e.close()}catch{}if(t)try{t.close()}catch{}}};function Tt(){return!!((process.env.XPC_SERVICE_NAME||"").includes("dev.sootsim.daemon")||process.env.INVOCATION_ID)}async function Si(o,e={}){(o.includes("--help")||o.includes("-h"))&&(console.log(`
23
23
  sootsim serve \u2014 run the sootsim bridge in the foreground
24
24
 
25
25
  hosts the WS bridge that CLI commands talk to. once running, any sootsim
@@ -37,5 +37,5 @@ examples:
37
37
  sootsim serve
38
38
  sootsim serve --port 7668 --quiet
39
39
  `),process.exit(0));let t=o.indexOf("--port"),i=t>=0&&o[t+1]?Number(o[t+1]):e.port??7668;Number.isNaN(i)&&(console.error(` invalid --port value: ${o[t+1]}`),process.exit(1));let s=o.includes("--quiet")||o.includes("-q"),n=Y();n&&Z(n)&&(console.error(` a sootsim bridge is already running (pid ${n.pid}, port ${n.bridgePort})`),console.error(" stop it with 'sootsim daemon stop' first"),process.exit(1)),O();let a=await ue(),r=new N({port:i,writeLockfile:!0,contrastOrigin:a}),c=await r.startAsync({silent:s}),l=Date.now(),d=f=>{s||process.stdout.write(`${f}
40
- `)},u=new Set,m=setInterval(()=>{let f=r.listSims(),S=new Set(f.map(g=>g.id));for(let g of f)if(!u.has(g.id)){let b=g.title||g.url||g.origin||"(unknown)";d(` + ${g.id} ${b}`)}for(let g of u)S.has(g)||d(` - ${g}`);u.clear();for(let g of S)u.add(g)},500);re({event:"daemon_heartbeat",properties:{bridge_port:c,under_daemon:It(),platform:process.platform,subsource:"daemon"}}),ne(),d(`sootsim bridge listening on ws://localhost:${c} (runtime http on same port)`),c!==i&&d(` (preferred port ${i} was taken \u2014 fell back to ${c})`),d(" ready for browser, electron, or headless playwright sims to connect"),d(" (ctrl-c to stop)");let p=async f=>{clearInterval(m),d(`
41
- ${f} received \u2014 shutting down after ${Math.round((Date.now()-l)/1e3)}s`);try{await r.close()}catch{}process.exit(0)};process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),process.on("SIGHUP",()=>p("SIGHUP")),process.on("exit",()=>{try{r.removeLockfile()}catch{}}),await new Promise(()=>{})}export{gi as runServe};
40
+ `)},u=new Set,m=setInterval(()=>{let f=r.listSims(),S=new Set(f.map(g=>g.id));for(let g of f)if(!u.has(g.id)){let b=g.title||g.url||g.origin||"(unknown)";d(` + ${g.id} ${b}`)}for(let g of u)S.has(g)||d(` - ${g}`);u.clear();for(let g of S)u.add(g)},500);re({event:"daemon_heartbeat",properties:{bridge_port:c,under_daemon:Tt(),platform:process.platform,subsource:"daemon"}}),ne(),d(`sootsim bridge listening on ws://localhost:${c} (runtime http on same port)`),c!==i&&d(` (preferred port ${i} was taken \u2014 fell back to ${c})`),d(" ready for browser, electron, or headless playwright sims to connect"),d(" (ctrl-c to stop)");let p=async f=>{clearInterval(m),d(`
41
+ ${f} received \u2014 shutting down after ${Math.round((Date.now()-l)/1e3)}s`);try{await r.close()}catch{}process.exit(0)};process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),process.on("SIGHUP",()=>p("SIGHUP")),process.on("exit",()=>{try{r.removeLockfile()}catch{}}),await new Promise(()=>{})}export{Si as runServe};
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.244 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{a as g,b as k}from"./chunk-5MSFB4LE.js";import{b as S,c as x}from"./chunk-SEW3SBFZ.js";import{a as w}from"./chunk-PLVKGUKI.js";import"./chunk-PWDCBXRI.js";import"./chunk-3D6IXEES.js";import"./chunk-2D62IZA6.js";import"./chunk-2OPBDHZC.js";import"./chunk-QRQRHX3L.js";import"./chunk-OTHI65BB.js";import"./chunk-S4KDO7C5.js";import"./chunk-67ZCDTCV.js";import{H as v,M as f,O as m,l as b}from"./chunk-LJTFFZX3.js";import"./chunk-MG2NFJOU.js";import"./chunk-G5F4MWYF.js";import"./chunk-DOSHBZMI.js";import"./chunk-QDSYYPBW.js";import{existsSync as r,mkdirSync as j,readFileSync as d,readdirSync as I,writeFileSync as D}from"fs";import{basename as p,dirname as y,join as i,relative as c,resolve as h}from"path";var T=["bun","pnpm","npm"];async function pe(n){(n.includes("--help")||n.includes("-h"))&&(console.log(`
1
+ /*! sootsim v0.1.246 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a as g,b as k}from"./chunk-SG737QIC.js";import{b as S,c as x}from"./chunk-RQIX3DGK.js";import{a as w}from"./chunk-N3JXF26I.js";import"./chunk-FZF3UW6C.js";import"./chunk-2NAUITBE.js";import"./chunk-3S3JZR2C.js";import"./chunk-S3Z2QPNE.js";import"./chunk-D4JXR3AG.js";import"./chunk-SRRNKOGW.js";import"./chunk-XIF34IJ4.js";import"./chunk-EKYPPHQ6.js";import{H as v,M as f,O as m,l as b}from"./chunk-Y34GLBNG.js";import"./chunk-MJDIZUU2.js";import"./chunk-B7LILV2Q.js";import"./chunk-XFVWTZ23.js";import"./chunk-PK3IUSQE.js";import{existsSync as r,mkdirSync as j,readFileSync as d,readdirSync as I,writeFileSync as D}from"fs";import{basename as p,dirname as y,join as i,relative as c,resolve as h}from"path";var T=["bun","pnpm","npm"];async function pe(n){(n.includes("--help")||n.includes("-h"))&&(console.log(`
3
3
  sootsim setup \u2014 set up this machine for SootSim
4
4
 
5
5
  usage:
@@ -94,4 +94,4 @@ module.exports = {
94
94
  4. inspect and drive it:
95
95
  sootsim describe
96
96
  sootsim do tap-text "Sign in"
97
- `)}function N(n,e){switch(n){case"bun":return`bunx ${e}`;case"pnpm":return`pnpm exec ${e}`;case"npm":return`npx ${e}`}}function ne(n,e){switch(n){case"bun":return`bun run ${e}`;case"pnpm":return`pnpm run ${e}`;case"npm":return`npm run ${e}`}}function oe(n){switch(n){case"bun":return"bun add -g sootsim";case"pnpm":return"pnpm add -g sootsim";case"npm":return"npm i -g sootsim"}}async function te(n,e){if(!e||n.dryRun)return;if(console.log(" last step:"),!process.stdin.isTTY){console.log(" run `sootsim open` after your Metro/Expo/One server is up");return}if(!await g("I'll run `sootsim open` for you now?",!0)){console.log(" later: sootsim open");return}let{runOpenCommand:o}=await import("./control-UDPDWRBU.js");await o([],{port:7668})}async function R(n,e,o){return o.yes?!0:process.stdin.isTTY?g(n,e):(console.log(` ${n} ${e?"[Y/n]":"[y/N]"} n (non-interactive; pass --yes to accept)`),!1)}export{J as detectConfigScaffoldExt,M as detectNodeVersionPins,W as detectPreferredPackageManager,E as readMachineSetupStatus,pe as runSetup,de as shouldRunSetupForBareCommand};
97
+ `)}function N(n,e){switch(n){case"bun":return`bunx ${e}`;case"pnpm":return`pnpm exec ${e}`;case"npm":return`npx ${e}`}}function ne(n,e){switch(n){case"bun":return`bun run ${e}`;case"pnpm":return`pnpm run ${e}`;case"npm":return`npm run ${e}`}}function oe(n){switch(n){case"bun":return"bun add -g sootsim";case"pnpm":return"pnpm add -g sootsim";case"npm":return"npm i -g sootsim"}}async function te(n,e){if(!e||n.dryRun)return;if(console.log(" last step:"),!process.stdin.isTTY){console.log(" run `sootsim open` after your Metro/Expo/One server is up");return}if(!await g("I'll run `sootsim open` for you now?",!0)){console.log(" later: sootsim open");return}let{runOpenCommand:o}=await import("./control-ZGVBXUKX.js");await o([],{port:7668})}async function R(n,e,o){return o.yes?!0:process.stdin.isTTY?g(n,e):(console.log(` ${n} ${e?"[Y/n]":"[y/N]"} n (non-interactive; pass --yes to accept)`),!1)}export{J as detectConfigScaffoldExt,M as detectNodeVersionPins,W as detectPreferredPackageManager,E as readMachineSetupStatus,pe as runSetup,de as shouldRunSetupForBareCommand};
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.244 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import"./chunk-QDSYYPBW.js";import*as i from"fs";import*as I from"os";import*as a from"path";import{fileURLToPath as h}from"url";function $(){try{let t=h(import.meta.resolve("sootsim/package.json"));return a.join(a.dirname(t),"skills")}catch{let t=a.dirname(h(import.meta.url));return a.resolve(t,"../../skills")}}var d=$(),w=new Set(["all","codex","claude"]);function S(){console.log(`sootsim skill
1
+ /*! sootsim v0.1.246 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import"./chunk-PK3IUSQE.js";import*as i from"fs";import*as I from"os";import*as a from"path";import{fileURLToPath as h}from"url";function $(){try{let t=h(import.meta.resolve("sootsim/package.json"));return a.join(a.dirname(t),"skills")}catch{let t=a.dirname(h(import.meta.url));return a.resolve(t,"../../skills")}}var d=$(),w=new Set(["all","codex","claude"]);function S(){console.log(`sootsim skill
3
3
 
4
4
  install and inspect bundled SootSim agent skills.
5
5
 
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.244 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{k as f}from"./chunk-Y2KQOMYR.js";import"./chunk-WR36BYQG.js";import"./chunk-5ESYYH63.js";import"./chunk-7YLGDFKU.js";import"./chunk-MKA7IFWN.js";import{a as t,b as n,c as l,d as c,e as a}from"./chunk-VJYSRAHZ.js";import"./chunk-YULJQBOJ.js";import"./chunk-DL3M4AVQ.js";import"./chunk-XVEN5M47.js";import"./chunk-CW6ZDGC2.js";import"./chunk-6BB55GST.js";import"./chunk-HH5BFXN5.js";import"./chunk-UEHOXLFD.js";import"./chunk-R2DSJS7L.js";import"./chunk-TL5J6UCV.js";import"./chunk-2OPBDHZC.js";import"./chunk-QRQRHX3L.js";import"./chunk-OTHI65BB.js";import"./chunk-S4KDO7C5.js";import"./chunk-67ZCDTCV.js";import"./chunk-LJTFFZX3.js";import"./chunk-JM7KI2DG.js";import"./chunk-DOSHBZMI.js";import"./chunk-QDSYYPBW.js";function p(){console.log(`
1
+ /*! sootsim v0.1.246 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{k as f}from"./chunk-T3U2KTTT.js";import"./chunk-HR5I5I3F.js";import"./chunk-3MWRVAIS.js";import"./chunk-SYR5I5FQ.js";import"./chunk-D4XZ5NEJ.js";import{a as t,b as n,c as l,d as c,e as a}from"./chunk-W7NCZBX7.js";import"./chunk-3CXN2CRU.js";import"./chunk-HYHHQXLJ.js";import"./chunk-ZNESHNGU.js";import"./chunk-K7JYLDUZ.js";import"./chunk-NUJBILY7.js";import"./chunk-CY2RNPJB.js";import"./chunk-CFVKQHZA.js";import"./chunk-6EQOR5WW.js";import"./chunk-J7KMGE4S.js";import"./chunk-S3Z2QPNE.js";import"./chunk-D4JXR3AG.js";import"./chunk-SRRNKOGW.js";import"./chunk-XIF34IJ4.js";import"./chunk-EKYPPHQ6.js";import"./chunk-Y34GLBNG.js";import"./chunk-EJMHVFJ6.js";import"./chunk-XFVWTZ23.js";import"./chunk-PK3IUSQE.js";function p(){console.log(`
3
3
  sootsim storage profile \u2014 manage isolated storage profiles
4
4
 
5
5
  usage:
@@ -0,0 +1,2 @@
1
+ /*! sootsim v0.1.246 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a}from"./chunk-EJMHVFJ6.js";import"./chunk-XFVWTZ23.js";import"./chunk-PK3IUSQE.js";export{a as settingsStore};
@@ -0,0 +1,2 @@
1
+ /*! sootsim v0.1.246 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a,b}from"./chunk-N3JXF26I.js";import"./chunk-FZF3UW6C.js";import"./chunk-Y34GLBNG.js";import"./chunk-PK3IUSQE.js";export{b as flushCliTelemetry,a as trackCliEvent};
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.244 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{g as m,i as d,l as s}from"./chunk-R2DSJS7L.js";import"./chunk-OTHI65BB.js";import"./chunk-S4KDO7C5.js";import"./chunk-LJTFFZX3.js";import"./chunk-QDSYYPBW.js";import{writeFileSync as g}from"fs";function u(){console.log(`
1
+ /*! sootsim v0.1.246 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{g as m,i as d,l as s}from"./chunk-6EQOR5WW.js";import"./chunk-SRRNKOGW.js";import"./chunk-XIF34IJ4.js";import"./chunk-Y34GLBNG.js";import"./chunk-PK3IUSQE.js";import{writeFileSync as g}from"fs";function u(){console.log(`
3
3
  sootsim timeline \u2014 control the semantic event timeline
4
4
 
5
5
  usage:
@@ -1,4 +1,4 @@
1
- /*! sootsim v0.1.244 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{a as d}from"./chunk-D5ZQSHVC.js";import{e as m}from"./chunk-MZWAGLVV.js";import"./chunk-R2DSJS7L.js";import"./chunk-OTHI65BB.js";import"./chunk-S4KDO7C5.js";import{K as a,g as r,h as l}from"./chunk-LJTFFZX3.js";import{a as c}from"./chunk-MG2NFJOU.js";import"./chunk-QDSYYPBW.js";import{spawn as g}from"node:child_process";import u from"node:fs";import p from"node:os";import e from"node:path";var f="https://registry.npmjs.org/sootsim/latest";async function j(o){let n=o.indexOf("--channel"),t=n>=0&&o[n+1]?o[n+1]:void 0;console.log(`sootsim upgrade
1
+ /*! sootsim v0.1.246 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a as d}from"./chunk-PZ3WING3.js";import{e as m}from"./chunk-F5BJD6Z5.js";import"./chunk-6EQOR5WW.js";import"./chunk-SRRNKOGW.js";import"./chunk-XIF34IJ4.js";import{K as a,g as r,h as l}from"./chunk-Y34GLBNG.js";import{a as c}from"./chunk-MJDIZUU2.js";import"./chunk-PK3IUSQE.js";import{spawn as g}from"node:child_process";import u from"node:fs";import p from"node:os";import e from"node:path";var f="https://registry.npmjs.org/sootsim/latest";async function j(o){let n=o.indexOf("--channel"),t=n>=0&&o[n+1]?o[n+1]:void 0;console.log(`sootsim upgrade
3
3
  `),console.log("runtime:");let i=m();i&&(console.log(` pinned to ${i} \u2014 installing the pin, not channel latest`),console.log(" (run `sootsim runtime unpin` to follow latest again)")),await d(["install",...t?["--channel",t]:[]],{}),console.log(`
4
4
  cli:`),await $()}function h(){if(l())return{kind:"dev"};let o=process.argv[1]??"";try{o=u.realpathSync(o)}catch{}let n=e.sep;if(o.includes(`${n}_npx${n}`)||o.includes(`${n}.bunx${n}`))return{kind:"npx"};if(o.includes(`${n}.bun${n}`))return{kind:"global",command:"bun",args:["add","-g","sootsim@latest"]};if(o.includes(`${n}pnpm${n}`))return{kind:"global",command:"pnpm",args:["add","-g","sootsim@latest"]};let t=e.join(r(),"cli");if(o.startsWith(`${t}${n}`))return{kind:"global",command:"npm",args:["i","-g","--prefix",t,"sootsim@latest"]};let i=e.resolve(process.env.SOOTSIM_CLI_PREFIX||e.join(p.homedir(),".local"));return o.startsWith(`${i}${n}`)?{kind:"global",command:"npm",args:["i","-g","--prefix",i,"sootsim@latest"]}:{kind:"global",command:"npm",args:["i","-g","sootsim@latest"]}}async function $(){let o=c(),n=await k();if(!n){console.log(` v${o} \u2014 couldn't reach the npm registry, skipped`);return}if(a(n,o)<=0){console.log(` v${o} (latest)`);return}let t=h();if(console.log(` v${o} \u2192 v${n}`),t.kind==="dev"){console.log(" running from the Contrast dev checkout \u2014 pull instead of upgrading");return}if(t.kind==="npx"){console.log(" running from the npx cache \u2014 get the latest with:"),console.log(" npx sootsim@latest");return}let i=`${t.command} ${t.args.join(" ")}`;console.log(` updating global install (${i})\u2026`),await v(t.command,t.args)?console.log(` updated to v${n}`):(console.log(" update failed \u2014 run it yourself:"),console.log(` ${i}`))}function v(o,n){return new Promise(t=>{let i=g(o,n,{stdio:"inherit"});i.on("error",()=>t(!1)),i.on("exit",s=>t(s===0))})}async function k(){try{let o=await fetch(f,{headers:{accept:"application/json"},signal:AbortSignal.timeout(8e3)});if(!o.ok)return null;let n=await o.json();return typeof n.version=="string"&&n.version?n.version:null}catch{return null}}export{j as runUpgrade};
@@ -0,0 +1,2 @@
1
+ /*! sootsim v0.1.246 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{e as a,f as b,g as c}from"./chunk-KUHWG5A3.js";import"./chunk-3SVLVFLE.js";import"./chunk-HYHHQXLJ.js";import"./chunk-ZNESHNGU.js";import"./chunk-K7JYLDUZ.js";import"./chunk-6EQOR5WW.js";import"./chunk-N3JXF26I.js";import"./chunk-FZF3UW6C.js";import"./chunk-SRRNKOGW.js";import"./chunk-XIF34IJ4.js";import"./chunk-Y34GLBNG.js";import"./chunk-PK3IUSQE.js";export{a as resolveDefaultUploadOrigin,b as resolvePublicPreviewOrigin,c as runUpload};
@@ -1,4 +1,4 @@
1
- /*! sootsim v0.1.244 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{b as s,d as l,i as r}from"./chunk-MZWAGLVV.js";import{a as i}from"./chunk-2D62IZA6.js";import"./chunk-LJTFFZX3.js";import{a as t}from"./chunk-MG2NFJOU.js";import"./chunk-QDSYYPBW.js";async function f(c){let{IS_BETA:m,BETA_LABEL:a}=await import("./beta-G5FZ5RSW.js"),u=m?` \xB7 ${a}`:"";console.log(`sootsim v${t()}${u}`);let o=i(),e=l();o.isDevBridge?(console.log(o.primary),o.installedRuntime&&console.log(`${o.installedRuntime} \xB7 ${e}`)):o.primary==="runtime not installed"?console.log("runtime not installed \u2014 run `sootsim runtime install`"):console.log(`${o.primary} \xB7 ${e}`);let n=await r({channel:e});n.pinned&&console.log(` runtime pinned to v${n.pinned} (\`sootsim runtime unpin\` to follow latest)`),n.outdated&&n.latest&&console.log(`
1
+ /*! sootsim v0.1.246 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{b as s,d as l,i as r}from"./chunk-F5BJD6Z5.js";import{a as i}from"./chunk-3S3JZR2C.js";import"./chunk-Y34GLBNG.js";import{a as t}from"./chunk-MJDIZUU2.js";import"./chunk-PK3IUSQE.js";async function f(c){let{IS_BETA:m,BETA_LABEL:a}=await import("./beta-XSTWPVNL.js"),u=m?` \xB7 ${a}`:"";console.log(`sootsim v${t()}${u}`);let o=i(),e=l();o.isDevBridge?(console.log(o.primary),o.installedRuntime&&console.log(`${o.installedRuntime} \xB7 ${e}`)):o.primary==="runtime not installed"?console.log("runtime not installed \u2014 run `sootsim runtime install`"):console.log(`${o.primary} \xB7 ${e}`);let n=await r({channel:e});n.pinned&&console.log(` runtime pinned to v${n.pinned} (\`sootsim runtime unpin\` to follow latest)`),n.outdated&&n.latest&&console.log(`
3
3
  \u2191 runtime v${n.latest} available \u2014 run \`sootsim upgrade\``),console.log(`
4
4
  what's new: ${s}`)}export{f as runVersion};