@vibelet/cli 1.2.5 → 1.2.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +2 -2
- package/dist/runtime-version.cjs +1 -1
- package/dist/vibelet.mjs +2 -2
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -85,7 +85,7 @@ process.stdin.resume();
|
|
|
85
85
|
`)}function by(t){return Array.isArray(t)?t.map(e=>!e||typeof e!="object"?"":typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:"").filter(Boolean).join(`
|
|
86
86
|
`):""}function wy(t){return Array.isArray(t)&&t.length>0&&t.every(e=>e&&typeof e=="object"&&e.type==="tool_reference")}function Iy(t){if(typeof t=="string")return t;let e=by(t);return e||(wy(t)?"":JSON.stringify(t))}function Ay(t){return/requested permissions|haven't granted/i.test(t)}function Tu(t){return t.replace(Sy,"").replace(/\s+/g," ").trim()}function Ty(t){let e=t.toLowerCase();return e==="error"||e==="failed"||e==="unknown error"}function Cy(t){return/\brate limit\b/i.test(t)||/\busage limit\b/i.test(t)||/\bquota\b/i.test(t)||/\btoo many requests\b/i.test(t)||/\bcredit balance\b/i.test(t)||/\bcredits? remaining\b/i.test(t)||/\bmax(?:imum)? usage\b/i.test(t)}function ky(t){return t.toLowerCase().startsWith("claude ")?t:`Claude usage limit reached. ${t}`}function Cu(t){let e=Tu(t.resultText??""),n=(t.stderrLines??[]).map(Tu).filter(Boolean).slice(-3),s=[e,...n].find(i=>!!i&&Cy(i));if(s)return ky(s);let r=[e,...n].find(i=>!!i&&!Ty(i));return r?t.exitCode!=null&&r!==e?`Claude exited with code ${t.exitCode}: ${r}`:r:t.exitCode!=null?`Claude exited with code ${t.exitCode}`:"Claude returned an error result."}function Ls(t){return t.startsWith(xu)}var kn=class{proc=null;handler=null;sessionId="";buffer="";cwd="";approvalMode;sawFinalResult=!1;interrupted=!1;exitHandler=null;lastStderr=[];pendingPermissionDescriptions=new Map;emittedToolCallIds=new Set;toolCallContext=new Map;replayPhase=!1;hookPort=null;hookSecret=null;hookFiles=null;buildClaudeEnv(){let e=S.buildSanitizedEnv();for(let n of Object.keys(e))n.startsWith("CMUX_")&&delete e[n];return e}async start(e,n,s){return this.cwd=e,this.approvalMode=s,n&&(this.sessionId=n),this.sessionId||(this.sessionId=`pending_${Date.now()}`),ee.info({sessionId:this.sessionId,cwd:e},"session initialized"),_.emit("driver.spawn",{agent:"claude",sessionId:this.sessionId,cwd:e}),this.sessionId}configureHookBridge(e,n){this.hookPort=e,this.hookSecret=n}sendPrompt(e,n){let s=["-p",e,"--output-format","stream-json","--verbose","--include-partial-messages"];n&&s.push("--model",n),this.sessionId&&!this.sessionId.startsWith("pending_")&&s.push("--resume",this.sessionId),Rs(this.hookFiles),this.hookFiles=null,this.approvalMode!=="plan"&&this.approvalMode!=="acceptEdits"&&this.approvalMode!=="autoApprove"&&this.hookPort&&this.hookSecret&&(this.hookFiles=vu(this.hookPort,this.hookSecret),s.push("--settings",this.hookFiles.settingsPath)),this.approvalMode==="plan"&&s.push("--permission-mode","plan"),this.approvalMode==="acceptEdits"&&s.push("--permission-mode","acceptEdits"),this.approvalMode==="autoApprove"&&s.push("--dangerously-skip-permissions");let r=this.sessionId.startsWith("pending_")?"(new)":`(resume ${this.sessionId.slice(0,8)})`;ee.info({sessionId:this.sessionId,label:r,promptPreview:e.slice(0,50)},"running claude"),Fi(`New message: ${e.slice(0,60)}`),this.sawFinalResult=!1,this.interrupted=!1,this.lastStderr=[],this.pendingPermissionDescriptions.clear(),this.emittedToolCallIds.clear(),this.toolCallContext.clear(),this.replayPhase=!0;let i=S.claudePath,o,a=s;if(S.isTransientPath(i)||i==="claude"){let c=S.execViaLoginShell("claude",s);o=c.command,a=c.args}else o=i;this.proc=(0,ku.spawn)(o,a,{cwd:this.cwd||void 0,stdio:["ignore","pipe","pipe"],env:this.buildClaudeEnv(),...process.platform==="win32"?{shell:!0,windowsHide:!0}:{}});let u=this.proc;u.on("error",c=>{if(this.proc!==u)return;let d=c.message;c.code==="ENOENT"&&this.cwd&&!(0,Ms.existsSync)(this.cwd)&&(d=`Working directory does not exist: ${this.cwd}`),ee.error({sessionId:this.sessionId,error:d,cwd:this.cwd},"spawn error"),_.emit("driver.error",{agent:"claude",sessionId:this.sessionId,error:d}),this.handler?.({type:"error",sessionId:this.sessionId,message:d})}),this.buffer="",u.stdout.on("data",c=>{if(this.proc!==u)return;this.buffer+=c.toString();let d=this.buffer.split(`
|
|
87
87
|
`);this.buffer=d.pop();for(let f of d)if(f.trim())try{this.handleRaw(JSON.parse(f))}catch{ee.warn({sessionId:this.sessionId,linePreview:f.slice(0,100)},"failed to parse stdout line")}}),u.stderr.on("data",c=>{if(this.proc!==u)return;let d=c.toString().trim();d&&(ee.debug({sessionId:this.sessionId,stderr:d},"stderr"),this.lastStderr.push(d),this.lastStderr.length>10&&this.lastStderr.shift())}),u.on("exit",(c,d)=>{if(this.proc!==u){ee.debug({sessionId:this.sessionId,exitCode:c,signal:d},"stale proc exit ignored, current proc was replaced");return}ee.info({sessionId:this.sessionId,exitCode:c,signal:d},"process exited");let f=this.interrupted;this.proc=null,Rs(this.hookFiles),this.hookFiles=null,this.interrupted=!1,this.toolCallContext.clear(),f&&!this.sawFinalResult?this.handler?.({type:"session.interrupted",sessionId:this.sessionId}):c&&c!==0&&!this.sawFinalResult&&(ee.error({sessionId:this.sessionId,exitCode:c,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.handler?.({type:"error",sessionId:this.sessionId,message:Cu({stderrLines:this.lastStderr,exitCode:c})})),this.exitHandler?.(c)})}respondApproval(e,n){if(ee.info({sessionId:this.sessionId,requestId:e,approved:n},"approval response"),!this.proc?.stdin?.writable)return ee.error({sessionId:this.sessionId},"cannot send approval: stdin not writable"),!1;let s=JSON.stringify({type:"control_response",request_id:e,permission_granted:n});return this.proc.stdin.write(s+`
|
|
88
|
-
`),!0}getRespondingLivenessHint(){return!this.proc||this.proc.exitCode!==null||this.proc.signalCode!==null||this.proc.killed?"dead":"alive"}setApprovalMode(e){this.approvalMode=e,ee.info({sessionId:this.sessionId,approvalMode:e},"approval mode updated")}interrupt(){this.proc&&!this.proc.killed&&(this.interrupted=!0,this.proc.kill("SIGTERM"),ee.info({sessionId:this.sessionId},"interrupted"))}stop(){if(!this.proc)return;this.proc.kill("SIGTERM");let e=this.proc;setTimeout(()=>{e.killed||e.kill("SIGKILL")},5e3).unref(),this.proc=null,Rs(this.hookFiles),this.hookFiles=null,this.toolCallContext.clear()}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}handleRaw(e){let n=e.type;if(n==="system"&&e.subtype==="init"){let s=e.session_id??"";s&&s!==this.sessionId&&(ee.info({oldSessionId:this.sessionId,newSessionId:s},"session ID resolved"),_.emit("driver.init",{agent:"claude",sessionId:s}),this.sessionId=s);return}if(this.handler)switch(n){case"assistant":{if(this.replayPhase)break;let s=e.message?.content;if(!Array.isArray(s))break;for(let r of s)if(r.type==="tool_use"&&!this.emittedToolCallIds.has(r.id)){this.emittedToolCallIds.add(r.id);let i=r.input??{},o=Es(r.name,i,this.cwd);this.toolCallContext.set(r.id,{toolName:r.name,...o?{generatedFilePath:o,fileExistedAtStart:(0,Ms.existsSync)(o)}:{}}),this.handler({type:"tool.call",sessionId:this.sessionId,toolName:r.name,input:i,toolCallId:r.id})}break}case"user":{if(this.replayPhase)break;let s=e.message?.content;if(!Array.isArray(s))break;for(let r of s)if(r.type==="tool_result"){let i=typeof r.tool_use_id=="string"?r.tool_use_id:"",o=i?this.toolCallContext.get(i):void 0,a=Iy(r.content);if(!r.is_error&&o?.generatedFilePath&&o.fileExistedAtStart===!1&&(0,Ms.existsSync)(o.generatedFilePath)){let l=Ae([o.generatedFilePath]);l&&this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:i,output:l})}else if(!r.is_error&&o?.generatedFilePath&&o.fileExistedAtStart==null&&Ps(e.toolUseResult,a)){let l=Ae([o.generatedFilePath]);l&&this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:i,output:l})}if(!a){i&&this.toolCallContext.delete(i);continue}if(r.is_error===!0&&i&&Ay(a)){this.pendingPermissionDescriptions.set(i,a);continue}this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:i,output:a}),i&&this.toolCallContext.delete(i)}break}case"control_request":{this.replayPhase=!1;let s=e.request;s?.subtype==="can_use_tool"&&(_.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:s.tool_name}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:e.request_id,toolName:s.tool_name??"unknown",input:s.input??{},description:s.description??s.title??""}));break}case"stream_event":{this.replayPhase=!1;let s=e.event;s?.type==="content_block_delta"&&s?.delta?.type==="text_delta"&&s?.delta?.text&&this.handler({type:"text.delta",sessionId:this.sessionId,content:s.delta.text});break}case"result":{this.replayPhase=!1,this.sawFinalResult=!0;let s=typeof e.result=="string"?e.result:"";if(e.is_error){Fi("Claude failed."),this.handler({type:"error",sessionId:this.sessionId,message:Cu({resultText:s,stderrLines:this.lastStderr})});break}let r=Array.isArray(e.permission_denials)?e.permission_denials:[];if(r.length>0){let a=r[0]??{},l=typeof a.tool_use_id=="string"?a.tool_use_id:`missing_${Date.now()}`,u=typeof a.tool_name=="string"?a.tool_name:"unknown",c=a.tool_input&&typeof a.tool_input=="object"?a.tool_input:{},d=this.pendingPermissionDescriptions.get(l)??`Claude requested permissions to use ${u}.`;_.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:u}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:`${xu}${l}`,toolName:u,input:c,description:d})}this.pendingPermissionDescriptions.clear();let i=e.total_cost_usd,o=e.usage?{inputTokens:e.usage.input_tokens,outputTokens:e.usage.output_tokens,...Number.isFinite(e.usage.cache_creation_input_tokens)?{cacheCreationInputTokens:e.usage.cache_creation_input_tokens}:{},...Number.isFinite(e.usage.cache_read_input_tokens)?{cacheReadInputTokens:e.usage.cache_read_input_tokens}:{}}:void 0;Fi("Claude finished. Run `claude --continue` to continue on desktop."),_.emit("session.done",{agent:"claude",sessionId:this.sessionId,cost:i,usage:o}),this.handler({type:"session.done",sessionId:this.sessionId,cost:i,usage:o});break}}}};var Mu=require("child_process"),Lu=require("fs");var Ui=class{counters=new Map;timers=new Map;gauges=new Map;startTime=Date.now();logInterval=null;increment(e,n={}){this.counters.has(e)||this.counters.set(e,[]);let s=this.counters.get(e),r=JSON.stringify(n),i=s.find(o=>JSON.stringify(o.labels)===r);i?i.value++:s.push({value:1,labels:n})}gauge(e,n){this.gauges.set(e,n)}startTimer(e){let n=performance.now();return()=>{let s=Math.round(performance.now()-n),r=this.timers.get(e)??{count:0,totalMs:0,minMs:1/0,maxMs:0,lastMs:0};return r.count++,r.totalMs+=s,r.minMs=Math.min(r.minMs,s),r.maxMs=Math.max(r.maxMs,s),r.lastMs=s,this.timers.set(e,r),s}}snapshot(){let e={};for(let[r,i]of this.counters)e[r]=i.map(o=>({...o}));let n={};for(let[r,i]of this.timers)n[r]={...i,minMs:i.minMs===1/0?0:i.minMs};let s={};for(let[r,i]of this.gauges)s[r]=i;return{uptimeMs:Date.now()-this.startTime,counters:e,timers:n,gauges:s}}startPeriodicLog(e=6e4){this.logInterval||(this.logInterval=setInterval(()=>{let n=this.snapshot();L.info({metrics:n},"periodic metrics snapshot")},e),this.logInterval.unref())}stopPeriodicLog(){this.logInterval&&(clearInterval(this.logInterval),this.logInterval=null)}},b=new Ui;var Ru=require("node:fs"),Hi=require("node:path"),xy="@vibelet/cli";function Ry(t){try{let e=JSON.parse((0,Ru.readFileSync)(t,"utf8"));if(e.name===xy&&typeof e.version=="string"&&e.version.length>0)return e.version}catch{}return null}function Ey(){return"1.2.5"}var Lt=Ey();var x=L.child({module:"codex"});function Py(t){switch(t.kind){case"request-user-input-approval":return{provider:"codex",kind:t.kind,rpcId:t.rpcId,questionId:t.questionId,approveLabel:t.approveLabel,denyLabel:t.denyLabel};default:return{provider:"codex",kind:t.kind,rpcId:t.rpcId}}}function My(t){let e=t.approvalContext;if(!e||e.provider!=="codex")return null;switch(e.kind){case"command-execution":return{kind:e.kind,responseKind:"v2",rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"file-change":return{kind:e.kind,responseKind:"v2",rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"request-user-input-approval":return!e.questionId||!e.approveLabel||!e.denyLabel?null:{kind:e.kind,rpcId:e.rpcId,questionId:e.questionId,approveLabel:e.approveLabel,denyLabel:e.denyLabel,toolName:t.toolName,input:t.input};case"exec-command-legacy":return{kind:e.kind,rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"apply-patch-legacy":return{kind:e.kind,rpcId:e.rpcId,toolName:t.toolName,input:t.input};default:return null}}function F(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function M(t){return typeof t=="string"&&t.trim().length>0?t.trim():null}function Wi(t){let e=Number(t);return!Number.isFinite(e)||e<=0?null:Math.trunc(e)}var Ly=new Set(["aborted","interrupted","cancelled","canceled","failed"]);function Ny(t){let e=M(t);return e?e.toLowerCase():null}function Oy(t){try{let e=JSON.parse(t),n=F(F(e)?.error)?.message;if(typeof n=="string"&&n.trim())return n}catch{}return t}function Dy(t){let e=M(t);return e?e.replace(/[^a-z0-9]/gi,"").toLowerCase():null}function qi(t){return t?M(t.itemId)??M(t.id)??M(t.callId)??M(t.call_id):null}function Gi(t,e){let n={};for(let[s,r]of Object.entries(t))e.includes(s)||(n[s]=r);return n}function Nu(t){return/\bapprove\b|\ballow\b|\baccept\b|\byes\b|\bcontinue\b|\bproceed\b|\brun\b|\bapply\b/i.test(t)}function Ou(t){return/\bdeny\b|\breject\b|\bdecline\b|\bno\b|\bcancel\b|\babort\b|\bstop\b/i.test(t)}function By(t){if(!Array.isArray(t))return null;for(let e of t){let n=F(e);if(!n)continue;let s=M(n.id),r=Array.isArray(n.options)?n.options.map(l=>F(l)).filter(l=>!!l):[];if(!s||r.length===0)continue;let i=r.map(l=>M(l.label)).filter(l=>!!l);if(i.length<2)continue;let o=i.find(l=>Nu(l))??i[0],a=i.find(l=>Ou(l))??i[i.length-1];if(!(!o||!a||o===a))return{questionId:s,approveLabel:o,denyLabel:a}}return null}function Fy(t){if(!Array.isArray(t)||t.length===0)return!1;let e=t.map(r=>F(r)).filter(r=>!!r).flatMap(r=>(Array.isArray(r.options)?r.options:[]).map(o=>F(o)).filter(o=>!!o).map(o=>M(o.label)).filter(o=>!!o)),n=e.some(r=>Nu(r)),s=e.some(r=>Ou(r));return n&&s}function Eu(t){let e=Dy(t.type??t.itemType);if(e==="commandexecution")return{toolName:"Bash",input:Gi(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="filechange")return{toolName:"Patch",input:Gi(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="mcptoolcall"){let n=M(t.server),s=M(t.tool)??M(t.name);return s?{toolName:n?`mcp__${n}__${s}`:s,input:F(t.arguments)??F(t.input)??{}}:null}return null}function Uy(t,e){let n=M(t.path);if(!n||!(Array.isArray(t.changes)?t.changes:[]).some(o=>F(o)?.kind==="create"))return null;let i=st(n,e);return Mt(i)?i:null}function Hy(t){if(!Array.isArray(t))return"";for(let e of t){let n=F(e);if(!n)continue;let s=M(n.question)??M(n.header);if(s)return s}return""}function Wy(t){let e=F(t);if(!e)return;let n=Wi(e.input_tokens??e.inputTokens)??0,s=Wi(e.output_tokens??e.outputTokens)??0,r=Wi(e.modelContextWindow??e.model_context_window??e.contextWindowTokens);if(!(n<=0&&s<=0&&!r))return{inputTokens:n,outputTokens:s,...r?{contextWindowTokens:r}:{}}}function Pu(t,e){return t==="autoApprove"?{approvalPolicy:"never",sandbox:"danger-full-access",sandboxPolicy:{type:"dangerFullAccess"}}:t==="plan"?{approvalPolicy:"on-request",sandbox:"workspace-write",sandboxPolicy:{type:"workspaceWrite",writableRoots:[],readOnlyAccess:{type:"fullAccess"},networkAccess:!0,excludeTmpdirEnvVar:!1,excludeSlashTmp:!1}}:{approvalPolicy:"on-request",sandbox:"workspace-write",sandboxPolicy:{type:"workspaceWrite",writableRoots:[e],readOnlyAccess:{type:"fullAccess"},networkAccess:!0,excludeTmpdirEnvVar:!1,excludeSlashTmp:!1}}}var xn=class{proc=null;handler=null;exitHandler=null;buffer="";rpcId=0;pending=new Map;threadId="";lastStderr=[];approvalRequests=new Map;toolContextByCallId=new Map;turnStartInFlight=!1;interruptRequestedDuringTurnStart=!1;latestTurnUsage;approvalMode;cwd="";model;async start(e,n,s){this.approvalMode=s,this.cwd=e,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,this.latestTurnUsage=void 0;let r=S.codexPath,i,o=this.buildSpawnArgs();if(S.isTransientPath(r)||r==="codex"){let c=S.execViaLoginShell("codex",o);i=c.command,o=c.args,x.info({spawnCmd:i,argsPreview:o.slice(0,2)},"spawning via login shell")}else i=r,x.info({spawnCmd:i,args:o},"spawning");_.emit("driver.spawn",{agent:"codex",cwd:e,resumeSessionId:n}),this.lastStderr=[],this.proc=(0,Mu.spawn)(i,o,{cwd:e||void 0,stdio:["pipe","pipe","pipe"],env:S.buildSanitizedEnv(),...process.platform==="win32"?{shell:!0,windowsHide:!0}:{}}),this.proc.on("error",c=>{let d=c.message;c.code==="ENOENT"&&e&&!(0,Lu.existsSync)(e)&&(d=`Working directory does not exist: ${e}`),x.error({error:d,cwd:e},"spawn error"),_.emit("driver.error",{agent:"codex",error:d})}),this.proc.stdout.on("data",c=>{this.buffer+=c.toString();let d=this.buffer.split(`
|
|
88
|
+
`),!0}getRespondingLivenessHint(){return!this.proc||this.proc.exitCode!==null||this.proc.signalCode!==null||this.proc.killed?"dead":"alive"}setApprovalMode(e){this.approvalMode=e,ee.info({sessionId:this.sessionId,approvalMode:e},"approval mode updated")}interrupt(){this.proc&&!this.proc.killed&&(this.interrupted=!0,this.proc.kill("SIGTERM"),ee.info({sessionId:this.sessionId},"interrupted"))}stop(){if(!this.proc)return;this.proc.kill("SIGTERM");let e=this.proc;setTimeout(()=>{e.killed||e.kill("SIGKILL")},5e3).unref(),this.proc=null,Rs(this.hookFiles),this.hookFiles=null,this.toolCallContext.clear()}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}handleRaw(e){let n=e.type;if(n==="system"&&e.subtype==="init"){let s=e.session_id??"";s&&s!==this.sessionId&&(ee.info({oldSessionId:this.sessionId,newSessionId:s},"session ID resolved"),_.emit("driver.init",{agent:"claude",sessionId:s}),this.sessionId=s);return}if(this.handler)switch(n){case"assistant":{if(this.replayPhase)break;let s=e.message?.content;if(!Array.isArray(s))break;for(let r of s)if(r.type==="tool_use"&&!this.emittedToolCallIds.has(r.id)){this.emittedToolCallIds.add(r.id);let i=r.input??{},o=Es(r.name,i,this.cwd);this.toolCallContext.set(r.id,{toolName:r.name,...o?{generatedFilePath:o,fileExistedAtStart:(0,Ms.existsSync)(o)}:{}}),this.handler({type:"tool.call",sessionId:this.sessionId,toolName:r.name,input:i,toolCallId:r.id})}break}case"user":{if(this.replayPhase)break;let s=e.message?.content;if(!Array.isArray(s))break;for(let r of s)if(r.type==="tool_result"){let i=typeof r.tool_use_id=="string"?r.tool_use_id:"",o=i?this.toolCallContext.get(i):void 0,a=Iy(r.content);if(!r.is_error&&o?.generatedFilePath&&o.fileExistedAtStart===!1&&(0,Ms.existsSync)(o.generatedFilePath)){let l=Ae([o.generatedFilePath]);l&&this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:i,output:l})}else if(!r.is_error&&o?.generatedFilePath&&o.fileExistedAtStart==null&&Ps(e.toolUseResult,a)){let l=Ae([o.generatedFilePath]);l&&this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:i,output:l})}if(!a){i&&this.toolCallContext.delete(i);continue}if(r.is_error===!0&&i&&Ay(a)){this.pendingPermissionDescriptions.set(i,a);continue}this.handler({type:"tool.result",sessionId:this.sessionId,toolCallId:i,output:a}),i&&this.toolCallContext.delete(i)}break}case"control_request":{this.replayPhase=!1;let s=e.request;s?.subtype==="can_use_tool"&&(_.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:s.tool_name}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:e.request_id,toolName:s.tool_name??"unknown",input:s.input??{},description:s.description??s.title??""}));break}case"stream_event":{this.replayPhase=!1;let s=e.event;s?.type==="content_block_delta"&&s?.delta?.type==="text_delta"&&s?.delta?.text&&this.handler({type:"text.delta",sessionId:this.sessionId,content:s.delta.text});break}case"result":{this.replayPhase=!1,this.sawFinalResult=!0;let s=typeof e.result=="string"?e.result:"";if(e.is_error){Fi("Claude failed."),this.handler({type:"error",sessionId:this.sessionId,message:Cu({resultText:s,stderrLines:this.lastStderr})});break}let r=Array.isArray(e.permission_denials)?e.permission_denials:[];if(r.length>0){let a=r[0]??{},l=typeof a.tool_use_id=="string"?a.tool_use_id:`missing_${Date.now()}`,u=typeof a.tool_name=="string"?a.tool_name:"unknown",c=a.tool_input&&typeof a.tool_input=="object"?a.tool_input:{},d=this.pendingPermissionDescriptions.get(l)??`Claude requested permissions to use ${u}.`;_.emit("approval.request",{agent:"claude",sessionId:this.sessionId,toolName:u}),this.handler({type:"approval.request",sessionId:this.sessionId,requestId:`${xu}${l}`,toolName:u,input:c,description:d})}this.pendingPermissionDescriptions.clear();let i=e.total_cost_usd,o=e.usage?{inputTokens:e.usage.input_tokens,outputTokens:e.usage.output_tokens,...Number.isFinite(e.usage.cache_creation_input_tokens)?{cacheCreationInputTokens:e.usage.cache_creation_input_tokens}:{},...Number.isFinite(e.usage.cache_read_input_tokens)?{cacheReadInputTokens:e.usage.cache_read_input_tokens}:{}}:void 0;Fi("Claude finished. Run `claude --continue` to continue on desktop."),_.emit("session.done",{agent:"claude",sessionId:this.sessionId,cost:i,usage:o}),this.handler({type:"session.done",sessionId:this.sessionId,cost:i,usage:o});break}}}};var Mu=require("child_process"),Lu=require("fs");var Ui=class{counters=new Map;timers=new Map;gauges=new Map;startTime=Date.now();logInterval=null;increment(e,n={}){this.counters.has(e)||this.counters.set(e,[]);let s=this.counters.get(e),r=JSON.stringify(n),i=s.find(o=>JSON.stringify(o.labels)===r);i?i.value++:s.push({value:1,labels:n})}gauge(e,n){this.gauges.set(e,n)}startTimer(e){let n=performance.now();return()=>{let s=Math.round(performance.now()-n),r=this.timers.get(e)??{count:0,totalMs:0,minMs:1/0,maxMs:0,lastMs:0};return r.count++,r.totalMs+=s,r.minMs=Math.min(r.minMs,s),r.maxMs=Math.max(r.maxMs,s),r.lastMs=s,this.timers.set(e,r),s}}snapshot(){let e={};for(let[r,i]of this.counters)e[r]=i.map(o=>({...o}));let n={};for(let[r,i]of this.timers)n[r]={...i,minMs:i.minMs===1/0?0:i.minMs};let s={};for(let[r,i]of this.gauges)s[r]=i;return{uptimeMs:Date.now()-this.startTime,counters:e,timers:n,gauges:s}}startPeriodicLog(e=6e4){this.logInterval||(this.logInterval=setInterval(()=>{let n=this.snapshot();L.info({metrics:n},"periodic metrics snapshot")},e),this.logInterval.unref())}stopPeriodicLog(){this.logInterval&&(clearInterval(this.logInterval),this.logInterval=null)}},b=new Ui;var Ru=require("node:fs"),Hi=require("node:path"),xy="@vibelet/cli";function Ry(t){try{let e=JSON.parse((0,Ru.readFileSync)(t,"utf8"));if(e.name===xy&&typeof e.version=="string"&&e.version.length>0)return e.version}catch{}return null}function Ey(){return"1.2.7"}var Lt=Ey();var x=L.child({module:"codex"});function Py(t){switch(t.kind){case"request-user-input-approval":return{provider:"codex",kind:t.kind,rpcId:t.rpcId,questionId:t.questionId,approveLabel:t.approveLabel,denyLabel:t.denyLabel};default:return{provider:"codex",kind:t.kind,rpcId:t.rpcId}}}function My(t){let e=t.approvalContext;if(!e||e.provider!=="codex")return null;switch(e.kind){case"command-execution":return{kind:e.kind,responseKind:"v2",rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"file-change":return{kind:e.kind,responseKind:"v2",rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"request-user-input-approval":return!e.questionId||!e.approveLabel||!e.denyLabel?null:{kind:e.kind,rpcId:e.rpcId,questionId:e.questionId,approveLabel:e.approveLabel,denyLabel:e.denyLabel,toolName:t.toolName,input:t.input};case"exec-command-legacy":return{kind:e.kind,rpcId:e.rpcId,toolName:t.toolName,input:t.input};case"apply-patch-legacy":return{kind:e.kind,rpcId:e.rpcId,toolName:t.toolName,input:t.input};default:return null}}function F(t){return!t||typeof t!="object"||Array.isArray(t)?null:t}function M(t){return typeof t=="string"&&t.trim().length>0?t.trim():null}function Wi(t){let e=Number(t);return!Number.isFinite(e)||e<=0?null:Math.trunc(e)}var Ly=new Set(["aborted","interrupted","cancelled","canceled","failed"]);function Ny(t){let e=M(t);return e?e.toLowerCase():null}function Oy(t){try{let e=JSON.parse(t),n=F(F(e)?.error)?.message;if(typeof n=="string"&&n.trim())return n}catch{}return t}function Dy(t){let e=M(t);return e?e.replace(/[^a-z0-9]/gi,"").toLowerCase():null}function qi(t){return t?M(t.itemId)??M(t.id)??M(t.callId)??M(t.call_id):null}function Gi(t,e){let n={};for(let[s,r]of Object.entries(t))e.includes(s)||(n[s]=r);return n}function Nu(t){return/\bapprove\b|\ballow\b|\baccept\b|\byes\b|\bcontinue\b|\bproceed\b|\brun\b|\bapply\b/i.test(t)}function Ou(t){return/\bdeny\b|\breject\b|\bdecline\b|\bno\b|\bcancel\b|\babort\b|\bstop\b/i.test(t)}function By(t){if(!Array.isArray(t))return null;for(let e of t){let n=F(e);if(!n)continue;let s=M(n.id),r=Array.isArray(n.options)?n.options.map(l=>F(l)).filter(l=>!!l):[];if(!s||r.length===0)continue;let i=r.map(l=>M(l.label)).filter(l=>!!l);if(i.length<2)continue;let o=i.find(l=>Nu(l))??i[0],a=i.find(l=>Ou(l))??i[i.length-1];if(!(!o||!a||o===a))return{questionId:s,approveLabel:o,denyLabel:a}}return null}function Fy(t){if(!Array.isArray(t)||t.length===0)return!1;let e=t.map(r=>F(r)).filter(r=>!!r).flatMap(r=>(Array.isArray(r.options)?r.options:[]).map(o=>F(o)).filter(o=>!!o).map(o=>M(o.label)).filter(o=>!!o)),n=e.some(r=>Nu(r)),s=e.some(r=>Ou(r));return n&&s}function Eu(t){let e=Dy(t.type??t.itemType);if(e==="commandexecution")return{toolName:"Bash",input:Gi(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="filechange")return{toolName:"Patch",input:Gi(t,["id","itemId","type","itemType","stdout","stderr","exitCode","exit_code","status","success","error"])};if(e==="mcptoolcall"){let n=M(t.server),s=M(t.tool)??M(t.name);return s?{toolName:n?`mcp__${n}__${s}`:s,input:F(t.arguments)??F(t.input)??{}}:null}return null}function Uy(t,e){let n=M(t.path);if(!n||!(Array.isArray(t.changes)?t.changes:[]).some(o=>F(o)?.kind==="create"))return null;let i=st(n,e);return Mt(i)?i:null}function Hy(t){if(!Array.isArray(t))return"";for(let e of t){let n=F(e);if(!n)continue;let s=M(n.question)??M(n.header);if(s)return s}return""}function Wy(t){let e=F(t);if(!e)return;let n=Wi(e.input_tokens??e.inputTokens)??0,s=Wi(e.output_tokens??e.outputTokens)??0,r=Wi(e.modelContextWindow??e.model_context_window??e.contextWindowTokens);if(!(n<=0&&s<=0&&!r))return{inputTokens:n,outputTokens:s,...r?{contextWindowTokens:r}:{}}}function Pu(t,e){return t==="autoApprove"?{approvalPolicy:"never",sandbox:"danger-full-access",sandboxPolicy:{type:"dangerFullAccess"}}:t==="plan"?{approvalPolicy:"on-request",sandbox:"workspace-write",sandboxPolicy:{type:"workspaceWrite",writableRoots:[],readOnlyAccess:{type:"fullAccess"},networkAccess:!0,excludeTmpdirEnvVar:!1,excludeSlashTmp:!1}}:{approvalPolicy:"on-request",sandbox:"workspace-write",sandboxPolicy:{type:"workspaceWrite",writableRoots:[e],readOnlyAccess:{type:"fullAccess"},networkAccess:!0,excludeTmpdirEnvVar:!1,excludeSlashTmp:!1}}}var xn=class{proc=null;handler=null;exitHandler=null;buffer="";rpcId=0;pending=new Map;threadId="";lastStderr=[];approvalRequests=new Map;toolContextByCallId=new Map;turnStartInFlight=!1;interruptRequestedDuringTurnStart=!1;latestTurnUsage;approvalMode;cwd="";model;async start(e,n,s){this.approvalMode=s,this.cwd=e,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,this.latestTurnUsage=void 0;let r=S.codexPath,i,o=this.buildSpawnArgs();if(S.isTransientPath(r)||r==="codex"){let c=S.execViaLoginShell("codex",o);i=c.command,o=c.args,x.info({spawnCmd:i,argsPreview:o.slice(0,2)},"spawning via login shell")}else i=r,x.info({spawnCmd:i,args:o},"spawning");_.emit("driver.spawn",{agent:"codex",cwd:e,resumeSessionId:n}),this.lastStderr=[],this.proc=(0,Mu.spawn)(i,o,{cwd:e||void 0,stdio:["pipe","pipe","pipe"],env:S.buildSanitizedEnv(),...process.platform==="win32"?{shell:!0,windowsHide:!0}:{}}),this.proc.on("error",c=>{let d=c.message;c.code==="ENOENT"&&e&&!(0,Lu.existsSync)(e)&&(d=`Working directory does not exist: ${e}`),x.error({error:d,cwd:e},"spawn error"),_.emit("driver.error",{agent:"codex",error:d})}),this.proc.stdout.on("data",c=>{this.buffer+=c.toString();let d=this.buffer.split(`
|
|
89
89
|
`);this.buffer=d.pop();for(let f of d)if(f.trim())try{this.handleRaw(JSON.parse(f))}catch{x.warn({linePreview:f.slice(0,200)},"failed to parse stdout line")}}),this.proc.stderr.on("data",c=>{let d=c.toString().trim();d&&(x.debug({stderr:d},"stderr"),this.lastStderr.push(d),this.lastStderr.length>10&&this.lastStderr.shift())}),this.proc.on("exit",c=>{x.info({threadId:this.threadId,exitCode:c},"process exited"),c&&c!==0&&x.error({threadId:this.threadId,exitCode:c,lastStderr:this.lastStderr.slice(-3)},"abnormal exit"),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1;for(let[,{reject:d}]of this.pending)d(new Error(`Codex process exited with code ${c}`));this.pending.clear(),this.exitHandler?.(c),c&&this.handler&&this.threadId&&this.handler({type:"error",sessionId:this.threadId,message:`Codex process exited with code ${c}`})});let l=b.startTimer("rpc.duration");await this.rpc("initialize",{clientInfo:{name:"@vibelet/cli",version:Lt},capabilities:{experimentalApi:!0}}),l(),this.rpcNotify("initialized",{});let u=Pu(this.approvalMode,e);if(n){let c=await this.rpc("thread/resume",{threadId:n,approvalPolicy:u.approvalPolicy,sandbox:u.sandbox,persistExtendedHistory:!0});this.threadId=c?.thread?.id??n,x.info({threadId:this.threadId},"thread resumed"),_.emit("driver.init",{agent:"codex",sessionId:this.threadId})}else{let c=await this.rpc("thread/start",{cwd:e,approvalPolicy:u.approvalPolicy,sandbox:u.sandbox,experimentalRawEvents:!0,persistExtendedHistory:!0});this.threadId=c?.thread?.id??c?.threadId??"",x.info({threadId:this.threadId},"thread created"),_.emit("driver.init",{agent:"codex",sessionId:this.threadId})}return this.threadId}setModel(e){this.model=e}buildSpawnArgs(){let e=["app-server","--listen","stdio://"];return this.model&&e.push("-m",this.model),e}sendPrompt(e,n){let s=Pu(this.approvalMode,this.cwd||process.cwd());this.latestTurnUsage=void 0,this.turnStartInFlight=!0,this.interruptRequestedDuringTurnStart=!1,x.info({threadId:this.threadId,promptPreview:e.slice(0,50)},"turn/start"),this.rpc("turn/start",{threadId:this.threadId,input:[{type:"text",text:e}],approvalPolicy:s.approvalPolicy,sandboxPolicy:s.sandboxPolicy,...n?{model:n}:{}}).then(r=>{x.debug({resultPreview:JSON.stringify(r).slice(0,200)},"turn/start result"),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart&&(this.interruptRequestedDuringTurnStart=!1,this.requestTurnInterrupt())}).catch(r=>{this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,x.error({threadId:this.threadId,error:r.message},"sendPrompt error"),this.handler?.({type:"error",sessionId:this.threadId,message:r.message})})}respondApproval(e,n){if(!this.proc?.stdin?.writable)return!1;let s=this.approvalRequests.get(e),r=s?.rpcId??Number(e);if(!Number.isFinite(r))return!1;let i;if(!s)i=n?{decision:"approve"}:{decision:"deny",reason:"User denied from Vibelet"};else{switch(s.kind){case"command-execution":case"file-change":i={decision:n?"accept":"decline"};break;case"request-user-input-approval":i={answers:{[s.questionId]:{answers:[n?s.approveLabel:s.denyLabel]}}};break;case"exec-command-legacy":case"apply-patch-legacy":i={decision:n?"approved":"denied"};break;default:i={decision:n?"accept":"decline"};break}this.approvalRequests.delete(e)}return x.info({threadId:this.threadId,rpcId:r,approved:n},"approval response"),this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",id:r,result:i})+`
|
|
90
90
|
`),!0}restorePendingApproval(e){let n=My(e);n&&this.approvalRequests.set(e.requestId,n)}getRespondingLivenessHint(){return!this.proc||this.proc.exitCode!==null||this.proc.signalCode!==null||this.proc.killed?"dead":"alive"}interrupt(){this.turnStartInFlight&&(this.interruptRequestedDuringTurnStart=!0),this.requestTurnInterrupt()}setApprovalMode(e){this.approvalMode=e,x.info({approvalMode:e},"approval mode updated (takes effect on subsequent turns)")}stop(){if(!this.proc)return;this.proc.kill("SIGTERM");let e=this.proc;setTimeout(()=>{e.killed||e.kill("SIGKILL")},5e3).unref(),this.proc=null,this.approvalRequests.clear(),this.toolContextByCallId.clear(),this.turnStartInFlight=!1,this.interruptRequestedDuringTurnStart=!1,this.latestTurnUsage=void 0;for(let[,{reject:n}]of this.pending)n(new Error("Process stopped"));this.pending.clear()}onMessage(e){this.handler=e}onExit(e){this.exitHandler=e}rpc(e,n){let s=++this.rpcId,r=b.startTimer("rpc.duration");return new Promise((i,o)=>{if(this.pending.set(s,{resolve:a=>{r(),i(a)},reject:a=>{r(),o(a)}}),!this.proc?.stdin?.writable){this.pending.delete(s),r(),o(new Error("Process not available"));return}this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,id:s,params:n})+`
|
|
91
91
|
`),setTimeout(()=>{this.pending.has(s)&&(this.pending.delete(s),x.error({method:e,rpcId:s,threadId:this.threadId},"RPC timeout"),r(),o(new Error(`RPC timeout: ${e}`)))},3e4).unref()})}requestTurnInterrupt(){this.rpc("turn/interrupt",{threadId:this.threadId}).catch(()=>{})}rpcNotify(e,n){this.proc?.stdin?.writable&&this.proc.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,params:n})+`
|
|
@@ -114,7 +114,7 @@ ${n}`:n:t}function qt(t){return t.map(e=>({...e.clientMessageId?{clientMessageId
|
|
|
114
114
|
`).map(n=>Number(n.trim())).filter(n=>Number.isFinite(n)&&n>0);return[...new Set(e)]}function gf(t,e=B_){let n;try{n=F_(e("lsof",["-ti",`tcp:${t}`]))}catch{return[]}return n.map(s=>{try{let r=e("ps",["-p",String(s),"-o","command="]);return r?{pid:s,command:r}:{pid:s}}catch{return{pid:s}}})}var $t=require("fs"),ko=require("os"),yf=require("crypto"),vf=require("path");function Sf(t){return(0,yf.randomBytes)(t).toString("base64url")}function U_(){return`d_${Sf(12)}`}function H_(){return(0,ko.hostname)()}function W_(){let t=(0,ko.hostname)().trim().toLowerCase();return t?t.endsWith(".local")?t:`${t}.local`:"localhost"}function q_(t){return{daemonId:U_(),daemonSecret:Sf(32),displayName:H_(),canonicalHost:W_(),port:t,createdAt:new Date().toISOString()}}function mf(t,e){(0,$t.mkdirSync)((0,vf.dirname)(e),{recursive:!0}),(0,$t.writeFileSync)(e,JSON.stringify(t,null,2)+`
|
|
115
115
|
`,"utf8")}function _f(t,e=Zc){try{let s=(0,$t.readFileSync)(e,"utf8"),r=JSON.parse(s);if(typeof r.daemonId=="string"&&typeof r.daemonSecret=="string"&&typeof r.displayName=="string"&&typeof r.canonicalHost=="string"&&typeof r.createdAt=="string"){let i={daemonId:r.daemonId,daemonSecret:r.daemonSecret,displayName:r.displayName,canonicalHost:r.canonicalHost,port:typeof r.port=="number"&&Number.isFinite(r.port)?r.port:t,createdAt:r.createdAt};return i.port!==t&&(i.port=t,mf(i,e)),i}}catch{}let n=q_(t);return mf(n,e),n}var zt=require("crypto"),Vt=require("fs"),wf=require("path");function xo(t){return(0,zt.randomBytes)(t).toString("base64url")}function Ro(t){return(0,zt.createHash)("sha256").update(t).digest("hex")}function bf(t,e){let n=Buffer.from(t),s=Buffer.from(e);return n.length!==s.length?!1:(0,zt.timingSafeEqual)(n,s)}function G_(t){try{let e=(0,Vt.readFileSync)(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n.filter(s=>s&&typeof s.deviceId=="string"&&typeof s.deviceName=="string"&&typeof s.tokenHash=="string"&&typeof s.createdAt=="string"&&typeof s.lastSeenAt=="string"&&(typeof s.revokedAt=="string"||s.revokedAt===null)):[]}catch{return[]}}function Gn(t,e){(0,Vt.mkdirSync)((0,wf.dirname)(t),{recursive:!0}),(0,Vt.writeFileSync)(t,JSON.stringify(e,null,2)+`
|
|
116
116
|
`,"utf8")}var ur=class{constructor(e=eu){this.pairingsPath=e;this.records=G_(e)}records;windows=new Map;list(){return this.records.slice()}pairedCount(){return this.records.filter(e=>!e.revokedAt).length}openWindow(e=5*6e4,n=!1){let s=`pair_${xo(8)}`,r=xo(24),i=new Date(Date.now()+e).toISOString(),o={pairingId:s,pairNonce:r,expiresAt:i,reusable:n};return this.windows.set(r,o),o}consumeWindow(e){let n=this.windows.get(e);return!n||(n.reusable||this.windows.delete(e),new Date(n.expiresAt).getTime()<Date.now())?null:n}issuePairToken(e,n){let s=new Date().toISOString(),r=xo(32),i={deviceId:e,deviceName:n,tokenHash:Ro(r),createdAt:s,lastSeenAt:s,revokedAt:null},o=this.records.findIndex(a=>a.deviceId===e);return o>=0?this.records[o]=i:this.records.unshift(i),Gn(this.pairingsPath,this.records),r}validatePairToken(e,n,s=!0){let r=this.records.find(o=>o.deviceId===e&&!o.revokedAt);if(!r)return!1;let i=Ro(n);return bf(r.tokenHash,i)?(s&&(r.lastSeenAt=new Date().toISOString(),Gn(this.pairingsPath,this.records)),!0):!1}validateAnyPairToken(e,n=!0){let s=Ro(e),r=this.records.find(i=>!i.revokedAt&&bf(i.tokenHash,s));return r?(n&&(r.lastSeenAt=new Date().toISOString(),Gn(this.pairingsPath,this.records)),r):null}revoke(e){let n=this.records.find(s=>s.deviceId===e&&!s.revokedAt);return n?(n.revokedAt=new Date().toISOString(),Gn(this.pairingsPath,this.records),!0):!1}reset(){this.records=[],this.windows.clear(),Gn(this.pairingsPath,this.records)}};function dr(t){return Array.isArray(t)?t[0]:t}function If(t){let e=dr(t.headers["x-forwarded-for"]),n=dr(t.headers["cf-connecting-ip"]),s=dr(t.headers["x-real-ip"]),r=e?.split(",")[0]?.trim()||n||s||t.socket.remoteAddress||void 0,i=dr(t.headers["user-agent"]);return{...r?{ip:r}:{},...i?{userAgent:i}:{}}}function j_(t){return t?t==="127.0.0.1"||t==="::1"||t==="::ffff:127.0.0.1":!1}var $_=["x-forwarded-for","x-forwarded-host","x-forwarded-proto","x-real-ip","forwarded","via","cf-connecting-ip","cf-ray"];function z_(t){for(let e of $_)if(t[e]!==void 0)return!0;return!1}function ct(t){return j_(t.socket.remoteAddress)&&!z_(t.headers)}function V_(t){return t&&t.match(/^Bearer\s+(.+)$/i)?.[1]?.trim()||null}function Eo(t,e){return V_(t)??e}function fr(t,e){return!!(t&&e&&t===e)}function Po(t,e,n,s=!0){return t?fr(t,e)?!0:!!n(t,s):!1}var Af=require("fs");var Q_=new Set(["ws.connect","ws.auth.success"]);function J_(t){try{let n=(0,Af.readFileSync)(t,"utf8").split(`
|
|
117
|
-
`),s=[];for(let r of n)if(r)try{let i=JSON.parse(r);i&&typeof i.event=="string"&&Q_.has(i.event)&&s.push(i)}catch{}return s}catch{return[]}}function Tf(t,e=20,n=De){let s=J_(n),r=new Map;for(let o of s){if(!o.deviceId||!o.ts)continue;let a=r.get(o.deviceId)??[];a.push({ts:o.ts,...o.ip?{ip:o.ip}:{},...o.userAgent?{userAgent:o.userAgent}:{},...o.authMode?{authMode:o.authMode}:{}}),r.set(o.deviceId,a)}return t.list().map(o=>{let a=(r.get(o.deviceId)??[]).slice().sort((l,u)=>l.ts<u.ts?1:l.ts>u.ts?-1:0).slice(0,e);return{deviceId:o.deviceId,deviceName:o.deviceName,createdAt:o.createdAt,lastSeenAt:o.lastSeenAt,revokedAt:o.revokedAt,recentConnections:a}})}var xf=require("child_process"),Rf=require("fs");function pr(t){let e=t.split(".");return e.length!==4?!1:e.every(n=>/^\d+$/.test(n)&&Number(n)>=0&&Number(n)<=255)}function Mo(t){if(!pr(t))return!1;let[e,n]=t.split(".").map(Number);return e===100&&n>=64&&n<=127}function Y_(t){if(!pr(t))return!1;let[e,n]=t.split(".").map(Number);return e===169&&n===254}function K_(t){if(!pr(t))return!1;let[e,n]=t.split(".").map(Number);return e===198&&(n===18||n===19)}function X_(t){if(!pr(t))return!1;let[e,n]=t.split(".").map(Number);return e===10||e===172&&n>=16&&n<=31||e===192&&n===168}function hr(t){return!!t&&!Y_(t)&&!K_(t)}function fe(t){if(!t)return;let e=t.trim().replace(/\.$/,"");return e?e.toLowerCase():void 0}function Lo(t){return fe(t.replace(/^https?:\/\//,""))??t}function Z_(t,e){return(t??[]).map(n=>fe(n)).filter(n=>!!n).filter(n=>hr(n)).filter((n,s,r)=>n!==e&&r.indexOf(n)===s)}function eb(t){let e=t.trim().toLowerCase();return e?!(e==="lo"||e==="lo0"||e.startsWith("loopback")||e.startsWith("awdl")||e.startsWith("llw")||e.startsWith("utun")||e.startsWith("tun")||e.startsWith("tap")||e.startsWith("ipsec")||e.startsWith("bridge")||e.startsWith("docker")||e.startsWith("br-")||e.startsWith("veth")||e.startsWith("vmnet")||e.startsWith("vboxnet")||e.startsWith("tailscale")||e.startsWith("wg")||e.startsWith("zt")||e.startsWith("ham")):!1}function tb(t){let e=Lo(t);return Mo(e)||e.endsWith(".ts.net")}function nb(t){let e=Lo(t);return X_(e)||e.endsWith(".local")}function sb(t){return Lo(t).endsWith(".trycloudflare.com")}function Cf(t,e){return tb(t)?"tailscale":nb(t)?"local_network":e?"configured_host":"fallback"}function Ef(t){let e=new Set,n=[];for(let s of t){let r=`${s.host}:${s.port}:${s.secure===!0?"secure":"plain"}`;e.has(r)||(e.add(r),n.push(s))}return n}function rb(t){let e=t[0];return e?t.slice(1).filter(n=>n.port===e.port).map(n=>n.host).filter((n,s,r)=>n!==e.host&&r.indexOf(n)===s):[]}function ib(t){try{let e=new URL(t),n=fe(e.hostname);if(!n)throw new Error("invalid relay hostname");let s=e.port?Number(e.port):e.protocol==="https:"?443:80,r=Number.isFinite(s)&&s>0?Math.floor(s):443,i=sb(n);return{kind:"relay",host:n,port:r,...e.protocol==="https:"?{secure:!0}:{},source:i?"quick_tunnel":"configured_relay",stability:i?"ephemeral":"stable"}}catch{return null}}function ob(t,e,n){let s=fe(t)||"localhost",r=Z_(e,s);return Ef([{kind:"direct",host:s,port:n,source:Cf(s,!0),stability:"stable"},...r.map(i=>({kind:"direct",host:i,port:n,source:Cf(i,!1),stability:"stable"}))])}function Pf(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function ab(t){let e=[],n=[];for(let[s,r]of Object.entries(t))if(r&&eb(s))for(let i of r)i.internal||i.family!=="IPv4"||hr(i.address)&&(Mo(i.address)?e.push(i.address):n.push(i.address));return[...e,...n]}function kf(t){let e=JSON.parse(t),n=fe(e.Self?.DNSName),s=(e.Self?.TailscaleIPs??[]).map(o=>fe(o)).filter(o=>!!o).filter(o=>Mo(o)&&hr(o)),r=s[0]??n,i=[...n&&n!==r?[n]:[],...s.filter(o=>o!==r)];return{canonicalHost:r,fallbackHosts:i}}function Mf(t=xf.execFileSync,e=Rf.existsSync){let n=[process.env.TAILSCALE_SOCKET,"/tmp/tailscale.sock"].filter(s=>typeof s=="string"&&s.length>0).filter(s=>e(s));for(let s of n)try{let r=t("tailscale",["--socket",s,"status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return kf(r)}catch{}try{let s=t("tailscale",["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return kf(s)}catch{return{fallbackHosts:[]}}}function Lf(t){let e=ob(t.canonicalHost,t.fallbackHosts,t.port),n=t.relayUrl?ib(t.relayUrl):null,s=Ef([...n?[n]:[],...e]),r=s[0]??{kind:"direct",host:fe(t.canonicalHost)||"localhost",port:t.port,source:"configured_host",stability:"stable"};return{canonicalHost:r.host,fallbackHosts:rb(s),port:r.port,connections:s}}function Nf(t){let e=fe(t.canonicalHost),n=fe(t.configuredCanonicalHost)||fe(t.tailscaleCanonicalHost)||e||"localhost",s=[...e&&e!==n?[e]:[],...t.configuredFallbackHosts??[],...t.tailscaleFallbackHosts??[],...ab(t.interfaces)].map(r=>fe(r)).filter(r=>!!r).filter(r=>hr(r)).filter((r,i,o)=>r!==n&&o.indexOf(r)===i);return{canonicalHost:n,fallbackHosts:s}}function Of(t){if(typeof t=="string")return t;if(Buffer.isBuffer(t))return t.toString("utf8");if(Array.isArray(t))return Buffer.concat(t).toString("utf8");if(t instanceof ArrayBuffer)return Buffer.from(t).toString("utf8");if(ArrayBuffer.isView(t)){let e=t;return Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8")}return String(t)}var W=L.child({module:"daemon"}),jn=L.child({module:"ws"});function lb(){try{let t=JSON.parse(require("fs").readFileSync(nu,"utf8"));return typeof t.latestVersion=="string"?t.latestVersion:void 0}catch{return}}var cb=["
|
|
117
|
+
`),s=[];for(let r of n)if(r)try{let i=JSON.parse(r);i&&typeof i.event=="string"&&Q_.has(i.event)&&s.push(i)}catch{}return s}catch{return[]}}function Tf(t,e=20,n=De){let s=J_(n),r=new Map;for(let o of s){if(!o.deviceId||!o.ts)continue;let a=r.get(o.deviceId)??[];a.push({ts:o.ts,...o.ip?{ip:o.ip}:{},...o.userAgent?{userAgent:o.userAgent}:{},...o.authMode?{authMode:o.authMode}:{}}),r.set(o.deviceId,a)}return t.list().map(o=>{let a=(r.get(o.deviceId)??[]).slice().sort((l,u)=>l.ts<u.ts?1:l.ts>u.ts?-1:0).slice(0,e);return{deviceId:o.deviceId,deviceName:o.deviceName,createdAt:o.createdAt,lastSeenAt:o.lastSeenAt,revokedAt:o.revokedAt,recentConnections:a}})}var xf=require("child_process"),Rf=require("fs");function pr(t){let e=t.split(".");return e.length!==4?!1:e.every(n=>/^\d+$/.test(n)&&Number(n)>=0&&Number(n)<=255)}function Mo(t){if(!pr(t))return!1;let[e,n]=t.split(".").map(Number);return e===100&&n>=64&&n<=127}function Y_(t){if(!pr(t))return!1;let[e,n]=t.split(".").map(Number);return e===169&&n===254}function K_(t){if(!pr(t))return!1;let[e,n]=t.split(".").map(Number);return e===198&&(n===18||n===19)}function X_(t){if(!pr(t))return!1;let[e,n]=t.split(".").map(Number);return e===10||e===172&&n>=16&&n<=31||e===192&&n===168}function hr(t){return!!t&&!Y_(t)&&!K_(t)}function fe(t){if(!t)return;let e=t.trim().replace(/\.$/,"");return e?e.toLowerCase():void 0}function Lo(t){return fe(t.replace(/^https?:\/\//,""))??t}function Z_(t,e){return(t??[]).map(n=>fe(n)).filter(n=>!!n).filter(n=>hr(n)).filter((n,s,r)=>n!==e&&r.indexOf(n)===s)}function eb(t){let e=t.trim().toLowerCase();return e?!(e==="lo"||e==="lo0"||e.startsWith("loopback")||e.startsWith("awdl")||e.startsWith("llw")||e.startsWith("utun")||e.startsWith("tun")||e.startsWith("tap")||e.startsWith("ipsec")||e.startsWith("bridge")||e.startsWith("docker")||e.startsWith("br-")||e.startsWith("veth")||e.startsWith("vmnet")||e.startsWith("vboxnet")||e.startsWith("tailscale")||e.startsWith("wg")||e.startsWith("zt")||e.startsWith("ham")):!1}function tb(t){let e=Lo(t);return Mo(e)||e.endsWith(".ts.net")}function nb(t){let e=Lo(t);return X_(e)||e.endsWith(".local")}function sb(t){return Lo(t).endsWith(".trycloudflare.com")}function Cf(t,e){return tb(t)?"tailscale":nb(t)?"local_network":e?"configured_host":"fallback"}function Ef(t){let e=new Set,n=[];for(let s of t){let r=`${s.host}:${s.port}:${s.secure===!0?"secure":"plain"}`;e.has(r)||(e.add(r),n.push(s))}return n}function rb(t){let e=t[0];return e?t.slice(1).filter(n=>n.port===e.port).map(n=>n.host).filter((n,s,r)=>n!==e.host&&r.indexOf(n)===s):[]}function ib(t){try{let e=new URL(t),n=fe(e.hostname);if(!n)throw new Error("invalid relay hostname");let s=e.port?Number(e.port):e.protocol==="https:"?443:80,r=Number.isFinite(s)&&s>0?Math.floor(s):443,i=sb(n);return{kind:"relay",host:n,port:r,...e.protocol==="https:"?{secure:!0}:{},source:i?"quick_tunnel":"configured_relay",stability:i?"ephemeral":"stable"}}catch{return null}}function ob(t,e,n){let s=fe(t)||"localhost",r=Z_(e,s);return Ef([{kind:"direct",host:s,port:n,source:Cf(s,!0),stability:"stable"},...r.map(i=>({kind:"direct",host:i,port:n,source:Cf(i,!1),stability:"stable"}))])}function Pf(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean):[]}function ab(t){let e=[],n=[];for(let[s,r]of Object.entries(t))if(r&&eb(s))for(let i of r)i.internal||i.family!=="IPv4"||hr(i.address)&&(Mo(i.address)?e.push(i.address):n.push(i.address));return[...e,...n]}function kf(t){let e=JSON.parse(t),n=fe(e.Self?.DNSName),s=(e.Self?.TailscaleIPs??[]).map(o=>fe(o)).filter(o=>!!o).filter(o=>Mo(o)&&hr(o)),r=s[0]??n,i=[...n&&n!==r?[n]:[],...s.filter(o=>o!==r)];return{canonicalHost:r,fallbackHosts:i}}function Mf(t=xf.execFileSync,e=Rf.existsSync){let n=[process.env.TAILSCALE_SOCKET,"/tmp/tailscale.sock"].filter(s=>typeof s=="string"&&s.length>0).filter(s=>e(s));for(let s of n)try{let r=t("tailscale",["--socket",s,"status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return kf(r)}catch{}try{let s=t("tailscale",["status","--json"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:1500});return kf(s)}catch{return{fallbackHosts:[]}}}function Lf(t){let e=ob(t.canonicalHost,t.fallbackHosts,t.port),n=t.relayUrl?ib(t.relayUrl):null,s=Ef([...n?[n]:[],...e]),r=s[0]??{kind:"direct",host:fe(t.canonicalHost)||"localhost",port:t.port,source:"configured_host",stability:"stable"};return{canonicalHost:r.host,fallbackHosts:rb(s),port:r.port,connections:s}}function Nf(t){let e=fe(t.canonicalHost),n=fe(t.configuredCanonicalHost)||fe(t.tailscaleCanonicalHost)||e||"localhost",s=[...e&&e!==n?[e]:[],...t.configuredFallbackHosts??[],...t.tailscaleFallbackHosts??[],...ab(t.interfaces)].map(r=>fe(r)).filter(r=>!!r).filter(r=>hr(r)).filter((r,i,o)=>r!==n&&o.indexOf(r)===i);return{canonicalHost:n,fallbackHosts:s}}function Of(t){if(typeof t=="string")return t;if(Buffer.isBuffer(t))return t.toString("utf8");if(Array.isArray(t))return Buffer.concat(t).toString("utf8");if(t instanceof ArrayBuffer)return Buffer.from(t).toString("utf8");if(ArrayBuffer.isView(t)){let e=t;return Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8")}return String(t)}var W=L.child({module:"daemon"}),jn=L.child({module:"ws"});function lb(){try{let t=JSON.parse(require("fs").readFileSync(nu,"utf8"));return typeof t.latestVersion=="string"?t.latestVersion:void 0}catch{return}}var cb=["-y","vibelet@latest","restart"],Bo=!1;function ub(){let t=process.env.VIBELET_DAEMON_UPDATE_COMMAND||(process.platform==="win32"?"npx.cmd":"npx"),e=cb;if(process.env.VIBELET_DAEMON_UPDATE_ARGS_JSON)try{let s=JSON.parse(process.env.VIBELET_DAEMON_UPDATE_ARGS_JSON);Array.isArray(s)&&s.every(r=>typeof r=="string")&&(e=s)}catch{}let n=[t==="npx.cmd"?"npx":t,...e].map(s=>/^[A-Za-z0-9_/@:=-]+$/.test(s)?s:JSON.stringify(s)).join(" ");return{command:t,args:e,displayCommand:n}}function db(t,e,n){(0,qe.mkdirSync)(xt,{recursive:!0});let s=null,r=null;try{s=(0,qe.openSync)(yn,"a"),r=(0,qe.openSync)(vn,"a");let i=(0,Ff.spawn)(t,e,{cwd:process.cwd(),env:{...process.env,VIBELET_UPDATE_SOURCE:"app"},detached:!0,stdio:["ignore",s,r]});i.once("error",o=>{Bo=!1,W.error({command:n,error:String(o)},"daemon update spawn failed"),_.emit("daemon.update.spawn_failed",{command:n,error:String(o)})}),i.unref(),W.info({command:n,pid:i.pid},"daemon update spawned"),_.emit("daemon.update.spawned",{command:n,pid:i.pid})}finally{s!==null&&(0,qe.closeSync)(s),r!==null&&(0,qe.closeSync)(r)}}function fb(t,e){let{command:n,args:s,displayCommand:r}=ub();if(Bo){t.send(JSON.stringify({type:"response",id:e,ok:!0,data:{started:!1,alreadyRunning:!0,command:r}}));return}Bo=!0,t.send(JSON.stringify({type:"response",id:e,ok:!0,data:{started:!0,command:r}})),W.info({command:r},"daemon update requested"),_.emit("daemon.update.requested",{command:r});let i=setTimeout(()=>{db(n,s,r)},100);typeof i.unref=="function"&&i.unref()}var j=_f(S.port),te=new cr((t,e)=>rr(t,{daemonId:j.daemonId,canonicalHost:$n().canonicalHost,...e??{}})),ae=new ur,mr=new Set,We=new WeakMap,Df=!1,Wf=Date.now(),Qt=null,gr=null,pb=1e3;function hb(){let t=Mf();return Nf({canonicalHost:j.canonicalHost,configuredCanonicalHost:S.canonicalHost,configuredFallbackHosts:Pf(S.fallbackHosts),tailscaleCanonicalHost:t.canonicalHost,tailscaleFallbackHosts:t.fallbackHosts,interfaces:(0,Hf.networkInterfaces)()})}function $n(){let t=Date.now();if(gr&&gr.expiresAt>t)return gr.value;let e=hb(),n=Lf({canonicalHost:e.canonicalHost,fallbackHosts:e.fallbackHosts,port:j.port,relayUrl:S.relayUrl});return gr={value:n,expiresAt:t+pb},n}function gb(t){let e={t:"vp",d:t.daemonId,n:t.displayName,h:t.canonicalHost,p:t.port,c:t.pairNonce,e:t.expiresAt};return t.fallbackHosts&&(e.f=t.fallbackHosts),t.connections?.length&&(e.o=t.connections.map(n=>[n.kind,n.host,n.port,n.source,n.stability,n.secure===!0])),e}async function mb(t){let e=JSON.stringify(gb(t));await(0,le.mkdir)(Ie,{recursive:!0}),await Do.default.toFile(Ei,e,{type:"png",errorCorrectionLevel:"M",margin:1,scale:8});let n=await Do.default.toString(e,{type:"terminal",small:!0,errorCorrectionLevel:"M"});Rt(`
|
|
118
118
|
Scan this QR code with Vibelet app:
|
|
119
119
|
|
|
120
120
|
${n}
|
package/dist/runtime-version.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var s=require("node:fs"),n=require("node:path"),c="@vibelet/cli";function a(e){try{let r=JSON.parse((0,s.readFileSync)(e,"utf8"));if(r.name===c&&typeof r.version=="string"&&r.version.length>0)return r.version}catch{}return null}function p(){return"1.2.
|
|
1
|
+
var s=require("node:fs"),n=require("node:path"),c="@vibelet/cli";function a(e){try{let r=JSON.parse((0,s.readFileSync)(e,"utf8"));if(r.name===c&&typeof r.version=="string"&&r.version.length>0)return r.version}catch{}return null}function p(){return"1.2.7"}var i=p();process.stdout.write(`${i}
|
|
2
2
|
`);
|
package/dist/vibelet.mjs
CHANGED
|
@@ -6848,7 +6848,7 @@ function checkForUpdateFromCache() {
|
|
|
6848
6848
|
updateMessage =
|
|
6849
6849
|
`\x1b[33m╭───────────────────────────────────────────╮\x1b[0m\n` +
|
|
6850
6850
|
`\x1b[33m│\x1b[0m Update available: \x1b[90m${packageJson.version}\x1b[0m → \x1b[32m${cached.latestVersion}\x1b[0m${' '.repeat(Math.max(0, 14 - packageJson.version.length - cached.latestVersion.length))}\x1b[33m│\x1b[0m\n` +
|
|
6851
|
-
`\x1b[33m│\x1b[0m Run \x1b[36mnpx
|
|
6851
|
+
`\x1b[33m│\x1b[0m Run \x1b[36mnpx -y vibelet@latest\x1b[0m to upgrade \x1b[33m│\x1b[0m\n` +
|
|
6852
6852
|
`\x1b[33m╰───────────────────────────────────────────╯\x1b[0m`;
|
|
6853
6853
|
}
|
|
6854
6854
|
}
|
|
@@ -6926,7 +6926,7 @@ function ensureRuntimeInstalled() {
|
|
|
6926
6926
|
fail(
|
|
6927
6927
|
`Refusing to downgrade vibelet runtime from v${runtimeMetadata.version} to v${packageJson.version}.`,
|
|
6928
6928
|
`An older daemon can silently drop on-disk state (sessions, archives) it doesn't know about.\n`
|
|
6929
|
-
+ `Run \`npx
|
|
6929
|
+
+ `Run \`npx -y vibelet@latest\` to use the newest CLI, or remove \`${runtimeCurrentDir}\` if you really need to roll back.`,
|
|
6930
6930
|
);
|
|
6931
6931
|
}
|
|
6932
6932
|
|