agentpager-cli 0.1.1 → 0.1.2
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/cli.js +1 -1
- package/package.json +3 -2
package/dist/cli.js
CHANGED
|
@@ -17,7 +17,7 @@ var Gs=Object.defineProperty;var T=(s,e,t)=>()=>{if(t)throw t[0];try{return s&&(
|
|
|
17
17
|
`).map(n=>n.trim()).filter(Boolean).map(n=>({id:n,label:n,current:!1}));if(r.length)return{models:r,current:""}}catch{}return{models:[],current:""}}if(e.includes("qwen")){try{let r=JSON.parse(ct(ot(at,".qwen","settings.json"))||"{}").modelProviders,n=[];Array.isArray(r)?n=r.map(o=>o&&o.name).filter(Boolean):r&&typeof r=="object"&&(n=Object.values(r).flatMap(o=>Array.isArray(o)?o.map(a=>a&&a.name):[o&&o.name]).filter(Boolean));let i=[...new Set(n.map(o=>String(o).replace(/^\[[^\]]*\]\s*/,"").trim()).filter(Boolean))];if(i.length)return{models:se(i),current:""}}catch{}return{models:se(["qwen3-coder"]),current:""}}if(e.includes("codex")){let t=(ct(ot(at,".codex","config.toml")).match(/^\s*model\s*=\s*"([^"]+)"/m)||[])[1]||"",r=[...new Set([t,...Ae.codex].filter(Boolean))];return{models:se(r,t),current:t}}if(e.includes("codebuddy")){let t="";try{t=JSON.parse(ct(ot(at,".codebuddy","settings.json"))||"{}").model||""}catch{}let r=[...new Set([t,...Ae.codebuddy].filter(Boolean))];return{models:se(r,t),current:t}}return e.includes("gemini")?{models:se(Ae.gemini,"gemma-4-31b-it"),current:"gemma-4-31b-it"}:{models:se(Ae.claude),current:""}}var xs,at,Ae,se,ct,vs=T(()=>{xs=pn(fn),at=_n(),Ae={claude:["fable","opus","sonnet","haiku"],gemini:["gemma-4-31b-it","gemma-4-26b-a4b-it","gemini-2.5-pro","gemini-3.5-flash","gemini-3-flash-preview","gemini-3.1-flash-lite","gemini-3.1-pro-preview"],codex:["gpt-5.5","gpt-5.5-codex","gpt-5"],codebuddy:["glm-5.1","deepseek-v3.2","kimi-k2.5","gpt-5.5","gemini-3-pro"]},se=(s,e)=>s.map(t=>({id:t,label:t,current:t===e})),ct=s=>{try{return hn(s)?mn(s,"utf8"):""}catch{return""}}});var Ge={};G(Ge,{listClaude:()=>An,listNative:()=>Xn,readClaude:()=>js,readNative:()=>Yn,searchClaude:()=>Mn});import{openSync as yn,readSync as wn,closeSync as xn,fstatSync as bn,readdirSync as L,statSync as J,existsSync as R,readFileSync as z,writeFileSync as vn,renameSync as Sn}from"node:fs";import{homedir as H}from"node:os";import{join as M}from"node:path";import{execFileSync as dt}from"node:child_process";import{createHash as ks}from"node:crypto";function Ce(s){return typeof s=="string"?s:Array.isArray(s)?s.map(e=>typeof e=="string"?e:e&&e.type==="text"&&e.text||"").join(""):""}function In(s){if(!Array.isArray(s))return null;let e=[];for(let t of s)if(t&&t.type==="image"&&t.source&&t.source.type==="base64"&&t.source.data)try{let r="cc_"+ks("sha1").update(t.source.data).digest("hex").slice(0,24),n=ke(r,t.source.media_type,t.source.data);e.push({id:r,media_type:n.media_type,bytes:n.bytes})}catch{}return e.length?e:null}function kn(s){if(!Array.isArray(s&&s.content))return null;let e=[];for(let t of s.content)if(t&&t.type==="input_image"&&typeof t.image_url=="string"){let r=t.image_url.match(/^data:(image\/[a-z+.-]+);base64,(.+)$/is);if(!r)continue;try{let n="cx_"+ks("sha1").update(r[2]).digest("hex").slice(0,24),i=ke(n,r[1],r[2]);e.push({id:n,media_type:i.media_type,bytes:i.bytes})}catch{}}return e.length?e:null}function C(s){let e=(s||"").trim();return!e||/^(\[Image: [^\]]+\]\s*)+$/.test(e)?!0:/^</.test(e)||/^Caveat:/.test(e)||/^This session is being continued/.test(e)||/^\[Request interrupted/.test(e)||/^Command:/.test(e)}function Ne(s){return String(s||"").replace(/^\s*<([a-z_]*metadata)>[\s\S]*?<\/\1>\s*/i,"").replace(/^\s*<task>\s*/i,"").replace(/<\/task>/gi," ").replace(/^\s*ou_[0-9a-f]{16,}\s*[::]\s*/i,"").trim()}function K(s,e,t){let r=yn(s,"r");try{let n=bn(r).size,i=Math.min(t,n),o=e?Math.max(0,n-i):0,a=Buffer.alloc(i);return wn(r,a,0,i,o),a.toString("utf8")}catch{return""}finally{xn(r)}}function P(s){let e=[];for(let t of s.split(`
|
|
18
18
|
`)){let r=t.trim();if(r)try{e.push(JSON.parse(r))}catch{}}return e}function En(s){let e="",t="",r="",n="";for(let a of P(K(s,!1,65536))){if(!t&&a.cwd&&(t=a.cwd),!n&&a.type==="ai-title"&&a.aiTitle&&(n=String(a.aiTitle).replace(/\s+/g," ").trim().slice(0,60)),!e&&a.type==="user"&&a.message){let l=Ne(Ce(a.message.content));l&&!C(l)&&(e=l.replace(/\s+/g," ").trim().slice(0,40))}if(n&&t)break}let i=P(K(s,!0,65536)),o=0;for(let a=i.length-1;a>=0;a--){let l=i[a];if(!o&&l&&l.timestamp&&(o=Date.parse(l.timestamp)||0),!n&&l.type==="ai-title"&&l.aiTitle&&(n=String(l.aiTitle).replace(/\s+/g," ").trim().slice(0,60)),!r&&(l.type==="assistant"||l.type==="user")&&l.message){let d=Ne(Ce(l.message.content));d&&!C(d)&&(r=d.replace(/\s+/g," ").trim().slice(0,50))}if(o&&n&&r)break}return{title:n||e,cwd:t,preview:r,ts:o}}function ft(){if(!R(Te))return[];let s=[];for(let e of L(Te)){let t=M(Te,e),r;try{r=J(t)}catch{continue}if(r.isDirectory())for(let n of L(t)){if(!n.endsWith(".jsonl"))continue;let i=M(t,n),o;try{o=J(i)}catch{continue}o.size<64||s.push({id:n.replace(/\.jsonl$/,""),proj:e,fp:i,mtime:o.mtimeMs})}}return s.sort((e,t)=>t.mtime-e.mtime)}function pt(s){let e=En(s.fp);return{id:s.id,provider:"claude",project:s.proj,cwd:e.cwd,title:e.title||"(\u65E0\u6807\u9898\u4F1A\u8BDD)",preview:e.preview,updated_at:e.ts||Math.round(s.mtime)}}function An(s=20,e=0){let t=ft(),r=t.length,n=Math.max(0,e|0),i=t.slice(n,n+s);return{items:i.map(pt),total:r,offset:n,hasMore:n+i.length<r}}function Mn(s,e=50){let t=(s||"").trim();if(!t)return{items:[],total:0,q:t};let r=ft();if(!r.length)return{items:[],total:0,q:t};let n=new Set,i=200;for(let a=0;a<r.length;a+=i){let l=r.slice(a,a+i).map(d=>d.fp);try{dt("grep",["-l","-i","-F","--",t,...l],{encoding:"utf8",maxBuffer:67108864}).split(`
|
|
19
19
|
`).forEach(p=>{p.trim()&&n.add(p.trim())})}catch{}}let o=r.filter(a=>n.has(a.fp));return{items:o.slice(0,e).map(pt),total:o.length,q:t}}function Es(){if(!R(Ss))return[];let s=[],e=(t,r)=>{if(r>4)return;let n;try{n=L(t)}catch{return}for(let i of n){let o=M(t,i),a;try{a=J(o)}catch{continue}if(a.isDirectory())e(o,r+1);else if(i.startsWith("rollout-")&&i.endsWith(".jsonl")&&a.size>=64){let l=i.match(/-([0-9a-f-]{36})\.jsonl$/);s.push({id:l?l[1]:i.replace(/\.jsonl$/,""),fp:o,mtime:a.mtimeMs})}}};return e(Ss,0),s.sort((t,r)=>r.mtime-t.mtime)}function ie(s){return Array.isArray(s.content)?s.content.map(e=>e&&typeof e.text=="string"?e.text:"").join(""):""}function Tn(s){let e="",t="",r="";for(let n of P(K(s,!1,65536))){let i=n.payload||n;if(!t&&n.type==="session_meta"&&i.cwd&&(t=i.cwd),!e&&n.type==="response_item"&&i.role==="user"){let o=Ne(ie(i));o&&!C(o)&&(e=o.replace(/\s+/g," ").slice(0,40))}if(e&&t)break}for(let n of P(K(s,!0,65536)).reverse()){let i=n.payload||n;if(n.type==="response_item"){let o=Ne(ie(i));if(o&&!C(o)){r=o.replace(/\s+/g," ").slice(0,50);break}}}return{title:e,cwd:t,preview:r}}function Cn(s){let e=Tn(s.fp);return{id:s.id,provider:"codex",project:e.cwd?e.cwd.split("/").pop():"",cwd:e.cwd,title:e.title||"(\u65E0\u6807\u9898\u4F1A\u8BDD)",preview:e.preview,updated_at:Math.round(s.mtime)}}function Nn(s,e){let t=Es().find(n=>n.id===s);if(!t)return{id:s,msgs:[]};let r=[];for(let n of P(z(t.fp,"utf8"))){if(n.type!=="response_item")continue;let i=n.payload||n,o=ie(i).trim(),a=i.role==="user"?kn(i):null,l=o&&!C(o)?o:"";!l&&!a||r.push({role:i.role==="user"?"me":"agent",text:l,...a?{images:a}:{}})}return{id:s,msgs:r.slice(-(e||400))}}function Oe(s,e){if(!R(s))return[];let t=[];for(let r of L(s)){let n=e?M(s,r,e):M(s,r),i;try{i=J(n)}catch{continue}if(i.isDirectory())for(let o of L(n)){if(!o.endsWith(".jsonl"))continue;let a=M(n,o),l;try{l=J(a)}catch{continue}l.size<64||t.push({id:o.replace(/\.jsonl$/,""),fp:a,mtime:l.mtimeMs})}}return t.sort((r,n)=>n.mtime-r.mtime)}function Re(s){return s?Array.isArray(s.parts)?s.parts.map(e=>e&&typeof e.text=="string"?e.text:"").join(""):Ce(s.content):""}function On(s){let e="",t="",r="";for(let n of P(K(s,!1,65536))){if(!t&&n.cwd&&(t=n.cwd),!e&&n.type==="user"&&n.message){let i=Re(n.message).trim();i&&!C(i)&&(e=i.replace(/\s+/g," ").slice(0,40))}if(e&&t)break}for(let n of P(K(s,!0,65536)).reverse())if((n.type==="assistant"||n.type==="user")&&n.message){let i=Re(n.message).trim();if(i&&!C(i)){r=i.replace(/\s+/g," ").slice(0,50);break}}return{title:e,cwd:t,preview:r}}function Rn(s){let e=On(s.fp);return{id:s.id,provider:"qwen",project:e.cwd?e.cwd.split("/").pop():"",cwd:e.cwd,title:e.title||"(\u65E0\u6807\u9898\u4F1A\u8BDD)",preview:e.preview,updated_at:Math.round(s.mtime)}}function Pn(s,e){let t=Oe(As,"chats").find(n=>n.id===s);if(!t)return{id:s,msgs:[]};let r=[];for(let n of P(z(t.fp,"utf8")))if(n.type==="user"&&n.message){let i=Re(n.message).trim();i&&!C(i)&&r.push({role:"me",text:i})}else if(n.type==="assistant"&&n.message){let i=Re(n.message).trim();i&&r.push({role:"agent",text:i})}return{id:s,msgs:r.slice(-(e||400))}}function jn(s){let e="",t="",r="";for(let n of P(K(s,!1,65536))){if(!t&&n.cwd&&(t=n.cwd),!e&&n.role==="user"&&Array.isArray(n.content)){let i=ie(n).trim();i&&!C(i)&&(e=i.replace(/\s+/g," ").slice(0,40))}if(e&&t)break}for(let n of P(K(s,!0,65536)).reverse())if(Array.isArray(n.content)){let i=ie(n).trim();if(i&&!C(i)){r=i.replace(/\s+/g," ").slice(0,50);break}}return{title:e,cwd:t,preview:r}}function Gn(s){let e=jn(s.fp);return{id:s.id,provider:"codebuddy",project:e.cwd?e.cwd.split("/").pop():"",cwd:e.cwd,title:e.title||"(\u65E0\u6807\u9898\u4F1A\u8BDD)",preview:e.preview,updated_at:Math.round(s.mtime)}}function Ln(s,e){let t=Oe(Ms,"").find(n=>n.id===s);if(!t)return{id:s,msgs:[]};let r=[];for(let n of P(z(t.fp,"utf8"))){if(!Array.isArray(n.content))continue;let i=ie(n).trim();!i||C(i)||r.push({role:n.role==="user"?"me":"agent",text:i})}return{id:s,msgs:r.slice(-(e||400))}}function je(s,e){try{let t=dt("sqlite3",["-json",s,e],{encoding:"utf8",maxBuffer:16777216,timeout:5e3});return t.trim()?JSON.parse(t):[]}catch{return[]}}function Dn(){if(!R(re))return[];let s;try{s=J(re)}catch{return[]}return Y({fp:re,mtime:s.mtimeMs},()=>je(re,"SELECT id,title,directory,time_updated FROM session ORDER BY time_updated DESC;").map(t=>({id:t.id,provider:"opencode",project:t.directory?String(t.directory).split("/").pop():"",cwd:t.directory||"",title:t.title||"(\u65E0\u6807\u9898\u4F1A\u8BDD)",preview:"",updated_at:Number(t.time_updated)||0})))||[]}function qn(s,e){if(!R(re))return{id:s,msgs:[]};let t=String(s).replace(/'/g,""),r=je(re,`SELECT m.data AS mdata, p.data AS pdata FROM part p JOIN message m ON m.id=p.message_id WHERE p.session_id='${t}' ORDER BY p.time_created;`),n=[];for(let i of r){let o="agent";try{JSON.parse(i.mdata).role==="user"&&(o="me")}catch{}let a="";try{let l=JSON.parse(i.pdata);l&&l.type==="text"&&(a=l.text||"")}catch{}a=(a||"").trim(),!(!a||C(a))&&n.push({role:o,text:a})}return{id:s,msgs:n.slice(-(e||400))}}function Ts(s){return typeof s=="string"?s:Array.isArray(s)?s.map(e=>e&&e.text||(typeof e=="string"?e:"")).join(""):""}function Bn(s){let e="",t="";for(let r of je(s,"SELECT CAST(data AS TEXT) AS t FROM blobs;")){let n;try{n=JSON.parse(r.t)}catch{continue}let i=Ts(n.content);if(!t){let o=i.match(/Workspace Path:\s*([^\n]+)/);o&&(t=o[1].trim())}if(!e&&n.role==="user"){let o=Cs(i);o&&!Ns(o)&&!C(o)&&(e=o.replace(/\s+/g," ").slice(0,40))}if(e&&t)break}return{title:e,cwd:t}}function Un(s){if(!R(ne))return"";for(let e of L(ne)){let t=M(ne,e,s,"store.db");if(R(t))return t}return""}function $n(s,e){let t=Un(s);if(!t)return{id:s,msgs:[]};let r=[];for(let n of je(t,"SELECT CAST(data AS TEXT) AS t FROM blobs;")){let i;try{i=JSON.parse(n.t)}catch{continue}if(i.role!=="user"&&i.role!=="assistant")continue;let o=Cs(Ts(i.content));!o||Ns(o)||C(o)||r.push({role:i.role==="user"?"me":"agent",text:o})}return{id:s,msgs:r.slice(-(e||400))}}function Fn(){if(!R(ne))return[];let s=[];for(let e of L(ne)){let t=M(ne,e),r;try{r=J(t)}catch{continue}if(r.isDirectory())for(let n of L(t)){let i=M(t,n,"store.db");if(!R(i))continue;let o;try{o=J(i)}catch{continue}s.push(Y({fp:i,mtime:o.mtimeMs},()=>{let a=Bn(i);return{id:n,provider:"cursor",project:a.cwd?a.cwd.split("/").pop():"",cwd:a.cwd,title:a.title||"cursor \u4F1A\u8BDD",preview:"",updated_at:o.mtimeMs}}))}}return s}function Os(s){let e=[];for(let t of P(s)){let r=t.$set&&t.$set.messages||t.messages;if(Array.isArray(r))for(let n of r){let i=Array.isArray(n.content)?n.content.map(o=>o&&o.text||"").join(""):typeof n.content=="string"?n.content:"";i&&e.push({role:n.type==="user"?"me":"agent",text:i})}}return e}function Jn(){if(!R(Me))return[];let s=[];for(let e of L(Me)){let t=M(Me,e,"chats");if(!R(t))continue;let r="";try{r=z(M(Me,e,".project_root"),"utf8").trim()}catch{}for(let n of L(t)){if(!n.startsWith("session-")||!n.endsWith(".jsonl"))continue;let i=M(t,n),o;try{o=J(i)}catch{continue}let a=Y({fp:i,mtime:o.mtimeMs},()=>{let l=K(i,!1,2e5);if(!l.includes('"messages"'))return null;let d=Os(l);if(!d.some(u=>!lt(u.text.trim())))return null;let p="";for(let u of d){let _=u.text.trim();if(u.role==="me"&&_&&!lt(_)){p=_.replace(/\s+/g," ").slice(0,40);break}}return{id:i,provider:"gemini",project:r?r.split("/").pop():"",cwd:r,title:p||"(\u65E0\u6807\u9898\u4F1A\u8BDD)",preview:"",updated_at:o.mtimeMs}});a&&s.push(a)}}return s}function Kn(s,e){if(!R(s))return{id:s,msgs:[]};let t=Os(z(s,"utf8")).filter(r=>{let n=r.text.trim();return n&&!lt(n)}).map(r=>({role:r.role,text:r.text.trim()}));return{id:s,msgs:t.slice(-(e||400))}}function Wn(s){if(!s.length)return s;Ps();let e=s.filter(t=>{let r=V.get("cxreal:"+t.fp);return!r||r.mtime!==t.mtime});if(e.length){let t=new Set;for(let r=0;r<e.length;r+=200){let n=e.slice(r,r+200).map(i=>i.fp);try{dt("grep",["-l","-F","--",'"type":"output_text"',...n],{encoding:"utf8",maxBuffer:1<<26}).split(`
|
|
20
|
-
`).forEach(i=>{i.trim()&&t.add(i.trim())})}catch{}}for(let r of e)V.set("cxreal:"+r.fp,{mtime:r.mtime,item:t.has(r.fp)});Pe=!0}return s.filter(t=>{let r=V.get("cxreal:"+t.fp);return r&&r.item})}function Ps(){if(!Is){Is=!0;try{let s=JSON.parse(z(ut,"utf8"));if(s&&s.v===Rs&&s.files)for(let[e,t]of Object.entries(s.files))V.set(e,t)}catch{}}}function Hn(){if(Pe){Pe=!1;try{let s=ut+".tmp";vn(s,JSON.stringify({v:Rs,files:Object.fromEntries(V)})),Sn(s,ut)}catch{}}}function Y(s,e){let t=V.get(s.fp);if(t&&t.mtime===s.mtime)return t.item;let r=e(s);return V.set(s.fp,{mtime:s.mtime,item:r}),Pe=!0,r}function Xn(s=20,e=0){Ps();let t=[...ft().map(o=>Y(o,pt)),...Wn(Es()).map(o=>Y(o,Cn)),...Oe(As,"chats").map(o=>Y(o,Rn)),...Oe(Ms,"").map(o=>Y(o,Gn)),...Dn(),...Fn(),...Jn()].filter(Boolean).sort((o,a)=>(a.updated_at||0)-(o.updated_at||0));Hn();let r=t.length,n=Math.max(0,e|0),i=t.slice(n,n+s);return{items:i,total:r,offset:n,hasMore:n+i.length<r}}function Yn(s,e,t,r=400){let n=String(s||"");return n.includes("codex")?Nn(e,r):n.includes("qwen")?Pn(e,r):n.includes("codebuddy")?Ln(e,r):n.includes("opencode")?qn(e,r):n.includes("gemini")?Kn(e,r):n.includes("cursor")?$n(e,r):js(e,t,r)}function js(s,e,t=400){let r=M(Te,e||"",s+".jsonl");if(!R(r))return{id:s,rows:[]};let n=$(),i=[];for(let a of P(z(r,"utf8")))if(a.type==="user"&&a.message){let l=a.message.content;if(Array.isArray(l)&&l.some(A=>A&&A.type==="tool_result")){i.push(...n.onMessage(a));continue}let p=Ce(l),u=In(l),_=p&&!C(p)?p.trim():"";(_||u)&&i.push(b.user(_,u||void 0))}else a.type==="assistant"&&a.message?i.push(...n.onMessage(a)):a.type==="result"&&i.push(...n.onMessage(a));let o=de(i);for(let a of o.rows)a.kind==="assistant"&&(a.streaming=!1);return{id:s,rows:o.rows.slice(-t)}}var Te,Ss,As,Ms,re,ne,Cs,Ns,Me,lt,ut,Rs,V,Is,Pe,Le=T(()=>{le();rt();U();fe();Te=M(H(),".claude","projects");Ss=M(H(),".codex","sessions");As=M(H(),".qwen","projects");Ms=M(H(),".codebuddy","projects");re=M(H(),".local","share","opencode","opencode.db");ne=M(H(),".cursor","chats");Cs=s=>s.replace(/<\/?user_query>/g,"").trim(),Ns=s=>/^<user_info>|^<environment|^<additional|^<system/.test(s);Me=M(H(),".gemini","tmp");lt=s=>C(s)||/^<session_context>/.test(s);ut=M(H(),".agentpager","native-cache.json"),Rs=1,V=new Map,Is=!1,Pe=!1});import{readFileSync as Ls,writeFileSync as Ds,mkdirSync as qs,existsSync as Bs}from"node:fs";import{homedir as Us}from"node:os";import{join as ht}from"node:path";import{randomUUID as $s}from"node:crypto";var De=process.env.AGENTPAGER_HOME||ht(Us(),".agentpager"),pe=ht(De,"config.json");function qe(){return Bs(pe)?JSON.parse(Ls(pe,"utf8")):null}function Q(s){return qs(De,{recursive:!0}),Ds(pe,JSON.stringify(s,null,2)),s}function me(){let s=qe();return s||(s={device_id:"device_"+$s().slice(0,12),device_kp:{stub:!0},relay_url:process.env.AGENTPAGER_RELAY||"ws://127.0.0.1:8090/ws",relay_http:process.env.AGENTPAGER_RELAY_HTTP||"http://127.0.0.1:8090",binding:null,agents:[]},Q(s))}var oe={DIR:De,FILE:pe};Ue();import{WebSocket as nr}from"ws";import Z from"tweetnacl";var er=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function ae(s){let e=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],t=s.length,r=new Uint8Array((t+8>>6<<6)+64);r.set(s),r[t]=128;let n=t*8,i=new DataView(r.buffer);i.setUint32(r.length-4,n>>>0),i.setUint32(r.length-8,Math.floor(n/4294967296));let o=new Uint32Array(64),a=(p,u)=>p>>>u|p<<32-u;for(let p=0;p<r.length;p+=64){for(let h=0;h<16;h++)o[h]=i.getUint32(p+h*4);for(let h=16;h<64;h++){let k=a(o[h-15],7)^a(o[h-15],18)^o[h-15]>>>3,c=a(o[h-2],17)^a(o[h-2],19)^o[h-2]>>>10;o[h]=o[h-16]+k+o[h-7]+c|0}let[u,_,A,O,y,v,g,w]=e;for(let h=0;h<64;h++){let k=a(y,6)^a(y,11)^a(y,25),c=y&v^~y&g,f=w+k+c+er[h]+o[h]|0,m=a(u,2)^a(u,13)^a(u,22),S=u&_^u&A^_&A,E=m+S|0;w=g,g=v,v=y,y=O+f|0,O=A,A=_,_=u,u=f+E|0}e[0]=e[0]+u|0,e[1]=e[1]+_|0,e[2]=e[2]+A|0,e[3]=e[3]+O|0,e[4]=e[4]+y|0,e[5]=e[5]+v|0,e[6]=e[6]+g|0,e[7]=e[7]+w|0}let l=new Uint8Array(32),d=new DataView(l.buffer);for(let p=0;p<8;p++)d.setUint32(p*4,e[p]>>>0);return l}var ge=(s,e)=>{let t=new Uint8Array(s.length+e.length);return t.set(s),t.set(e,s.length),t};function ye(s,e){s.length>64&&(s=ae(s));let t=new Uint8Array(64);t.set(s);let r=new Uint8Array(64),n=new Uint8Array(64);for(let i=0;i<64;i++)r[i]=t[i]^54,n[i]=t[i]^92;return ae(ge(n,ae(ge(r,e))))}function gt(s,e,t,r){let n=ye(e,s),i=new Uint8Array(r),o=new Uint8Array(0),a=0,l=1;for(;a<r;)o=ye(n,ge(ge(o,t),new Uint8Array([l++]))),i.set(o.subarray(0,Math.min(o.length,r-a)),a),a+=o.length;return i}function yt(s,e){if(s.length!==e.length)return!1;let t=0;for(let r=0;r<s.length;r++)t|=s[r]^e[r];return t===0}var ee=s=>new TextEncoder().encode(s),wt=(...s)=>{let e=0;for(let n of s)e+=n.length;let t=new Uint8Array(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return t},ce="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function te(s){let e="";for(let t=0;t<s.length;t+=3){let r=s[t],n=t+1<s.length?s[t+1]:0,i=t+2<s.length?s[t+2]:0;e+=ce[r>>2]+ce[(r&3)<<4|n>>4],e+=t+1<s.length?ce[(n&15)<<2|i>>6]:"=",e+=t+2<s.length?ce[i&63]:"="}return e}function X(s){let e=s.replace(/=+$/,""),t=new Uint8Array(e.length*6>>3),r=0,n=0,i=0;for(let o of e)n=n<<6|ce.indexOf(o),r+=6,r>=8&&(r-=8,t[i++]=n>>r&255);return t}function tr(s){let e=s.map(r=>r instanceof Uint8Array?r:ee(String(r))),t=[];for(let r of e){let n=new Uint8Array(4);new DataView(n.buffer).setUint32(0,r.length,!0),t.push(n,r)}return wt(...t)}var sr="ABCDEFGHJKMNPQRSTUVWXYZ23456789";function xt(s=8){let e="";for(;e.length<s;){let t=Z.randomBytes(1)[0];t<248&&(e+=sr[t%31])}return e}function rr(s){let e="";for(let t of s)e+=t.toString(16).padStart(2,"0");return e}function bt(s){return rr(ae(ee("agentpager-psid|"+s))).slice(0,32)}function vt(){return Z.box.keyPair()}function St(s,e){let t=Z.scalarMult(s,e);if(t.every(r=>r===0))throw new Error("insecure_ecdh: low-order/zero peer key");return t}function It({psid:s,phone_id:e,device_id:t,epk_phone:r,epk_device:n}){return tr([s,e,t,r,n])}function $e(s,e,t){return ye(ee("agentpager-pair|"+s),wt(e,ee("|"+t)))}function kt(s,e){return yt(s,e)}function Et(s,e){return gt(s,e,ee("agentpager-chan"),32)}function At(s,e){let t=Z.randomBytes(24),r=Z.secretbox(ee(JSON.stringify(e)),t,s);return{n:te(t),c:te(r)}}function Mt(s,e){let t=Z.secretbox.open(X(e.c),X(e.n),s);return t?JSON.parse(new TextDecoder().decode(t)):null}function Tt(s,{onCode:e,timeoutMs:t=6e5}={}){return new Promise((r,n)=>{let i=xt();e&&e(i);let o=bt(i),a=vt(),l=new nr(`${s.relay_url}?role=device&id=${s.device_id}`),d=setTimeout(()=>{try{l.close()}catch{}n(new Error("pair_timeout"))},t),p=null,u=null,_=!1,A=!1,O=null,y=h=>{clearTimeout(d);try{l.close()}catch{}h?n(h):r(s)},v=()=>It({psid:o,phone_id:p.phone_id,device_id:s.device_id,epk_phone:p.epk,epk_device:a.publicKey});l.on("open",()=>l.send(JSON.stringify({type:"pair_offer",psid:o,device_id:s.device_id,epk:te(a.publicKey)}))),l.on("message",h=>{let k;try{k=JSON.parse(h.toString())}catch{return}if(k.type==="pair_peer"){p={phone_id:k.phone_id,epk:X(k.epk)};let c=v();try{u=Et(St(a.secretKey,p.epk),c)}catch(f){return y(new Error("pair_failed: "+f.message))}l.send(JSON.stringify({type:"pair_mac",psid:o,mac:te($e(i,c,"device"))})),_=!0,O&&g(O),w()}else if(k.type==="pair_mac"){if(!p){O=k.mac;return}g(k.mac)}}),l.on("error",h=>y(h));function g(h){if(A=kt(X(h),$e(i,v(),"phone")),!A)return y(new Error("pair_failed: mac_mismatch (wrong code or MITM)"));w()}function w(){_&&A&&u&&(s.binding={phone_id:p.phone_id,paired_at:Date.now(),chan_key:te(u)},Q(s),y(null))}})}import{hostname as Vn}from"node:os";import{WebSocket as ir}from"ws";import{EventEmitter as or}from"node:events";var we=class extends or{constructor({relay_url:e,device_id:t}){super(),this.url=`${e}?role=device&id=${t}`,this.device_id=t,this.ws=null,this.backoff=500,this.alive=!1,this.stopped=!1}connect(){return this.ws=new ir(this.url),this.ws.on("open",()=>{this.alive=!0,this.backoff=500,this.emit("open"),this._heartbeat()}),this.ws.on("message",e=>{let t;try{t=JSON.parse(e.toString())}catch{return}t.type==="envelope"?this.emit("envelope",t.envelope):t.type==="pair_result"?this.emit("pair_result",t):t.type==="delivery.expired"?this.emit("expired",t.msg_id):t.type==="paired"?this.emit("paired",t):this.emit("control",t)}),this.ws.on("pong",()=>{this.alive=!0}),this.ws.on("close",()=>{this._down()}),this.ws.on("error",e=>{this.emit("error",e)}),this}_heartbeat(){clearInterval(this._hb),this._hb=setInterval(()=>{if(!(!this.ws||this.ws.readyState!==this.ws.OPEN)){if(!this.alive){try{this.ws.terminate()}catch{}return}this.alive=!1;try{this.ws.ping()}catch{}}},3e4)}_down(){clearInterval(this._hb),this.emit("close"),!this.stopped&&(this.backoff=Math.min(this.backoff*2,15e3),setTimeout(()=>this.connect(),this.backoff))}send(e){return this.ws&&this.ws.readyState===this.ws.OPEN?(this.ws.send(JSON.stringify(e)),!0):!1}sendEnvelope(e){return this.send({type:"envelope",envelope:e})}stop(){this.stopped=!0,clearInterval(this._hb);try{this.ws.close()}catch{}}};import{randomUUID as ar}from"node:crypto";var cr=0;function Ct(s,e,t,r){return{v:1,from:e,to:t,msg_id:ar(),counter:++cr,ts:Date.now(),box:At(s,r)}}function Nt(s,e){return Mt(s,e.box)}import{existsSync as Ur}from"node:fs";le();async function ns({provider:s,workdir:e,resumeSessionId:t,onSessionId:r,model:n}){if(s==="mock")return new Ze({resumeSessionId:t,onSessionId:r});if(s==="codex"){let{CodexSession:o}=await Promise.resolve().then(()=>(Jt(),Ft));return new o({workdir:e,resumeSessionId:t,onSessionId:r,model:n})}if(s==="codebuddy"){let{CodeBuddySession:o}=await Promise.resolve().then(()=>(Wt(),Kt));return new o({workdir:e,resumeSessionId:t,onSessionId:r,model:n})}if(s==="qwen"){let{QwenSession:o}=await Promise.resolve().then(()=>(Xt(),Ht));return new o({workdir:e,resumeSessionId:t,onSessionId:r,model:n})}if(s==="opencode"){let{OpenCodeSession:o}=await Promise.resolve().then(()=>(Vt(),Yt));return new o({workdir:e,resumeSessionId:t,onSessionId:r,model:n})}if(s==="gemini"){let{GeminiSession:o}=await Promise.resolve().then(()=>(Zt(),Qt));return new o({workdir:e,resumeSessionId:t,onSessionId:r,model:n})}if(s==="cursor"){let{CursorSession:o}=await Promise.resolve().then(()=>(rs(),ss));return new o({workdir:e,resumeSessionId:t,onSessionId:r,model:n})}let{query:i}=await import("@anthropic-ai/claude-agent-sdk");return new Qe({query:i,workdir:e,resumeSessionId:t,onSessionId:r,model:n})}function is(s){let e=String(s||"").toLowerCase(),t={structured_tools:!1,structured_diff:!1,reasoning:!1,hot_model_switch:!0,resume:!0,interactive_approval:!1};return e==="codex"?{...t,structured_tools:!0,structured_diff:!0,reasoning:!0}:e==="claude"||e===""?{...t,structured_tools:!0,structured_diff:!0}:e==="qwen"||e==="codebuddy"?{...t,structured_tools:!0,structured_diff:!0,reasoning:!0}:e==="cursor"?{...t,structured_tools:!0,structured_diff:!0}:e==="mock"?{...t,hot_model_switch:!1,resume:!0}:t}function $r(){if(process.env.AGENTPAGER_CLAUDE_BIN)return process.env.AGENTPAGER_CLAUDE_BIN;for(let s of[process.env.HOME+"/.local/bin/claude",process.env.HOME+"/.npm-global/bin/claude"])if(Ur(s))return s;return"claude"}var Qe=class{constructor({query:e,workdir:t,resumeSessionId:r,onSessionId:n,model:i}){this._queue=[],this._waiter=null,this._closed=!1,this._active=null,this._reported=!1,this.onSessionId=n,this._mapper=$();let o=$r(),a=this;async function*l(){for(;!a._closed;){let d=await new Promise(p=>{a._queue.length?p(a._queue.shift()):a._waiter=p});if(d===null)return;yield{type:"user",message:{role:"user",content:d}}}}this.q=e({prompt:l(),options:{pathToClaudeCodeExecutable:o,cwd:t,permissionMode:"default",settingSources:[],...i?{model:i}:{},...r?{resume:r}:{},canUseTool:async(d,p)=>({behavior:"allow",updatedInput:p})}}),this._pump()}async _pump(){try{for await(let e of this.q){!this._reported&&e.session_id&&(this._reported=!0,this.onSessionId?.(e.session_id));let t=this._active;for(let r of this._mapper.onMessage(e))t?.onEvent?t.onEvent(r):r.type==="delta"?t?.onDelta?.(r.text):r.type==="tool_use"&&t?.onToolUse?.(r.tool.name),r.type==="done"&&(this._active=null,t?.resolve?.({done:!0,reason:r.reason}))}}catch(e){let t=this._active;this._active=null,t?.resolve?.({done:!0,interrupted:!0,error:e.message})}this._closed=!0}runTurn({text:e,onDelta:t,onToolUse:r,onEvent:n}){return new Promise(i=>{if(this._active={onDelta:t,onToolUse:r,onEvent:n,resolve:i},this._waiter){let o=this._waiter;this._waiter=null,o(e)}else this._queue.push(e)})}interrupt(){return this.q.interrupt()}setModel(e){return this.q.setModel(e)}setPermissionMode(e){return this.q.setPermissionMode(e)}close(){if(this._closed=!0,this._waiter){let e=this._waiter;this._waiter=null,e(null)}}},Ze=class{constructor({resumeSessionId:e,onSessionId:t}){this.resumed=!!e,t?.(e||"mock-session")}async runTurn({text:e,onDelta:t,onToolUse:r}){if(this._aborted=!1,e&&e.includes("__throw__"))throw new Error("mock provider blew up");t(this.resumed?`echo(resumed): ${e}`:`echo: ${e}`);for(let n=0;n<12&&!this._aborted;n++)await new Promise(i=>setTimeout(i,50));return this._aborted?(t("[mock] interrupted"),{done:!0,interrupted:!0}):(r("Bash"),t("[mock] tool ran (auto-approved)"),{done:!0})}interrupt(){this._aborted=!0}setModel(){}setPermissionMode(){}close(){}};import{openSync as os,writeSync as as,fsyncSync as cs,closeSync as ls,readFileSync as Fr,renameSync as us,existsSync as ds,mkdirSync as Jr}from"node:fs";import{join as tt}from"node:path";var et=tt(oe.DIR,"transcripts"),F=500,Kr=2*F,Wr=3*F,ve=class{constructor(e){Jr(et,{recursive:!0}),this.file=tt(et,`${e}.jsonl`);let t=this._readLines();this.seq=this._lastSeqFrom(t),this._lines=t.length}renameTo(e){let t=tt(et,`${e}.jsonl`);this.file!==t&&ds(this.file)&&us(this.file,t),this.file=t}_readLines(){return ds(this.file)?Fr(this.file,"utf8").trim().split(`
|
|
20
|
+
`).forEach(i=>{i.trim()&&t.add(i.trim())})}catch{}}for(let r of e)V.set("cxreal:"+r.fp,{mtime:r.mtime,item:t.has(r.fp)});Pe=!0}return s.filter(t=>{let r=V.get("cxreal:"+t.fp);return r&&r.item})}function Ps(){if(!Is){Is=!0;try{let s=JSON.parse(z(ut,"utf8"));if(s&&s.v===Rs&&s.files)for(let[e,t]of Object.entries(s.files))V.set(e,t)}catch{}}}function Hn(){if(Pe){Pe=!1;try{let s=ut+".tmp";vn(s,JSON.stringify({v:Rs,files:Object.fromEntries(V)})),Sn(s,ut)}catch{}}}function Y(s,e){let t=V.get(s.fp);if(t&&t.mtime===s.mtime)return t.item;let r=e(s);return V.set(s.fp,{mtime:s.mtime,item:r}),Pe=!0,r}function Xn(s=20,e=0){Ps();let t=[...ft().map(o=>Y(o,pt)),...Wn(Es()).map(o=>Y(o,Cn)),...Oe(As,"chats").map(o=>Y(o,Rn)),...Oe(Ms,"").map(o=>Y(o,Gn)),...Dn(),...Fn(),...Jn()].filter(Boolean).sort((o,a)=>(a.updated_at||0)-(o.updated_at||0));Hn();let r=t.length,n=Math.max(0,e|0),i=t.slice(n,n+s);return{items:i,total:r,offset:n,hasMore:n+i.length<r}}function Yn(s,e,t,r=400){let n=String(s||"");return n.includes("codex")?Nn(e,r):n.includes("qwen")?Pn(e,r):n.includes("codebuddy")?Ln(e,r):n.includes("opencode")?qn(e,r):n.includes("gemini")?Kn(e,r):n.includes("cursor")?$n(e,r):js(e,t,r)}function js(s,e,t=400){let r=M(Te,e||"",s+".jsonl");if(!R(r))return{id:s,rows:[]};let n=$(),i=[];for(let a of P(z(r,"utf8")))if(a.type==="user"&&a.message){let l=a.message.content;if(Array.isArray(l)&&l.some(A=>A&&A.type==="tool_result")){i.push(...n.onMessage(a));continue}let p=Ce(l),u=In(l),_=p&&!C(p)?p.trim():"";(_||u)&&i.push(b.user(_,u||void 0))}else a.type==="assistant"&&a.message?i.push(...n.onMessage(a)):a.type==="result"&&i.push(...n.onMessage(a));let o=de(i);for(let a of o.rows)a.kind==="assistant"&&(a.streaming=!1);return{id:s,rows:o.rows.slice(-t)}}var Te,Ss,As,Ms,re,ne,Cs,Ns,Me,lt,ut,Rs,V,Is,Pe,Le=T(()=>{le();rt();U();fe();Te=M(H(),".claude","projects");Ss=M(H(),".codex","sessions");As=M(H(),".qwen","projects");Ms=M(H(),".codebuddy","projects");re=M(H(),".local","share","opencode","opencode.db");ne=M(H(),".cursor","chats");Cs=s=>s.replace(/<\/?user_query>/g,"").trim(),Ns=s=>/^<user_info>|^<environment|^<additional|^<system/.test(s);Me=M(H(),".gemini","tmp");lt=s=>C(s)||/^<session_context>/.test(s);ut=M(H(),".agentpager","native-cache.json"),Rs=1,V=new Map,Is=!1,Pe=!1});import{readFileSync as Ls,writeFileSync as Ds,mkdirSync as qs,existsSync as Bs}from"node:fs";import{homedir as Us}from"node:os";import{join as ht}from"node:path";import{randomUUID as $s}from"node:crypto";var De=process.env.AGENTPAGER_HOME||ht(Us(),".agentpager"),pe=ht(De,"config.json");function qe(){return Bs(pe)?JSON.parse(Ls(pe,"utf8")):null}function Q(s){return qs(De,{recursive:!0}),Ds(pe,JSON.stringify(s,null,2)),s}function me(){let s=qe();return s||(s={device_id:"device_"+$s().slice(0,12),device_kp:{stub:!0},relay_url:process.env.AGENTPAGER_RELAY||"wss://to50.cn/ap/ws",relay_http:process.env.AGENTPAGER_RELAY_HTTP||"https://to50.cn/ap",binding:null,agents:[]},Q(s))}var oe={DIR:De,FILE:pe};Ue();import{WebSocket as nr}from"ws";import Z from"tweetnacl";var er=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function ae(s){let e=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],t=s.length,r=new Uint8Array((t+8>>6<<6)+64);r.set(s),r[t]=128;let n=t*8,i=new DataView(r.buffer);i.setUint32(r.length-4,n>>>0),i.setUint32(r.length-8,Math.floor(n/4294967296));let o=new Uint32Array(64),a=(p,u)=>p>>>u|p<<32-u;for(let p=0;p<r.length;p+=64){for(let h=0;h<16;h++)o[h]=i.getUint32(p+h*4);for(let h=16;h<64;h++){let k=a(o[h-15],7)^a(o[h-15],18)^o[h-15]>>>3,c=a(o[h-2],17)^a(o[h-2],19)^o[h-2]>>>10;o[h]=o[h-16]+k+o[h-7]+c|0}let[u,_,A,O,y,v,g,w]=e;for(let h=0;h<64;h++){let k=a(y,6)^a(y,11)^a(y,25),c=y&v^~y&g,f=w+k+c+er[h]+o[h]|0,m=a(u,2)^a(u,13)^a(u,22),S=u&_^u&A^_&A,E=m+S|0;w=g,g=v,v=y,y=O+f|0,O=A,A=_,_=u,u=f+E|0}e[0]=e[0]+u|0,e[1]=e[1]+_|0,e[2]=e[2]+A|0,e[3]=e[3]+O|0,e[4]=e[4]+y|0,e[5]=e[5]+v|0,e[6]=e[6]+g|0,e[7]=e[7]+w|0}let l=new Uint8Array(32),d=new DataView(l.buffer);for(let p=0;p<8;p++)d.setUint32(p*4,e[p]>>>0);return l}var ge=(s,e)=>{let t=new Uint8Array(s.length+e.length);return t.set(s),t.set(e,s.length),t};function ye(s,e){s.length>64&&(s=ae(s));let t=new Uint8Array(64);t.set(s);let r=new Uint8Array(64),n=new Uint8Array(64);for(let i=0;i<64;i++)r[i]=t[i]^54,n[i]=t[i]^92;return ae(ge(n,ae(ge(r,e))))}function gt(s,e,t,r){let n=ye(e,s),i=new Uint8Array(r),o=new Uint8Array(0),a=0,l=1;for(;a<r;)o=ye(n,ge(ge(o,t),new Uint8Array([l++]))),i.set(o.subarray(0,Math.min(o.length,r-a)),a),a+=o.length;return i}function yt(s,e){if(s.length!==e.length)return!1;let t=0;for(let r=0;r<s.length;r++)t|=s[r]^e[r];return t===0}var ee=s=>new TextEncoder().encode(s),wt=(...s)=>{let e=0;for(let n of s)e+=n.length;let t=new Uint8Array(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return t},ce="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function te(s){let e="";for(let t=0;t<s.length;t+=3){let r=s[t],n=t+1<s.length?s[t+1]:0,i=t+2<s.length?s[t+2]:0;e+=ce[r>>2]+ce[(r&3)<<4|n>>4],e+=t+1<s.length?ce[(n&15)<<2|i>>6]:"=",e+=t+2<s.length?ce[i&63]:"="}return e}function X(s){let e=s.replace(/=+$/,""),t=new Uint8Array(e.length*6>>3),r=0,n=0,i=0;for(let o of e)n=n<<6|ce.indexOf(o),r+=6,r>=8&&(r-=8,t[i++]=n>>r&255);return t}function tr(s){let e=s.map(r=>r instanceof Uint8Array?r:ee(String(r))),t=[];for(let r of e){let n=new Uint8Array(4);new DataView(n.buffer).setUint32(0,r.length,!0),t.push(n,r)}return wt(...t)}var sr="ABCDEFGHJKMNPQRSTUVWXYZ23456789";function xt(s=8){let e="";for(;e.length<s;){let t=Z.randomBytes(1)[0];t<248&&(e+=sr[t%31])}return e}function rr(s){let e="";for(let t of s)e+=t.toString(16).padStart(2,"0");return e}function bt(s){return rr(ae(ee("agentpager-psid|"+s))).slice(0,32)}function vt(){return Z.box.keyPair()}function St(s,e){let t=Z.scalarMult(s,e);if(t.every(r=>r===0))throw new Error("insecure_ecdh: low-order/zero peer key");return t}function It({psid:s,phone_id:e,device_id:t,epk_phone:r,epk_device:n}){return tr([s,e,t,r,n])}function $e(s,e,t){return ye(ee("agentpager-pair|"+s),wt(e,ee("|"+t)))}function kt(s,e){return yt(s,e)}function Et(s,e){return gt(s,e,ee("agentpager-chan"),32)}function At(s,e){let t=Z.randomBytes(24),r=Z.secretbox(ee(JSON.stringify(e)),t,s);return{n:te(t),c:te(r)}}function Mt(s,e){let t=Z.secretbox.open(X(e.c),X(e.n),s);return t?JSON.parse(new TextDecoder().decode(t)):null}function Tt(s,{onCode:e,timeoutMs:t=6e5}={}){return new Promise((r,n)=>{let i=xt();e&&e(i);let o=bt(i),a=vt(),l=new nr(`${s.relay_url}?role=device&id=${s.device_id}`),d=setTimeout(()=>{try{l.close()}catch{}n(new Error("pair_timeout"))},t),p=null,u=null,_=!1,A=!1,O=null,y=h=>{clearTimeout(d);try{l.close()}catch{}h?n(h):r(s)},v=()=>It({psid:o,phone_id:p.phone_id,device_id:s.device_id,epk_phone:p.epk,epk_device:a.publicKey});l.on("open",()=>l.send(JSON.stringify({type:"pair_offer",psid:o,device_id:s.device_id,epk:te(a.publicKey)}))),l.on("message",h=>{let k;try{k=JSON.parse(h.toString())}catch{return}if(k.type==="pair_peer"){p={phone_id:k.phone_id,epk:X(k.epk)};let c=v();try{u=Et(St(a.secretKey,p.epk),c)}catch(f){return y(new Error("pair_failed: "+f.message))}l.send(JSON.stringify({type:"pair_mac",psid:o,mac:te($e(i,c,"device"))})),_=!0,O&&g(O),w()}else if(k.type==="pair_mac"){if(!p){O=k.mac;return}g(k.mac)}}),l.on("error",h=>y(h));function g(h){if(A=kt(X(h),$e(i,v(),"phone")),!A)return y(new Error("pair_failed: mac_mismatch (wrong code or MITM)"));w()}function w(){_&&A&&u&&(s.binding={phone_id:p.phone_id,paired_at:Date.now(),chan_key:te(u)},Q(s),y(null))}})}import{hostname as Vn}from"node:os";import{WebSocket as ir}from"ws";import{EventEmitter as or}from"node:events";var we=class extends or{constructor({relay_url:e,device_id:t}){super(),this.url=`${e}?role=device&id=${t}`,this.device_id=t,this.ws=null,this.backoff=500,this.alive=!1,this.stopped=!1}connect(){return this.ws=new ir(this.url),this.ws.on("open",()=>{this.alive=!0,this.backoff=500,this.emit("open"),this._heartbeat()}),this.ws.on("message",e=>{let t;try{t=JSON.parse(e.toString())}catch{return}t.type==="envelope"?this.emit("envelope",t.envelope):t.type==="pair_result"?this.emit("pair_result",t):t.type==="delivery.expired"?this.emit("expired",t.msg_id):t.type==="paired"?this.emit("paired",t):this.emit("control",t)}),this.ws.on("pong",()=>{this.alive=!0}),this.ws.on("close",()=>{this._down()}),this.ws.on("error",e=>{this.emit("error",e)}),this}_heartbeat(){clearInterval(this._hb),this._hb=setInterval(()=>{if(!(!this.ws||this.ws.readyState!==this.ws.OPEN)){if(!this.alive){try{this.ws.terminate()}catch{}return}this.alive=!1;try{this.ws.ping()}catch{}}},3e4)}_down(){clearInterval(this._hb),this.emit("close"),!this.stopped&&(this.backoff=Math.min(this.backoff*2,15e3),setTimeout(()=>this.connect(),this.backoff))}send(e){return this.ws&&this.ws.readyState===this.ws.OPEN?(this.ws.send(JSON.stringify(e)),!0):!1}sendEnvelope(e){return this.send({type:"envelope",envelope:e})}stop(){this.stopped=!0,clearInterval(this._hb);try{this.ws.close()}catch{}}};import{randomUUID as ar}from"node:crypto";var cr=0;function Ct(s,e,t,r){return{v:1,from:e,to:t,msg_id:ar(),counter:++cr,ts:Date.now(),box:At(s,r)}}function Nt(s,e){return Mt(s,e.box)}import{existsSync as Ur}from"node:fs";le();async function ns({provider:s,workdir:e,resumeSessionId:t,onSessionId:r,model:n}){if(s==="mock")return new Ze({resumeSessionId:t,onSessionId:r});if(s==="codex"){let{CodexSession:o}=await Promise.resolve().then(()=>(Jt(),Ft));return new o({workdir:e,resumeSessionId:t,onSessionId:r,model:n})}if(s==="codebuddy"){let{CodeBuddySession:o}=await Promise.resolve().then(()=>(Wt(),Kt));return new o({workdir:e,resumeSessionId:t,onSessionId:r,model:n})}if(s==="qwen"){let{QwenSession:o}=await Promise.resolve().then(()=>(Xt(),Ht));return new o({workdir:e,resumeSessionId:t,onSessionId:r,model:n})}if(s==="opencode"){let{OpenCodeSession:o}=await Promise.resolve().then(()=>(Vt(),Yt));return new o({workdir:e,resumeSessionId:t,onSessionId:r,model:n})}if(s==="gemini"){let{GeminiSession:o}=await Promise.resolve().then(()=>(Zt(),Qt));return new o({workdir:e,resumeSessionId:t,onSessionId:r,model:n})}if(s==="cursor"){let{CursorSession:o}=await Promise.resolve().then(()=>(rs(),ss));return new o({workdir:e,resumeSessionId:t,onSessionId:r,model:n})}let{query:i}=await import("@anthropic-ai/claude-agent-sdk");return new Qe({query:i,workdir:e,resumeSessionId:t,onSessionId:r,model:n})}function is(s){let e=String(s||"").toLowerCase(),t={structured_tools:!1,structured_diff:!1,reasoning:!1,hot_model_switch:!0,resume:!0,interactive_approval:!1};return e==="codex"?{...t,structured_tools:!0,structured_diff:!0,reasoning:!0}:e==="claude"||e===""?{...t,structured_tools:!0,structured_diff:!0}:e==="qwen"||e==="codebuddy"?{...t,structured_tools:!0,structured_diff:!0,reasoning:!0}:e==="cursor"?{...t,structured_tools:!0,structured_diff:!0}:e==="mock"?{...t,hot_model_switch:!1,resume:!0}:t}function $r(){if(process.env.AGENTPAGER_CLAUDE_BIN)return process.env.AGENTPAGER_CLAUDE_BIN;for(let s of[process.env.HOME+"/.local/bin/claude",process.env.HOME+"/.npm-global/bin/claude"])if(Ur(s))return s;return"claude"}var Qe=class{constructor({query:e,workdir:t,resumeSessionId:r,onSessionId:n,model:i}){this._queue=[],this._waiter=null,this._closed=!1,this._active=null,this._reported=!1,this.onSessionId=n,this._mapper=$();let o=$r(),a=this;async function*l(){for(;!a._closed;){let d=await new Promise(p=>{a._queue.length?p(a._queue.shift()):a._waiter=p});if(d===null)return;yield{type:"user",message:{role:"user",content:d}}}}this.q=e({prompt:l(),options:{pathToClaudeCodeExecutable:o,cwd:t,permissionMode:"default",settingSources:[],...i?{model:i}:{},...r?{resume:r}:{},canUseTool:async(d,p)=>({behavior:"allow",updatedInput:p})}}),this._pump()}async _pump(){try{for await(let e of this.q){!this._reported&&e.session_id&&(this._reported=!0,this.onSessionId?.(e.session_id));let t=this._active;for(let r of this._mapper.onMessage(e))t?.onEvent?t.onEvent(r):r.type==="delta"?t?.onDelta?.(r.text):r.type==="tool_use"&&t?.onToolUse?.(r.tool.name),r.type==="done"&&(this._active=null,t?.resolve?.({done:!0,reason:r.reason}))}}catch(e){let t=this._active;this._active=null,t?.resolve?.({done:!0,interrupted:!0,error:e.message})}this._closed=!0}runTurn({text:e,onDelta:t,onToolUse:r,onEvent:n}){return new Promise(i=>{if(this._active={onDelta:t,onToolUse:r,onEvent:n,resolve:i},this._waiter){let o=this._waiter;this._waiter=null,o(e)}else this._queue.push(e)})}interrupt(){return this.q.interrupt()}setModel(e){return this.q.setModel(e)}setPermissionMode(e){return this.q.setPermissionMode(e)}close(){if(this._closed=!0,this._waiter){let e=this._waiter;this._waiter=null,e(null)}}},Ze=class{constructor({resumeSessionId:e,onSessionId:t}){this.resumed=!!e,t?.(e||"mock-session")}async runTurn({text:e,onDelta:t,onToolUse:r}){if(this._aborted=!1,e&&e.includes("__throw__"))throw new Error("mock provider blew up");t(this.resumed?`echo(resumed): ${e}`:`echo: ${e}`);for(let n=0;n<12&&!this._aborted;n++)await new Promise(i=>setTimeout(i,50));return this._aborted?(t("[mock] interrupted"),{done:!0,interrupted:!0}):(r("Bash"),t("[mock] tool ran (auto-approved)"),{done:!0})}interrupt(){this._aborted=!0}setModel(){}setPermissionMode(){}close(){}};import{openSync as os,writeSync as as,fsyncSync as cs,closeSync as ls,readFileSync as Fr,renameSync as us,existsSync as ds,mkdirSync as Jr}from"node:fs";import{join as tt}from"node:path";var et=tt(oe.DIR,"transcripts"),F=500,Kr=2*F,Wr=3*F,ve=class{constructor(e){Jr(et,{recursive:!0}),this.file=tt(et,`${e}.jsonl`);let t=this._readLines();this.seq=this._lastSeqFrom(t),this._lines=t.length}renameTo(e){let t=tt(et,`${e}.jsonl`);this.file!==t&&ds(this.file)&&us(this.file,t),this.file=t}_readLines(){return ds(this.file)?Fr(this.file,"utf8").trim().split(`
|
|
21
21
|
`).filter(Boolean):[]}_lastSeqFrom(e){for(let t=e.length-1;t>=0;t--)try{return JSON.parse(e[t]).seq||0}catch{}return 0}append(e){let t=++this.seq,r=JSON.stringify({seq:t,ts:Date.now(),payload:e})+`
|
|
22
22
|
`,n=os(this.file,"a");try{as(n,r),cs(n)}finally{ls(n)}return++this._lines>Wr&&this._compact(),t}_compact(){let e=this._readLines().slice(-Kr),t=`${this.file}.tmp`,r=os(t,"w");try{as(r,e.join(`
|
|
23
23
|
`)+`
|
package/package.json
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agentpager-cli",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "AgentPager daemon — 手机遥控你电脑上的编程 Agent(Claude Code/Codex/Gemini 等 7 家)。配对后在微信小程序里实时查看会话、续聊、语音输入、发图。",
|
|
6
6
|
"bin": {
|
|
7
|
-
"agentpager": "dist/cli.js"
|
|
7
|
+
"agentpager": "dist/cli.js",
|
|
8
|
+
"agentpager-cli": "dist/cli.js"
|
|
8
9
|
},
|
|
9
10
|
"scripts": {
|
|
10
11
|
"test:crypto": "node test/crypto.test.mjs",
|