agent-afk 2.6.0 → 2.6.1
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.mjs +4 -4
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -1693,8 +1693,8 @@ ${h}`:p.prompt},model:p.model??this.ctx.defaultSubagentModel??this.ctx.defaultMo
|
|
|
1693
1693
|
`),m=[l];for(let f of p)m.push(u+" "+fe(f,r)+" "+u);if(t!==void 0){let f=V(d.dim(t),r).split(`
|
|
1694
1694
|
`);for(let h of f)m.push(u+" "+fe(h,r)+" "+u)}return m.push(c),m.join(`
|
|
1695
1695
|
`)}var Dk={plan:d.plan,status:d.info,checkpoint:d.success,diagnosis:d.warning},Lk={plan:"PLAN",status:"STATUS",checkpoint:"\u2705 CHECKPOINT",diagnosis:"DIAGNOSIS"};function pt(e){let t=Array.isArray(e.body)?e.body:e.body.split(`
|
|
1696
|
-
`);if(e.kind==="user")return Nk(t);let n=e.title??Lk[e.kind];return Fk(e.kind,n,t)}function Nk(e){let
|
|
1697
|
-
`));let
|
|
1696
|
+
`);if(e.kind==="user")return Nk(t,e.leftPad??0);let n=e.title??Lk[e.kind];return Fk(e.kind,n,t)}function Nk(e,t=0){let n=Math.max(20,q()-4-t),r=[];for(let a of e)r.push(...V(lt(a),n).split(`
|
|
1697
|
+
`));let o=d.user("\u2502"),s=" ".repeat(t);return r.map(a=>s+o+" "+a).join(`
|
|
1698
1698
|
`)}function Fk(e,t,n){let r=Dk[e],o=n.map(lt),s=` ${t} `,a=r.bold(s),i=Math.max(U(t)+4,...o.map(g=>U(g))),l=Math.max(40,i)+4,c=Math.min(l,Math.min(q()-4,100));c=Math.min(c,Yr());let u="\u2500".repeat(c+4-1-U(s)),p=r("\u256D\u2500")+a+r(u+"\u256E"),m=r("\u2570"+"\u2500".repeat(c+4)+"\u256F"),f=r("\u2502"),h=[p];for(let g of o){let y=V(g,c).split(`
|
|
1699
1699
|
`);for(let k of y)h.push(f+" "+fe(k,c)+" "+f)}return h.push(m),h.join(`
|
|
1700
1700
|
`)}function re(e){let t=Math.min(q(),120);if(e===void 0)return d.dim("\u2500".repeat(t));let n=d.dim("\u2500\u2500")+" "+d.bold(e)+" ",r="\u2500\u2500 "+e+" ",o=Math.max(0,t-U(r));return n+d.dim("\u2500".repeat(o))}var Jr=new Set;function $n(e){return Jr.add(e),()=>{Jr.delete(e)}}async function lu(){await Promise.all([...Jr].map(e=>e())),Jr.clear()}import{readFileSync as Uk,writeFileSync as jk,existsSync as Us,mkdirSync as Bk,readdirSync as Hk,statSync as Wk}from"fs";import{join as cu,basename as Kk}from"path";function js(){return Gi(),pn()}function uu(e){return cu(js(),`${e}.json`)}function Xr(e,t){let n=js();Us(n)||Bk(n,{recursive:!0});let r=t??e.sessionId??`session-${Date.now()}`,o={sessionId:e.sessionId,model:e.model,startedAt:e.sessionStartTime,savedAt:Date.now(),totalTurns:e.totalTurns,totalCostUsd:e.totalCostUsd,totalTokens:e.totalTokens,totalDurationMs:e.totalDurationMs,turns:e.turns},s=uu(r);return jk(s,JSON.stringify(o,null,2)),s}function Bs(e){let t=e.includes("/")?e:uu(e);if(Us(t))try{let n=Uk(t,"utf-8");return JSON.parse(n)}catch{return}}function du(){let e=js();if(!Us(e))return[];let t=[];for(let n of Hk(e)){if(!n.endsWith(".json"))continue;let r=cu(e,n);try{if(!Wk(r).isFile())continue;let s=Bs(r);if(!s||typeof s.savedAt!="number"||typeof s.model!="string")continue;t.push({path:r,id:Kk(n,".json"),sessionId:s.sessionId,model:s.model,startedAt:s.startedAt,savedAt:s.savedAt,totalTurns:s.totalTurns,totalCostUsd:s.totalCostUsd})}catch{}}return t.sort((n,r)=>r.savedAt-n.savedAt),t}import*as zd from"node:readline";function pu(e){let t=Math.max(0,Math.min(1,e.ratio)),n=t>.8?d.error:t>.5?d.warning:d.meta,r=20,o=Math.round(t*r),s=r-o,a="["+"\u2588".repeat(o)+"\u2591".repeat(s)+"]",i=Math.round(t*100)+"%",l="";e.used!==void 0&&e.limit!==void 0&&(l=N(e.used)+"/"+N(e.limit));let c=l?`${a} ${i} ${l}`:`${a} ${i}`,u=`${a} ${i}`,p=`ctx ${i}`,m=e.sparkline?d.meta(e.sparkline)+" ":"",f=e.sparkline?U(e.sparkline)+1:0,h=Math.max(0,e.width-f);if(U(c)<=h&&h>90)return m+n(c);if(U(u)<=h&&h>32)return m+n(u);if(U(p)<=h)return m+n(p);if(e.width>0){let g=m+n(p);return ae(g,e.width)}return n(i)}import Gk from"chalk";var Ws=new Map;function mu(e,t){let n=Ws.get(e);if(n){if(n.glyph===t.glyph&&n.color===t.color&&n.inFlightVerb===t.inFlightVerb)return;throw new Error(`Trusted skill "${e}" already registered with different config`)}Ws.set(e,t),jc(e)}function Qr(e){return Ws.get(e)}function zk(e){return(e/1e3).toFixed(1)+"s"}function fu(e,t){let n=Qr(e.skillName),r=zk(e.durationMs);if(!n){let s=`[${e.skillName} \xB7 ${r}]`;return Hs(s,t?.columns)}if(t?.isTTY!==!1){let s;if(e.claimsTotal!==void 0){let i=e.claimsTotal===e.claimsConfirmed&&e.claimsRefuted===void 0&&e.claimsInconclusive===void 0,l;if(i)l=`${e.claimsTotal} claims \xB7 all confirmed`;else{let c=`${e.claimsTotal} claims`;e.claimsConfirmed!==void 0&&(c+=` \xB7 ${e.claimsConfirmed} confirmed`),e.claimsRefuted!==void 0&&(c+=` \xB7 ${e.claimsRefuted} refuted`),e.claimsInconclusive!==void 0&&(c+=` \xB7 ${e.claimsInconclusive} inconclusive`),l=c}s=`${n.glyph} ${e.skillName} \xB7 ${l} \xB7 ${r}`}else s=`${n.glyph} ${e.skillName} \xB7 ${r}`;let a=Gk.hex(n.color)(s);return Hs(a,t?.columns)}else{let s;if(e.claimsTotal!==void 0){let a=e.claimsConfirmed??0;s=`[${e.skillName} \xB7 ${a}/${e.claimsTotal} confirmed \xB7 ${r}]`}else s=`[${e.skillName} \xB7 ${r}]`;return Hs(s,t?.columns)}}function Hs(e,t){return t!==void 0&&U(e)>t?ae(e,t):e}function gu(e){let t=Qr(e);return t?`${t.glyph} ${t.inFlightVerb}`:e}var Zr=class{stream;force;throttleMs;started=!1;lastRepaint=0;lastFields=null;resizeUnsub=null;lastPaintedRow=null;extraRows=0;constructor(t={}){this.stream=t.stream??process.stdout,this.force=t.force??!1,this.throttleMs=t.throttleMs??100}get enabled(){return this.force||!!this.stream.isTTY}start(){if(this.started||!this.enabled)return;this.started=!0,this.lastRepaint=0;let t=this.currentRows();this.stream.write("\x1B[s"),this.writeScrollRegion(t),this.stream.write("\x1B[u"),this.resizeUnsub===null&&(this.resizeUnsub=dt.subscribe(()=>{this.onResize()}))}onResize(){if(!this.started||!this.enabled)return;let t=this.currentRows();this.stream.write("\x1B[s"),this.lastPaintedRow!==null&&this.lastPaintedRow!==this.paintRow(t)&&(this.stream.write(`\x1B[${this.lastPaintedRow};1H`),this.stream.write("\x1B[2K")),this.writeScrollRegion(t),this.stream.write("\x1B[u"),this.flush()}repaint(t){if(!this.enabled||!this.started){this.lastFields=t;return}let n=Date.now();if(n-this.lastRepaint<this.throttleMs){this.lastFields=t;return}this.lastRepaint=n,this.lastFields=t;let r=this.currentRows();this.stream.write("\x1B[s"),this.stream.write(`\x1B[${this.paintRow(r)};1H`),this.stream.write("\x1B[2K"),this.stream.write(this.formatLine(t)),this.stream.write("\x1B[u"),this.lastPaintedRow=this.paintRow(r)}flush(){this.lastRepaint=0,this.lastFields&&this.repaint(this.lastFields)}setExtraRows(t){if(this.extraRows=t,this.started&&this.enabled){let n=this.currentRows();this.stream.write("\x1B[s"),this.writeScrollRegion(n),this.stream.write("\x1B[u"),this.flush()}}rearm(){if(!this.started||!this.enabled)return;let t=this.currentRows();this.stream.write("\x1B[s"),this.writeScrollRegion(t),this.stream.write("\x1B[u"),this.flush()}stop(){if(this.resizeUnsub!==null&&(this.resizeUnsub(),this.resizeUnsub=null),!this.started||!this.enabled){this.started=!1;return}let t=this.currentRows();this.stream.write("\x1B[s"),this.stream.write(`\x1B[${this.lastPaintedRow??this.paintRow(t)};1H`),this.stream.write("\x1B[2K"),this.stream.write("\x1B[r"),this.stream.write("\x1B[u"),this.started=!1,this.lastRepaint=0,this.lastPaintedRow=null}formatLine(t){let n=[],r=Math.max(4,(this.stream.columns??80)-2);if(t.trustedSkillVerifying&&n.push(gu(t.trustedSkillVerifying)),n.push(d.brand(t.model)),t.planMode&&n.push(d.warning("\u25CF plan")),t.contextPct!==void 0){let s=pu({ratio:t.contextPct,used:t.contextUsedTokens,limit:t.contextLimit,sparkline:t.contextSparkline,width:r});n.push(s)}t.cost!==void 0&&n.push(d.meta(`$${t.cost.toFixed(2)}`)),t.tokens!==void 0&&n.push(d.meta(`${Vk(t.tokens)} tok`));let o=n.join(d.dim(" \xB7 "));return ae(o,r)}currentRows(){let t=this.stream.rows;return typeof t=="number"&&t>0?t:24}paintRow(t){return t>1?t:1}writeScrollRegion(t){let n=1+this.extraRows;if(t>n){this.stream.write(`\x1B[1;${t-n}r`);return}this.stream.write("\x1B[r")}};function Vk(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`}var Ae=new Map,At=new Map;function Z(e){if(Ae.has(e.name))throw new Error(`Slash command already registered: ${e.name}`);Ae.set(e.name,e);for(let t of e.aliases??[]){if(At.has(t)||Ae.has(t))throw new Error(`Slash alias collides: ${t}`);At.set(t,e.name)}}function mt(e){if(Ae.has(e.name)){for(let[t,n]of At.entries())n===e.name&&At.delete(t);Ae.delete(e.name)}Z(e)}function hu(){Ae.clear(),At.clear()}function Xe(){return[...Ae.values()].sort((e,t)=>e.name.localeCompare(t.name))}function yu(){let e=[];for(let[t,n]of At.entries()){let r=Ae.get(n);r&&e.push({alias:t,canonical:n,summary:r.summary})}return e.sort((t,n)=>t.alias.localeCompare(n.alias))}function qk(e){if(Ae.has(e))return Ae.get(e);let t=At.get(e);return t?Ae.get(t):void 0}function Yk(e,t){let n=Array.from({length:e.length+1},()=>new Array(t.length+1).fill(0));for(let r=0;r<=e.length;r++)n[r][0]=r;for(let r=0;r<=t.length;r++)n[0][r]=r;for(let r=1;r<=e.length;r++)for(let o=1;o<=t.length;o++){let s=e[r-1]===t[o-1]?0:1;n[r][o]=Math.min(n[r-1][o]+1,n[r][o-1]+1,n[r-1][o-1]+s)}return n[e.length][t.length]}function Jk(e,t=3){let n;for(let r of Ae.keys()){let o=Yk(e,r);o<=t&&(n===void 0||o<n.dist)&&(n={name:r,dist:o})}return n?.name}function Xk(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.indexOf(" ");return n===-1?{name:t,args:""}:{name:t.slice(0,n),args:t.slice(n+1).trim()}}async function ku(e,t){let n=Xk(e);if(n===null)return{handled:!1};let r=qk(n.name);if(!r){let s=Jk(n.name);return s?t.out.warn(`Unknown command: ${n.name} (did you mean ${s}?)`):t.out.warn(`Unknown command: ${n.name} (type /help for commands)`),{handled:!0,result:"continue"}}let o=await r.handler(t,n.args);return o==="forward"?{handled:!1}:{handled:!0,result:o}}import Zk from"ora";function bu(e){return{totalTurns:0,totalCostUsd:0,totalTokens:0,totalDurationMs:0,sessionStartTime:Date.now(),turnCosts:[],turnTokens:[],turns:[],model:e,planMode:!1}}function wu(e){e.totalTurns=0,e.totalCostUsd=0,e.totalTokens=0,e.totalDurationMs=0,e.sessionStartTime=Date.now(),e.turnCosts.length=0,e.turnTokens.length=0,e.turns.length=0,delete e.sessionId}function eo(e,t,n,r){let o=r?.totalCostUsd??0,s=r?.durationMs??0,a=Number(r?.usage?.input_tokens??0),i=Number(r?.usage?.output_tokens??0),l=a,c=i,u=Number(r?.usage?.cache_read_input_tokens??0)+Number(r?.usage?.cache_creation_input_tokens??0),p=r?.usage?.iterations;if(Array.isArray(p)&&p.length>0){let f=p[p.length-1];if(f&&typeof f=="object"){let h=f;l=Number(h.input_tokens??0),c=Number(h.output_tokens??0),u=Number(h.cache_read_input_tokens??0)+Number(h.cache_creation_input_tokens??0)}}e.totalTurns+=1,e.totalCostUsd+=o,e.totalDurationMs+=s,e.totalTokens+=a+i,e.turnCosts.push(o),e.turnTokens.push({input:l,output:c,cache:u}),r?.sessionId&&!e.sessionId&&(e.sessionId=String(r.sessionId));let m={user:t,assistant:n,timestamp:Date.now(),costUsd:o,durationMs:s,inputTokens:a,outputTokens:i};return e.turns.push(m),m}function Su(e,t=5){if(e.length===0)return"";let n=e.slice(-t),r=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"];return n.map(o=>{let s=Math.max(0,Math.min(1,o)),a=Math.min(7,Math.floor(s*8));return r[a]}).join("")}var to={stream:process.stdout,hideCursor:!1,discardStdin:!1};function Ks(e,t){if(t?.getRatio()!==void 0)return t.getRatio();let n=e.turnTokens[e.turnTokens.length-1];if(!n)return 0;let r=n.input+n.output+n.cache;return Math.min(1,r/Fe(e.model))}function On(e,t){let n=Ks(e,t),r=Fe(e.model),o,s=t?.getDetail();if(s!==void 0)o=s.used;else{let i=e.turnTokens[e.turnTokens.length-1];i&&(o=i.input+i.output+i.cache)}let a;if(e.turnTokens.length>=2){let i=e.turnTokens.map(c=>(c.input+c.output+c.cache)/r),l=Su(i,5);l.length>0&&(a=l)}return{model:e.model,cost:e.totalCostUsd,tokens:e.totalTokens,contextPct:n,contextLimit:r,contextUsedTokens:o,contextSparkline:a,planMode:e.planMode}}var eb={name:"/exit",aliases:["/quit"],summary:"Exit the session",async handler(){return"exit"}},tb={name:"/clear",summary:"Clear conversation history",async handler(e){try{await e.session.reset(),e.ui.clearScreen(),wu(e.stats),e.ledger?.clear(),e.out.success("Conversation history cleared.")}catch(t){e.out.error(t instanceof Error?t.message:"Unknown error")}return"continue"}},nb={name:"/compact",summary:"Compact history (summarize older messages)",async handler(e){let t=Zk({text:d.meta("Summarizing earlier turns..."),...to}).start();try{let n=await e.session.compact();if(t.stop(),n.compacted){let r=n.tokensSavedEstimate?` (~${n.tokensSavedEstimate} input tokens saved)`:"";e.out.success(`Compacted ${n.messagesBefore} \u2192 ${n.messagesAfter} messages${r}.`)}else{let r=n.reason??"unknown";r==="aborted"?e.out.info("Compaction cancelled."):r.startsWith("summarization-failed")?e.out.error(`Compaction failed: ${r}. History unchanged.`):e.out.info(`Nothing to compact (${r}).`)}}catch(n){t.stop(),e.out.error(n instanceof Error?n.message:"Unknown error")}return"continue"}},rb={name:"/help",summary:"Show this help",async handler(e){let t=Xe(),n=t.reduce((r,o)=>Math.max(r,o.name.length),0)+2;e.out.line(),e.out.line(d.bold(d.brand("Commands"))),e.out.line(re());for(let r of t){let o=r.usage??r.name,s=" ".repeat(Math.max(0,n-o.length));e.out.line(` ${d.warning(o)}${s} ${d.dim(r.summary)}`)}return e.out.line(),e.out.line(d.dim(" Tip: Ctrl+C interrupts a running turn; a second press exits.")),e.out.line(),"continue"}},vu=[eb,tb,nb,rb];function Gs(e,t=30){return!e||e.length===0?d.dim("(none)"):e.length<=t?e.join(", "):`${e.slice(0,t).join(", ")}, ${d.dim(`+${e.length-t} more`)}`}function _e(e,t){return` ${d.label(e.padEnd(16))} ${t}`}function no(e){let t=[];t.push(" "+re("Session Debug")),e.sessionId&&t.push(_e("session",e.sessionId)),e.model&&t.push(_e("model",e.model)),e.permissionMode&&t.push(_e("permission",e.permissionMode)),e.cwd&&t.push(_e("cwd",e.cwd)),e.claudeCodeVersion&&t.push(_e("sdk",`v${e.claudeCodeVersion}`)),e.apiKeySource&&t.push(_e("api key",e.apiKeySource)),e.outputStyle&&t.push(_e("output style",e.outputStyle));let n=e.tools?.length??0;t.push(_e(`tools (${n})`,Gs(e.tools)));let r=e.mcpServers??[],o=r.length?r.map(c=>`${c.name}[${c.status}]`).join(", "):d.dim("(none)");t.push(_e(`mcp (${r.length})`,o));let s=e.skills?.length??0;t.push(_e(`skills (${s})`,Gs(e.skills)));let a=e.plugins?.length??0,i=a?(e.plugins??[]).map(c=>c.name).join(", "):d.dim("(none)");t.push(_e(`plugins (${a})`,i));let l=e.slashCommands?.length??0;return t.push(_e(`slash (${l})`,Gs(e.slashCommands))),t.push(" "+re()),t.join(`
|
|
@@ -1802,7 +1802,7 @@ _ended: ${new Date().toISOString()}_
|
|
|
1802
1802
|
return "no"
|
|
1803
1803
|
end try
|
|
1804
1804
|
`;return new Promise(r=>{let o=rp("osascript",["-e",n],{stdio:["ignore","pipe","pipe"]}),s="",a="";o.stdout?.on("data",i=>{s+=i.toString("utf8")}),o.stderr?.on("data",i=>{a+=i.toString("utf8")}),o.on("error",()=>r({ok:!1,exitCode:null,stderr:a})),o.on("close",i=>{r({ok:i===0&&s.trim()==="ok",exitCode:i,stderr:a})})})}function jS(e){return'"'+e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'}function BS(e){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71?"image/png":e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?"image/jpeg":e.length>=4&&e[0]===71&&e[1]===73&&e[2]===70&&e[3]===56?"image/gif":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":null}import HS from"chalk";import WS from"string-width";function KS(e,t){if(t<=0)return"";let n=0;for(let r=0;r<e.length;r++)if(n+=WS(e[r]),n>t)return e.slice(0,r)+d.dim("\u2026");return e}function ap(e,t,n,r){let o=t?">":" ",s=e.value,a=e.summary?` ${e.summary}`:"",i=`${s}${a}`,l=KS(i,n-4),c=` ${o} ${l}`,u=r==="flag"?d.warning:d.meta;return t?HS.inverse(d.user(c)):u(c)}import gi from"string-width";function Wn(e){let{buffer:t,promptText:n,isTTY:r}=e;if(!r)return n+t;let o=e.terminalWidth??q(),s=t.includes(`
|
|
1805
|
-
`),
|
|
1805
|
+
`),a=gi(Et(n)),i=a+gi(Et(t))>=o-2;return!s&&!i?n+t:pt({kind:"user",body:t,leftPad:Math.max(0,a-2)})}function hi(e,t,n){let r=n||80,o=e.split(`
|
|
1806
1806
|
`),s=0;for(let a=0;a<o.length;a++){let i=Et(o[a]),l=(a===0?t:0)+gi(i);s+=Math.max(1,Math.ceil(l/r))}return Math.max(0,s-1)}var GS="\x1B[?2004h",zS="\x1B[?2004l";function lp(e,t){let n=e.isRaw;e.setRawMode(!0),e.resume(),t.write(GS);let r=!1;return{restore(){if(!r){r=!0;try{t.write(zS)}catch{}try{e.setRawMode(n)}catch{}}}}}function yi(e,t){let n=e.slice(0,t);if(/^\/[A-Za-z_-]*$/.test(n))return{kind:"slash",query:n.slice(1)};let r=n.split(/\s+/),o=r[r.length-1]??"";if(o.startsWith("@")&&/^@[^\s]*$/.test(o))return{kind:"file",query:o.slice(1)};let s=/^\/([A-Za-z][A-Za-z0-9_:-]*)\s+(?:.*\s)?--([a-z0-9-]*)$/.exec(n);if(s){let a=s[1],i=s[2],l=Xe().find(c=>c.name===`/${a}`);if(l?.flags&&l.flags.length>0)return{kind:"flag",command:a,query:i}}return null}function cp(e){let n=Xe().filter(s=>s.name.slice(1).startsWith(e)).map(s=>({value:s.name,summary:s.summary})),r=yu().filter(s=>s.alias.slice(1).startsWith(e)).map(s=>({value:s.alias,summary:s.summary}));return[...n,...r].sort((s,a)=>s.value.localeCompare(a.value)).slice(0,20)}function up(e,t=process.cwd()){return Qd(e,t).slice(0,20).map(n=>({value:n}))}function ki(e,t){let n=Xe().find(s=>s.name===`/${e}`);if(!n?.flags||n.flags.length===0)return[];let r=t.startsWith("--")?t.slice(2):t;return n.flags.filter(s=>(s.startsWith("--")?s.slice(2):s).startsWith(r)).map(s=>({value:s})).sort((s,a)=>s.value.localeCompare(a.value)).slice(0,20)}async function pp(e){let t=process.stdin,n=process.stdout,r=lp(t,n);VS(t);let o=e.promptFn(),s=dp(Et(o)),a=null,i=null;try{return await new Promise((l,c)=>{let u=G.seed(e.initialBuffer??""),p=!1,m=[],f=0,h=null,g=0,y=0,k=!1,b=!1,v=0,I=0,R=0,x=null,E=[],w=6,P=0,C=!1,A=8,_={has:F=>Xe().some(S=>S.name===`/${F}`)},T=()=>{if((R>0||I>0)&&n.write(be.cursorUp(R+I)),n.write("\r"),n.write(be.eraseDown),E.length>0)n.write(tp(E)+`
|
|
1807
1807
|
`),R=1;else if(x!==null){let ce=x;x=null,n.write(ce+`
|
|
1808
1808
|
`),R=1}else R=0;n.write(o+pi(u.buffer,_)),h=yi(u.buffer,u.cursor),h?(h.kind==="slash"?m=cp(h.query):h.kind==="file"?m=up(h.query):m=ki(h.command,h.query),p=m.length>0):(p=!1,m=[]),f>=m.length&&(f=Math.max(0,m.length-1)),y>f&&(y=f),f>=y+w&&(y=f-w+1);let F=n.columns||80;if(g=0,p&&F>40){let ce=Math.min(F-4,60),Ie=Math.min(m.length-y,w);for(let Se=0;Se<Ie;Se++){let ge=y+Se,L=ap(m[ge],ge===f,ce,h?.kind);n.write(`
|
|
@@ -1948,7 +1948,7 @@ complete -c afk -l trigger -x -a '${n}' -d 'Trigger type'`}function Qp(e){e.comm
|
|
|
1948
1948
|
`);return r.length>0&&r[r.length-1]===""&&r.pop(),r.slice(-t)}catch{return[]}}function yT(e){try{if(process.platform==="linux"){let t=`/proc/${e}/stat`;if(!Lt(t))return{};let r=jo(t,"utf-8").split(" "),o=Number.parseInt(r[21]??"0",10),l=mT("/proc/1").mtimeMs/1e3+o/100,c=Math.floor(Date.now()/1e3-l),p=jo(`/proc/${e}/status`,"utf-8").match(/VmRSS:\s+(\d+)\s+kB/),m=p?Math.round(Number.parseInt(p[1]??"0",10)/1024):void 0;return{uptimeSec:c,memoryMb:m}}if(process.platform==="darwin"){let{execFileSync:t}=gm("child_process"),n=t("ps",["-p",String(e),"-o","etime=,rss="],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim(),[r,o]=n.split(/\s+/);return{uptimeSec:kT(r??""),memoryMb:o?Math.round(Number.parseInt(o,10)/1024):void 0}}}catch{}return{}}function kT(e){if(!e)return;let t=e.split("-"),n=0,r=e;t.length===2&&(n=Number.parseInt(t[0]??"0",10),r=t[1]??"");let o=r.split(":").map(l=>Number.parseInt(l,10));if(o.some(l=>!Number.isFinite(l)))return;let s=0,a=0,i=0;if(o.length===3)[s,a,i]=o;else if(o.length===2)[a,i]=o;else if(o.length===1)[i]=o;else return;return n*86400+s*3600+a*60+i}import{createInterface as bT}from"readline";import te from"chalk";var nm="https://api.telegram.org";async function tm(e){try{let t=await fetch(`${nm}/bot${e}/getMe`);if(!t.ok)return null;let n=await t.json();return!n.ok||!n.result?.id||!n.result?.first_name?null:{id:n.result.id,...n.result.username!==void 0?{username:n.result.username}:{},firstName:n.result.first_name}}catch{return null}}function wT(e){let t=new Map;for(let n of e){let o=(n.message??n.edited_message)?.chat;!o||typeof o.id!="number"||t.set(o.id,{chatId:o.id,type:o.type??"unknown",...o.username!==void 0?{username:o.username}:{},...o.first_name!==void 0?{firstName:o.first_name}:{}})}return[...t.values()].reverse()}async function ST(e){try{let t=await fetch(`${nm}/bot${e}/getUpdates`);if(!t.ok)return[];let n=await t.json();return!n.ok||!Array.isArray(n.result)?[]:n.result}catch{return[]}}async function vT(e,t={}){let n=t.maxAttempts??30,r=t.intervalMs??2e3;for(let o=0;o<n;o++){let s=await ST(e),a=wT(s);if(a.length>0)return a;o<n-1&&await new Promise(i=>setTimeout(i,r))}return[]}function Li(e){let t=bT({input:process.stdin,output:process.stdout});return new Promise(n=>{t.question(e,r=>{t.close(),n(r.trim())})})}async function rm(){let e=Ke();console.log(""),console.log(te.bold("\u{1F916} Telegram bot setup")),console.log(""),console.log(te.gray(`Config will be written to ${e}`)),console.log("");let t=process.env.TELEGRAM_BOT_TOKEN?.trim()??"",n=null;for(t&&(console.log(te.gray("Validating existing TELEGRAM_BOT_TOKEN...")),n=await tm(t),n?console.log(te.green(`\u2713 Token valid for @${n.username??n.firstName} (id ${n.id})`)):(console.log(te.yellow("\u26A0 Existing TELEGRAM_BOT_TOKEN is invalid; prompting for a new one")),t=""));!n;)t=await Li("Paste your bot token (from @BotFather): "),t||(console.error(te.red("No token provided. Aborting.")),process.exit(1)),n=await tm(t),n||console.log(te.red("\u2717 Token rejected by getMe. Try again or Ctrl-C to abort."));ln(e,"TELEGRAM_BOT_TOKEN",t),console.log(te.green(`\u2713 Saved TELEGRAM_BOT_TOKEN \u2192 ${e}`)),console.log(""),console.log(te.bold("Now DM your bot to authorize your account."));let r=n.username?`@${n.username}`:`"${n.firstName}"`;console.log(` 1. Open Telegram and find ${te.cyan(r)}`),console.log(' 2. Send any message (e.g. "hi")'),console.log(""),console.log(te.gray("Polling for your chat ID (up to 60s)..."));let o=await vT(t);if(o.length===0){console.error(te.red("\u2717 No chats found after 60s.")),console.error(te.gray(" Send a message to the bot and run `afk telegram setup` again,")),console.error(te.gray(" or paste your chat ID manually:"));let a=await Li("Chat ID: "),i=Number.parseInt(a,10);return Number.isFinite(i)||(console.error(te.red("Invalid chat ID. Aborting.")),process.exit(1)),ln(e,"AFK_TELEGRAM_ALLOWED_CHAT_IDS",String(i)),console.log(te.green(`\u2713 Saved AFK_TELEGRAM_ALLOWED_CHAT_IDS=${i}`)),{envPath:e,bot:n,chatId:i}}let s=o[0];if(o.length>1){console.log(te.bold(`
|
|
1949
1949
|
Multiple chats found:`)),o.forEach((l,c)=>{let u=l.username?`@${l.username}`:l.firstName??l.type;console.log(` [${c+1}] ${u} (id ${l.chatId}, ${l.type})`)});let a=await Li("Which chat should be allowed? [1]: "),i=Number.parseInt(a||"1",10)-1;Number.isFinite(i)&&i>=0&&i<o.length&&(s=o[i])}else{let a=s.username?`@${s.username}`:s.firstName??s.type;console.log(te.green(`\u2713 Found chat with ${a} (id ${s.chatId})`))}return ln(e,"AFK_TELEGRAM_ALLOWED_CHAT_IDS",String(s.chatId)),console.log(te.green(`\u2713 Saved AFK_TELEGRAM_ALLOWED_CHAT_IDS=${s.chatId} \u2192 ${e}`)),console.log(""),console.log(te.bold("Setup complete. Start the bot with:")),console.log(te.cyan(" afk telegram start")),console.log(""),{envPath:e,bot:n,chatId:s.chatId}}function om(e){let t=e.command("telegram").description("Manage the Agent AFK Telegram bot (setup, start, stop, status)");t.command("setup").description("Interactive setup: validate bot token, discover chat ID, persist to ~/.afk/config/afk.env").action(async()=>{try{await rm()}catch(n){console.error(X.red(`Setup failed: ${n.message}`)),process.exit(1)}}),t.command("start").description("Start the bot as a background daemon").action(async()=>{let n=await $i();if(n.kind==="started"){console.log(X.green(`\u2713 Bot started (PID ${n.pid})`)),console.log(X.gray(` Logs: ${n.logFile}`)),console.log(X.gray(" Tail with: afk telegram logs --follow"));return}if(n.kind==="already-running"&&(console.log(X.yellow(`\u26A0 ${n.message}`)),process.exit(1)),n.kind==="exited-immediately"){if(console.error(X.red(`\u2717 ${n.message}`)),n.logTail&&n.logTail.length>0){console.error(""),console.error(X.bold("Last log entries:"));for(let r of n.logTail)console.error(X.gray(` ${r}`))}process.exit(1)}console.error(X.red(`\u2717 ${n.message}`)),process.exit(1)}),t.command("stop").description("Stop the bot (SIGTERM, then SIGKILL after 5s)").action(async()=>{let n=await Oi();if(n.kind==="not-running"){console.log(X.yellow("\u26A0 Bot is not running"));return}if(n.kind==="stopped"){console.log(X.green(`\u2713 Bot stopped (PID ${n.pid})`));return}console.log(X.yellow(`\u26A0 Bot force-killed (PID ${n.pid}); graceful shutdown timed out`))}),t.command("restart").description("Stop and restart the bot").action(async()=>{let n=await Oi();(n.kind==="stopped"||n.kind==="force-killed")&&console.log(X.gray(`Stopped (PID ${n.pid})`));let r=await $i();if(r.kind==="started"){console.log(X.green(`\u2713 Bot restarted (PID ${r.pid})`));return}console.error(X.red(`\u2717 Restart failed: ${r.message}`)),process.exit(1)}),t.command("status").description("Show running state, uptime, memory, and recent log entries").action(()=>{let n=Di();CT(n)}),t.command("logs").description("Show or follow the bot log").option("-f, --follow","Stream new log entries (like tail -f)",!1).option("-n, --lines <count>","Number of trailing lines to show","50").action(n=>{let{logFile:r}=Di();if(!xT(r)){console.log(X.yellow(`No log file at ${r}`)),console.log(X.gray("Start the bot first: afk telegram start"));return}let o=Number.parseInt(n.lines??"50",10);if(n.follow){TT("tail",["-n",String(o),"-f",r],{stdio:"inherit"}).on("error",i=>{console.error(X.red(`Failed to spawn tail: ${i.message}`))});return}let s=ET(r,"utf-8").split(`
|
|
1950
1950
|
`).slice(-o-1);console.log(s.join(`
|
|
1951
|
-
`))})}function CT(e){if(console.log(X.bold("\u{1F4CA} Telegram Bot Status")),console.log(""),e.running?(console.log(` ${X.green("\u25CF")} Running (PID ${e.pid})`),e.uptimeSec!==void 0&&console.log(` Uptime: ${PT(e.uptimeSec)}`),e.memoryMb!==void 0&&console.log(` Memory: ${e.memoryMb} MB`)):console.log(` ${X.red("\u25CF")} Stopped`),console.log(` PID: ${e.pidFile}`),console.log(` Logs: ${e.logFile}`),e.logTail&&e.logTail.length>0){console.log(""),console.log(X.bold("Recent log entries:"));for(let t of e.logTail)console.log(X.gray(` ${t}`))}}function PT(e){if(e<60)return`${e}s`;let t=Math.floor(e/60);if(t<60)return`${t}m ${e%60}s`;let n=Math.floor(t/60);return n<24?`${n}h ${t%60}m`:`${Math.floor(n/24)}d ${n%24}h`}import{readFileSync as AT}from"fs";import{dirname as _T,join as IT}from"path";import{fileURLToPath as RT}from"url";function zn(){try{return"2.6.
|
|
1951
|
+
`))})}function CT(e){if(console.log(X.bold("\u{1F4CA} Telegram Bot Status")),console.log(""),e.running?(console.log(` ${X.green("\u25CF")} Running (PID ${e.pid})`),e.uptimeSec!==void 0&&console.log(` Uptime: ${PT(e.uptimeSec)}`),e.memoryMb!==void 0&&console.log(` Memory: ${e.memoryMb} MB`)):console.log(` ${X.red("\u25CF")} Stopped`),console.log(` PID: ${e.pidFile}`),console.log(` Logs: ${e.logFile}`),e.logTail&&e.logTail.length>0){console.log(""),console.log(X.bold("Recent log entries:"));for(let t of e.logTail)console.log(X.gray(` ${t}`))}}function PT(e){if(e<60)return`${e}s`;let t=Math.floor(e/60);if(t<60)return`${t}m ${e%60}s`;let n=Math.floor(t/60);return n<24?`${n}h ${t%60}m`:`${Math.floor(n/24)}d ${n%24}h`}import{readFileSync as AT}from"fs";import{dirname as _T,join as IT}from"path";import{fileURLToPath as RT}from"url";function zn(){try{return"2.6.1"}catch{}try{let e=_T(RT(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(AT(IT(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}import{spawn as sm}from"child_process";import{existsSync as MT,mkdirSync as $T,readFileSync as im,unlinkSync as OT,writeFileSync as DT}from"fs";import{join as am}from"path";var LT=1440*60*1e3,NT="update-check.json",FT="pending-update.json";function lm(){return am(Xn(),NT)}function Ni(){return am(Xn(),FT)}function cm(){let e=Xn();MT(e)||$T(e,{recursive:!0})}function UT(e,t){let n=e.split(".").map(Number),r=t.split(".").map(Number),o=Math.max(n.length,r.length);for(let s=0;s<o;s++){let a=n[s]??0,i=r[s]??0;if(i>a)return!0;if(i<a)return!1}return!1}function jT(){try{let e=im(lm(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function BT(){try{cm();let e=`
|
|
1952
1952
|
const https = require('https');
|
|
1953
1953
|
const fs = require('fs');
|
|
1954
1954
|
const url = 'https://registry.npmjs.org/agent-afk/latest';
|