bridge-agent 0.16.0 → 0.16.4

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 (2) hide show
  1. package/dist/index.js +1 -1
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -273,7 +273,7 @@ session. You may call bridge_get_role_prompt again at any time to refresh.
273
273
 
274
274
  If bridge_get_role_prompt is unavailable, fall back to default behavior for role=${t}.`}var ju=/^[A-Za-z0-9][A-Za-z0-9._:\/-]{0,127}$/;function Do(t){return t?ju.test(t):!1}var Bu=new Set(["claude","aider","ollama"]);function La(t){return Bu.has(t)}var ja=v(require("os"));async function Mo(){return ja.default.platform()!=="darwin"?null:{key:"sim_ios",displayName:"iOS Simulator",binaryPath:"xcrun",authStatus:"ok"}}var it=require("child_process"),jo=require("fs/promises"),Wa=require("crypto"),Bt=v(require("fs")),cr=v(require("path")),Bo=v(require("os"));var pn=require("child_process"),Ba=require("fs/promises"),$a=v(require("path")),Ua=v(require("os"));async function $u(){return new Promise(t=>{let e=(0,pn.spawn)("xcrun",["simctl","list","devices","booted","--json"],{timeout:5e3}),n="";e.stdout.on("data",r=>{n+=r.toString("utf8")}),e.on("close",r=>{if(r!==0){t(null);return}try{let o=JSON.parse(n);for(let i of Object.values(o.devices)){let s=i.find(a=>a.state==="Booted");if(s){t(s.udid);return}}t(null)}catch{t(null)}}),e.on("error",()=>t(null))})}async function Uu(){return new Promise(t=>{let e=(0,pn.spawn)("xcrun",["simctl","list","devices","available","--json"],{timeout:5e3}),n="";e.stdout.on("data",r=>{n+=r.toString("utf8")}),e.on("close",r=>{if(r!==0){t([]);return}try{let o=JSON.parse(n),i=[];for(let[s,a]of Object.entries(o.devices)){for(let c of a){let l=s.replace(/^com\.apple\.CoreSimulator\.SimRuntime\./,"").replace(/-/g,".");if(i.push(`${c.name} (${l})`),i.length>=3)break}if(i.length>=3)break}t(i)}catch{t([])}}),e.on("error",()=>t([]))})}async function Lo(t){let e=[],n=null,r=await new Promise(i=>{let s=(0,pn.spawn)("xcrun",["simctl","help"],{timeout:2e3});s.on("close",a=>i(a===0)),s.on("error",()=>i(!1)),s.stdout?.resume(),s.stderr?.resume()});e.push({id:"xcrun_exists",status:r?"pass":"fail",label:"Xcode CLI tools",detail:r?void 0:"Xcode command-line tools not found. Install them to use the iOS Simulator panel.",fixCmd:r?void 0:"xcode-select --install"});let o=!1;if(r){let i=$a.default.join(Ua.default.homedir(),".local/bin/idb");o=await(0,Ba.access)(i).then(()=>!0).catch(()=>!1)}if(e.push({id:"idb_present",status:o?"pass":"fail",label:"idb",detail:o?void 0:"idb not found at ~/.local/bin/idb. Required for simulator automation.",fixCmd:o?void 0:"pip3 install fb-idb && brew install facebook/fb/idb-companion"}),r){let i=await new Promise(s=>{let a=(0,pn.spawn)("xcrun",["simctl","list","--json"],{timeout:5e3});a.on("close",c=>s(c===0)),a.on("error",()=>s(!1)),a.stdout?.resume(),a.stderr?.resume()});if(e.push({id:"simctl_ok",status:i?"pass":"fail",label:"simctl",detail:i?void 0:"simctl is not responding. Xcode may not be fully installed.",fixCmd:i?void 0:"sudo xcode-select --reset"}),i)if(n=await $u(),n)e.push({id:"booted_simulator",status:"pass",label:"Booted simulator"});else{let s=await Uu();e.push({id:"booted_simulator",status:"fail",label:"Booted simulator",detail:s.length>0?`No simulator is booted. Available: ${s.join(", ")}. Open Simulator.app and boot one.`:"No simulator is booted and no devices found. Open Xcode \u2192 Window \u2192 Devices and Simulators to add one.",fixCmd:"open -a Simulator"})}else e.push({id:"booted_simulator",status:"fail",label:"Booted simulator",detail:"Skipped \u2014 previous check failed"})}else e.push({id:"simctl_ok",status:"fail",label:"simctl",detail:"Skipped \u2014 previous check failed"}),e.push({id:"booted_simulator",status:"fail",label:"Booted simulator",detail:"Skipped \u2014 previous check failed"});return{checks:e,udid:n}}var $o=cr.default.join(Bo.default.homedir(),".local/bin/idb");async function Fa(t){try{let e=await new Promise((i,s)=>{let a=(0,it.spawn)($o,["describe","--udid",t,"--json"],{timeout:1e4}),c="",l="";a.stdout.on("data",d=>{c+=d.toString("utf8")}),a.stderr.on("data",d=>{l+=d.toString("utf8")}),a.on("close",d=>{d!==0?s(new Error(l||`idb exited ${d}`)):i(c)}),a.on("error",d=>s(d))}),n=JSON.parse(e),r=n.screen_dimensions?.width_points,o=n.screen_dimensions?.height_points;if(Number.isFinite(r)&&Number.isFinite(o))return{width:r,height:o}}catch(e){console.warn("[daemon] simulator.metadata.error",{udid:t,error:String(e)})}return{}}function Fu(t,e,n){let r=Buffer.from(t,"utf-8"),o=Buffer.allocUnsafe(1+r.length+4);return o.writeUInt8(r.length,0),r.copy(o,1),o.writeUInt16BE(Math.max(0,Math.min(65535,e)),1+r.length),o.writeUInt16BE(Math.max(0,Math.min(65535,n)),1+r.length+2),o}function Wu(t,e){let n=`/tmp/sim_frame_${e}.png`,r=`/tmp/sim_frame_${e}.jpg`;return new Promise(o=>{let i=(0,it.spawn)("xcrun",["simctl","io",t,"screenshot",n],{stdio:["ignore","ignore","ignore"]});i.on("close",async s=>{if(s!==0){o(null);return}try{await new Promise((a,c)=>{let l=(0,it.spawn)("sips",["-s","format","jpeg",n,"--out",r],{stdio:["ignore","ignore","ignore"]});l.on("close",d=>d===0?a():c(new Error(`sips exited ${d}`))),l.on("error",d=>c(d))}),o(await(0,jo.readFile)(r))}catch{try{o(await(0,jo.readFile)(n))}catch{o(null)}}}),i.on("error",()=>o(null))})}function ar(t,e){return new Promise((n,r)=>{let o=(0,it.spawn)($o,[...e,"--udid",t],{timeout:15e3}),i="";o.stderr.on("data",s=>{i+=s.toString("utf8")}),o.on("close",s=>{s!==0?r(new Error(i||`idb exited ${s}`)):n()}),o.on("error",s=>r(s))})}var lr=class{sessions=new Map;pendingSubscriptions=new Set;pendingUdids=new Map;pendingDaemonBootedUdids=new Set;bootedUdidsByAgent=new Map;ws=null;daemonId;installProc=new Map;cancelledInstalls=new Set;constructor(e){this.daemonId=e}updateWs(e){this.ws=e}async start(e){if(this.sessions.has(e)){console.warn("[daemon] simulator.start: session already exists",{agentId:e});return}let{checks:n,udid:r}=await Lo(e);if(this.sendSimHealth(e,n),n.find(u=>u.status==="fail")){if(this.bootedUdidsByAgent.has(e)){let u=this.bootedUdidsByAgent.get(e);this.pendingDaemonBootedUdids.delete(u),this.bootedUdidsByAgent.delete(e)}return}if(!r){this.sendError(e,"SPAWN_FAILED","No booted iOS simulator found");return}let i=[...this.sessions.values()].find(u=>u.udid===r);if(i){this.sendError(e,"DUPLICATE_SIMULATOR",`Simulator already attached as agent ${i.agentId}`,{existingAgentId:i.agentId,udid:r});return}let s=this.pendingUdids.get(r);if(s&&s!==e){this.sendError(e,"DUPLICATE_SIMULATOR",`Simulator already being attached as agent ${s}`,{existingAgentId:s,udid:r});return}this.pendingUdids.set(r,e);let a=this.pendingSubscriptions.has(e);this.pendingSubscriptions.delete(e);let c=await Fa(r);c.width!=null&&c.height!=null&&console.log("[daemon] simulator.metadata",{agentId:e,udid:r,logicalWidth:c.width,logicalHeight:c.height});let l=this.pendingDaemonBootedUdids.has(r);l&&(this.pendingDaemonBootedUdids.delete(r),this.bootedUdidsByAgent.delete(e));let d={agentId:e,udid:r,frameInterval:null,capturing:!1,subscribed:a,logicalWidth:c.width,logicalHeight:c.height,lastDescribeAt:Date.now(),daemonBooted:l};if(this.sessions.set(e,d),this.pendingUdids.delete(r),d.frameInterval=setInterval(async()=>{if(!(!d.subscribed||d.capturing)&&!(!this.ws||this.ws.bufferedAmount>256*1024)){d.capturing=!0;try{Date.now()-d.lastDescribeAt>=5e3&&(d.lastDescribeAt=Date.now(),Fa(r).then(p=>{p.width!=null&&p.height!=null&&(p.width!==d.logicalWidth||p.height!==d.logicalHeight)&&(console.log("[daemon] simulator.metadata.update",{agentId:e,udid:r,from:{logicalWidth:d.logicalWidth,logicalHeight:d.logicalHeight},to:p}),d.logicalWidth=p.width,d.logicalHeight=p.height)}).catch(()=>{}));let u=await Wu(r,e);if(u&&this.ws&&this.ws.readyState===I.OPEN){let p=d.logicalWidth??0,f=d.logicalHeight??0,g=Fu(e,p,f);this.ws.send(Buffer.concat([g,u]),{binary:!0})}}catch(u){console.error("[daemon] simulator.capture.error",{agentId:e,error:String(u)})}finally{d.capturing=!1}}},200),this.ws&&this.ws.readyState===I.OPEN){let u=(0,Wa.randomUUID)();this.ws.send(JSON.stringify({type:"session_started",agentId:e,sessionId:u})),this.ws.send(JSON.stringify({type:"agent_spawned",agentId:e,agentKey:"sim_ios",daemonId:this.daemonId}))}console.log("[daemon] simulator.started",{agentId:e,udid:r})}stop(e){let n=this.installProc.get(e);n&&(console.log("[daemon] simulator.install.cancelled",{agentId:e}),this.cancelledInstalls.add(e),n.kill("SIGTERM"),this.installProc.delete(e));let r=this.sessions.get(e);if(!r){for(let[s,a]of this.pendingUdids)if(a===e){this.pendingUdids.delete(s);break}return}r.frameInterval&&clearInterval(r.frameInterval);let o=r.udid,i=r.daemonBooted;this.sessions.delete(e),this.pendingUdids.delete(o),this.ws&&this.ws.readyState===I.OPEN&&this.ws.send(JSON.stringify({type:"exit",agentId:e,exitCode:0,signal:null})),console.log("[daemon] simulator.stop",{agentId:e,udid:o,daemonBooted:i}),i&&(0,it.spawn)("xcrun",["simctl","shutdown",o],{stdio:"ignore"}).on("error",s=>console.warn("[daemon] simulator.shutdown.error",{udid:o,err:String(s)}))}stopAll(){for(let e of[...this.installProc.keys()])this.stop(e);for(let e of[...this.sessions.keys()])this.stop(e)}subscribe(e){let n=this.sessions.get(e);n&&(n.subscribed=!0)}unsubscribe(e){let n=this.sessions.get(e);n&&(n.subscribed=!1)}async handle(e){let n=this.sessions.get(e.agentId);if(e.type==="sim_subscribe"){n?this.subscribe(e.agentId):this.pendingSubscriptions.add(e.agentId);return}if(e.type==="sim_unsubscribe"){this.pendingSubscriptions.delete(e.agentId),n&&this.unsubscribe(e.agentId);return}if(e.type==="sim_healthcheck"){let{checks:r}=await Lo(e.agentId);this.sendSimHealth(e.agentId,r);return}if(e.type==="sim_install_run"){await this.handleSimInstallRun(e.agentId);return}if(e.type==="sim_install_cancel"){this.handleSimInstallCancel(e.agentId);return}if(!n){console.warn("[daemon] simulator.handle: no session",{agentId:e.agentId,type:e.type});return}try{switch(e.type){case"sim_tap":{await ar(n.udid,["ui","tap",String(e.x),String(e.y)]);break}case"sim_swipe":{await ar(n.udid,["ui","swipe",String(e.x1),String(e.y1),String(e.x2),String(e.y2),"--duration",String(e.duration??.5)]);break}case"sim_key":{await ar(n.udid,["ui","text",e.key]);break}case"sim_button":{console.log("[daemon] simulator.button.start",{agentId:e.agentId,button:e.button,udid:n.udid}),await ar(n.udid,["ui","button",e.button]),console.log("[daemon] simulator.button.done",{agentId:e.agentId,button:e.button});break}case"sim_get_source":{let r=await new Promise((o,i)=>{let s=(0,it.spawn)($o,["ui","describe-all","--udid",n.udid],{timeout:15e3}),a="",c="";s.stdout.on("data",l=>{a+=l.toString("utf8")}),s.stderr.on("data",l=>{c+=l.toString("utf8")}),s.on("close",l=>{l!==0?i(new Error(c||`idb exited ${l}`)):o(a)}),s.on("error",l=>i(l))});this.ws&&this.ws.readyState===I.OPEN&&this.ws.send(JSON.stringify({type:"sim_source",agentId:e.agentId,source:r}));break}}}catch(r){console.error("[daemon] simulator.handle.error",{agentId:e.agentId,type:e.type,error:String(r)})}}sendError(e,n,r,o){this.ws&&this.ws.readyState===I.OPEN&&this.ws.send(JSON.stringify({type:"error",code:n,message:r,agentId:e,...o}))}sendSimHealth(e,n){this.ws&&this.ws.readyState===I.OPEN&&this.ws.send(JSON.stringify({type:"sim_health",agentId:e,checks:n}))}resolveSimInstallScript(){let e=process.env.BRIDGE_SIM_INSTALL_SCRIPT;if(e)return e;let n=cr.default.join(Bo.default.homedir(),".bridge/install-sim-prereqs.sh");if(Bt.default.existsSync(n))return n;let r=cr.default.join(__dirname,"../../../scripts/install-sim-prereqs.sh");return Bt.default.existsSync(r)?r:null}async handleSimInstallRun(e){if(this.installProc.has(e)){this.sendInstallProgress(e,{step:"error",error:"already installing"});return}this.cancelledInstalls.delete(e);let n=this.resolveSimInstallScript();if(!n){this.sendInstallProgress(e,{step:"error",error:"install script not found"});return}try{Bt.default.accessSync(n,Bt.default.constants.F_OK|Bt.default.constants.X_OK)}catch{this.sendInstallProgress(e,{step:"error",error:`install script not found at ${n}`});return}let r=(0,it.spawn)("bash",["-lc",n],{timeout:6e5});this.installProc.set(e,r);let o="pre_check",i="",s="";r.stdout?.on("data",a=>{i+=a.toString("utf8");let c;for(;(c=i.indexOf(`
275
275
  `))!==-1;){let l=i.slice(0,c);if(i=i.slice(c+1),!!l)if(l.startsWith("STEP:"))o=l.slice(5).trim(),this.sendInstallProgress(e,{step:o});else if(l.startsWith("BOOTED_UDID:")){let d=l.slice(12).trim();this.pendingDaemonBootedUdids.add(d),this.bootedUdidsByAgent.set(e,d)}else this.sendInstallProgress(e,{stream:"stdout",line:l})}}),r.stderr?.on("data",a=>{s+=a.toString("utf8");let c;for(;(c=s.indexOf(`
276
- `))!==-1;){let l=s.slice(0,c);s=s.slice(c+1),l&&this.sendInstallProgress(e,{stream:"stderr",line:l})}}),r.on("close",a=>{if(this.installProc.delete(e),a!==0){let l=this.bootedUdidsByAgent.get(e);l&&(this.pendingDaemonBootedUdids.delete(l),this.bootedUdidsByAgent.delete(e))}if(i){let l=i;i="",l.startsWith("STEP:")?(o=l.slice(5).trim(),this.sendInstallProgress(e,{step:o})):this.sendInstallProgress(e,{stream:"stdout",line:l})}if(s){let l=s;s="",this.sendInstallProgress(e,{stream:"stderr",line:l})}let c=this.cancelledInstalls.has(e);this.cancelledInstalls.delete(e),!c&&(a===0?this.sendInstallProgress(e,{step:"done",exitCode:0}):this.sendInstallProgress(e,{step:"error",exitCode:a??void 0,error:`install script exited with code ${a}`}))}),r.on("error",a=>{this.installProc.delete(e);let c=this.bootedUdidsByAgent.get(e);c&&(this.pendingDaemonBootedUdids.delete(c),this.bootedUdidsByAgent.delete(e));let l=this.cancelledInstalls.has(e);this.cancelledInstalls.delete(e),!l&&this.sendInstallProgress(e,{step:"error",error:String(a)})})}handleSimInstallCancel(e){let n=this.installProc.get(e);if(!n)return;this.cancelledInstalls.add(e);let r=this.bootedUdidsByAgent.get(e);r&&(this.pendingDaemonBootedUdids.delete(r),this.bootedUdidsByAgent.delete(e)),n.kill("SIGTERM"),this.installProc.delete(e),this.sendInstallProgress(e,{step:"error",error:"cancelled by user"})}sendInstallProgress(e,n){this.ws&&this.ws.readyState===I.OPEN&&this.ws.send(JSON.stringify({type:"sim_install_progress",agentId:e,...n}))}};kt();ne();var Za=v(require("path")),Vu="0.16.0",Qa;function re(){return Vu}function le(){if(Qa)return Qa;if(process.pkg!==void 0)return process.execPath;let t=[...process.env.npm_config_global_prefix?[Za.default.join(process.env.npm_config_global_prefix,"lib","node_modules","bridge-agent","dist","index.js")]:[],...process.argv[1]?[process.argv[1]]:[],process.execPath];for(let e of t)try{return require("node:fs").realpathSync(e)}catch{}return process.execPath}var Ho=require("fs"),Go=v(require("path")),tc=v(require("os"));var ec=require("node:fs"),yr=class{cache=new Map;get(e,n){let r=this.cache.get(e);if(r&&r.mtimeMs===n.mtimeMs&&r.size===n.size)return r.value}set(e,n,r){this.cache.set(e,{mtimeMs:n.mtimeMs,size:n.size,value:r})}invalidate(e){this.cache.delete(e)}clear(){this.cache.clear()}prune(e){for(let n of this.cache.keys())e.has(n)||this.cache.delete(n)}prunePrefix(e,n){for(let r of this.cache.keys())r.startsWith(e)&&!n.has(r)&&this.cache.delete(r)}get size(){return this.cache.size}},oe=new yr,Xg=new yr;async function Ce(t){try{let e=await ec.promises.stat(t);return{mtimeMs:e.mtimeMs,size:e.size}}catch{return null}}function at(){return new Promise(t=>setImmediate(t))}var Ku=2e5,Ju="ctx:";async function Yu(t){let e=Go.default.join(tc.default.homedir(),".claude","projects");try{let n=await Ho.promises.readdir(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory())continue;let o=Go.default.join(e,r.name,`${t}.jsonl`);if(await Ce(o))return o}}catch{}}async function zu(t,e){let n=await Ce(t);if(!n)return null;let r=Ju+t,o=oe.get(r,n);if(o!==void 0)return o;await at();try{let s=(await Ho.promises.readFile(t,"utf-8")).trim().split(`
276
+ `))!==-1;){let l=s.slice(0,c);s=s.slice(c+1),l&&this.sendInstallProgress(e,{stream:"stderr",line:l})}}),r.on("close",a=>{if(this.installProc.delete(e),a!==0){let l=this.bootedUdidsByAgent.get(e);l&&(this.pendingDaemonBootedUdids.delete(l),this.bootedUdidsByAgent.delete(e))}if(i){let l=i;i="",l.startsWith("STEP:")?(o=l.slice(5).trim(),this.sendInstallProgress(e,{step:o})):this.sendInstallProgress(e,{stream:"stdout",line:l})}if(s){let l=s;s="",this.sendInstallProgress(e,{stream:"stderr",line:l})}let c=this.cancelledInstalls.has(e);this.cancelledInstalls.delete(e),!c&&(a===0?this.sendInstallProgress(e,{step:"done",exitCode:0}):this.sendInstallProgress(e,{step:"error",exitCode:a??void 0,error:`install script exited with code ${a}`}))}),r.on("error",a=>{this.installProc.delete(e);let c=this.bootedUdidsByAgent.get(e);c&&(this.pendingDaemonBootedUdids.delete(c),this.bootedUdidsByAgent.delete(e));let l=this.cancelledInstalls.has(e);this.cancelledInstalls.delete(e),!l&&this.sendInstallProgress(e,{step:"error",error:String(a)})})}handleSimInstallCancel(e){let n=this.installProc.get(e);if(!n)return;this.cancelledInstalls.add(e);let r=this.bootedUdidsByAgent.get(e);r&&(this.pendingDaemonBootedUdids.delete(r),this.bootedUdidsByAgent.delete(e)),n.kill("SIGTERM"),this.installProc.delete(e),this.sendInstallProgress(e,{step:"error",error:"cancelled by user"})}sendInstallProgress(e,n){this.ws&&this.ws.readyState===I.OPEN&&this.ws.send(JSON.stringify({type:"sim_install_progress",agentId:e,...n}))}};kt();ne();var Za=v(require("path")),Vu="0.16.4",Qa;function re(){return Vu}function le(){if(Qa)return Qa;if(process.pkg!==void 0)return process.execPath;let t=[...process.env.npm_config_global_prefix?[Za.default.join(process.env.npm_config_global_prefix,"lib","node_modules","bridge-agent","dist","index.js")]:[],...process.argv[1]?[process.argv[1]]:[],process.execPath];for(let e of t)try{return require("node:fs").realpathSync(e)}catch{}return process.execPath}var Ho=require("fs"),Go=v(require("path")),tc=v(require("os"));var ec=require("node:fs"),yr=class{cache=new Map;get(e,n){let r=this.cache.get(e);if(r&&r.mtimeMs===n.mtimeMs&&r.size===n.size)return r.value}set(e,n,r){this.cache.set(e,{mtimeMs:n.mtimeMs,size:n.size,value:r})}invalidate(e){this.cache.delete(e)}clear(){this.cache.clear()}prune(e){for(let n of this.cache.keys())e.has(n)||this.cache.delete(n)}prunePrefix(e,n){for(let r of this.cache.keys())r.startsWith(e)&&!n.has(r)&&this.cache.delete(r)}get size(){return this.cache.size}},oe=new yr,Xg=new yr;async function Ce(t){try{let e=await ec.promises.stat(t);return{mtimeMs:e.mtimeMs,size:e.size}}catch{return null}}function at(){return new Promise(t=>setImmediate(t))}var Ku=2e5,Ju="ctx:";async function Yu(t){let e=Go.default.join(tc.default.homedir(),".claude","projects");try{let n=await Ho.promises.readdir(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory())continue;let o=Go.default.join(e,r.name,`${t}.jsonl`);if(await Ce(o))return o}}catch{}}async function zu(t,e){let n=await Ce(t);if(!n)return null;let r=Ju+t,o=oe.get(r,n);if(o!==void 0)return o;await at();try{let s=(await Ho.promises.readFile(t,"utf-8")).trim().split(`
277
277
  `);for(let a=s.length-1;a>=0;a--){let c=s[a]?.trim();if(c)try{let l=JSON.parse(c),d=l.message?.usage??l.usage;if(!d||typeof d!="object")continue;let u=d,p=(u.input_tokens??0)+(u.cache_creation_input_tokens??0)+(u.cache_read_input_tokens??0);if(p===0)continue;let g={usedPct:Math.min(100,Math.round(p/Ku*100)),usedTokens:p};return oe.set(r,n,g),g}catch{continue}}}catch{}return null}function qo(t,e,n){let r,o=-1,i=!0,s=async()=>{if(i)try{if(r||(r=await Yu(e)),!r)return;let l=await zu(r,o);if(!l||l.usedTokens===o)return;o=l.usedTokens,i&&n(t,l.usedPct,l.usedTokens)}catch{}},a=setTimeout(()=>{s()},5e3),c=setInterval(()=>{s()},6e4);return()=>{i=!1,clearTimeout(a),clearInterval(c)}}var _r=v(require("node:fs")),mn=v(require("node:path")),rc=v(require("node:os")),Xu=mn.default.join(rc.default.homedir(),".claude","projects"),Qu=30;function Zu(t){return t.replace(/[\/.]/g,"-")}async function oc(t){let e=Zu(t),n=mn.default.join(Xu,e),r;try{r=await _r.default.promises.readdir(n,{withFileTypes:!0})}catch{return[]}let o=[];for(let a of r)if(!(!a.isFile()||!a.name.endsWith(".jsonl")))try{let c=await _r.default.promises.stat(mn.default.join(n,a.name));o.push({name:a.name,mtimeMs:c.mtimeMs,mtime:c.mtime})}catch{}o.sort((a,c)=>c.mtimeMs-a.mtimeMs);let i=o.slice(0,Qu),s=[];for(let a of i){let c=a.name.replace(/\.jsonl$/,""),l=await ep(mn.default.join(n,a.name));s.push({sessionId:c,cwd:t,title:l??null,lastActivity:a.mtime.toISOString()})}return s}async function ep(t){try{let e=Buffer.alloc(16384),n=await _r.default.promises.open(t,"r");try{let{bytesRead:r}=await n.read(e,0,e.length,0);if(r===0)return null;let i=e.toString("utf-8",0,r).split(`
278
278
  `).slice(0,20);for(let s of i){let a=s.trim();if(a)try{let c=JSON.parse(a),l=tp(c);if(l)return l}catch{}}return null}finally{await n.close()}}catch{return null}}function tp(t){if(t.aiTitle&&typeof t.aiTitle=="string"&&t.aiTitle.trim())return t.aiTitle.trim();if(t.role==="user"&&t.content&&typeof t.content=="string"){let e=t.content.trim();if(e)return Vo(e)}if(t.type==="user"&&t.message&&typeof t.message=="object"&&t.message!==null){let e=t.message;if(e.role==="user"&&"content"in e){let n=nc(e.content);if(n)return n}}if(t.messages&&Array.isArray(t.messages)){for(let e of t.messages)if(e&&typeof e=="object"&&"role"in e&&e.role==="user"&&"content"in e){let n=nc(e.content);if(n)return n}}return null}function nc(t){if(typeof t=="string"){let e=t.trim();return e?Vo(e):null}if(Array.isArray(t)){let e=[];for(let r of t)r&&typeof r=="object"&&"type"in r&&r.type==="text"&&"text"in r&&typeof r.text=="string"&&e.push(r.text);let n=e.join(" ").trim();return n?Vo(n):null}return null}function Vo(t,e=80){return t.length>e?t.slice(0,e)+"\u2026":t}var yn=require("fs"),br=v(require("path")),cc=v(require("os"));ne();var ic=300*60*1e3,Ko={free:10,pro:40,max_5x:200,max_20x:200};function _n(){let t=te();try{let{statSync:e,readFileSync:n}=require("fs");if(!e(t,{throwIfNoEntry:!1}))return"pro";let o=JSON.parse(n(t,"utf-8")).claudeTier;if(typeof o=="string"&&o in Ko)return o}catch{}return"pro"}function np(t){if(!Array.isArray(t))return!1;for(let e of t)if(e&&typeof e=="object"&&e.type==="tool_result")return!0;return!1}var sc="quota:";async function ac(){let t=br.default.join(cc.default.homedir(),".claude","projects"),n=Date.now()-ic,r=1/0,o=0,i=0,s=0,a=!1,c=new Set,l=new Set;try{let u=await yn.promises.readdir(t,{withFileTypes:!0});for(let p of u){if(!p.isDirectory())continue;let f=br.default.join(t,p.name),g;try{g=(await yn.promises.readdir(f,{withFileTypes:!0})).filter(w=>w.isFile()&&w.name.endsWith(".jsonl")).map(w=>w.name)}catch{continue}for(let y of g){let w=br.default.join(f,y),E=await Ce(w);if(!E)continue;await at();let A=sc+w;c.add(A);let R=oe.get(A,E);if(R!==void 0){for(let h of R.events)h.epoch>=n&&(o++,h.epoch<r&&(r=h.epoch));continue}let N;try{if(E.size>20*1024*1024){let b=Math.max(0,E.size-10485760),m=await yn.promises.open(w,"r");try{let _=Buffer.alloc(E.size-b);await m.read(_,0,_.length,b);let C=_.toString("utf-8"),S=C.indexOf(`
279
279
  `);N=S>=0?C.slice(S+1):C}finally{await m.close()}}else N=await yn.promises.readFile(w,"utf-8")}catch{continue}let D=0,L=1/0,O=[];for(let h of N.split(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bridge-agent",
3
- "version": "0.16.0",
3
+ "version": "0.16.4",
4
4
  "description": "Bridge local agent — connects your AI tools to Jerico",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",