agent-afk 2.6.2 → 2.6.3
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 +2 -2
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -1736,7 +1736,7 @@ ${a}
|
|
|
1736
1736
|
|
|
1737
1737
|
`);if(n!==-1)return n+2;let r=t.match(/\n[ \t]*```[ \t]*\n/);if(r&&r.index!==void 0)return r.index+r[0].length;let o=t.match(/```[a-z]*\n/);return o&&o.index!==void 0&&!t.slice(o.index+o[0].length).includes("\n```"),-1}applyIndent(t){return t.split(`
|
|
1738
1738
|
`).map(n=>n?this.indent+n:"").join(`
|
|
1739
|
-
`)}isInOpenCodeFence(t){return(t.match(
|
|
1739
|
+
`)}isInOpenCodeFence(t){return(t.match(/^```/gm)??[]).length%2===1}commitBlock(t){if(!t.trim())return;let n=this.hasMarkdownContent(t),r=this.indent.length,o=Math.max(1,q()-2),s=Math.max(1,o-r),i;n?i=Ue(t,{maxWidth:s}):i=V(t,s);let a=V(i,s),c=this.applyIndent(a).replace(/\n+$/,"");this.compositor&&this.compositor.commitAbove(c+`
|
|
1740
1740
|
`),this.committed?this.committed+=`
|
|
1741
1741
|
|
|
1742
1742
|
`+c:this.committed+=c}scheduleRepaint(){this.isTTY&&(this.flushing||(this.throttleTimer&&clearTimeout(this.throttleTimer),this.throttleTimer=setTimeout(()=>{this.throttleTimer=null,this.repaint()},this.throttleMs)))}async repaint(){if(this.flushing||!this.isTTY||!this.buffer.trim())return;let t,n=this.indent.length,r=Math.max(1,q()-2),o=Math.max(1,r-n);this.isInOpenCodeFence(this.buffer)?t=`
|
|
@@ -1949,7 +1949,7 @@ complete -c afk -l trigger -x -a '${n}' -d 'Trigger type'`}function Qp(e){e.comm
|
|
|
1949
1949
|
`);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(!Nt(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,i=0,a=0;if(o.length===3)[s,i,a]=o;else if(o.length===2)[i,a]=o;else if(o.length===1)[a]=o;else return;return n*86400+s*3600+i*60+a}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),i=wT(s);if(i.length>0)return i;o<n-1&&await new Promise(a=>setTimeout(a,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 i=await Li("Chat ID: "),a=Number.parseInt(i,10);return Number.isFinite(a)||(console.error(te.red("Invalid chat ID. Aborting.")),process.exit(1)),ln(e,"AFK_TELEGRAM_ALLOWED_CHAT_IDS",String(a)),console.log(te.green(`\u2713 Saved AFK_TELEGRAM_ALLOWED_CHAT_IDS=${a}`)),{envPath:e,bot:n,chatId:a}}let s=o[0];if(o.length>1){console.log(te.bold(`
|
|
1950
1950
|
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 i=await Li("Which chat should be allowed? [1]: "),a=Number.parseInt(i||"1",10)-1;Number.isFinite(a)&&a>=0&&a<o.length&&(s=o[a])}else{let i=s.username?`@${s.username}`:s.firstName??s.type;console.log(te.green(`\u2713 Found chat with ${i} (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();PT(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",a=>{console.error(X.red(`Failed to spawn tail: ${a.message}`))});return}let s=ET(r,"utf-8").split(`
|
|
1951
1951
|
`).slice(-o-1);console.log(s.join(`
|
|
1952
|
-
`))})}function PT(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: ${CT(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 CT(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.
|
|
1952
|
+
`))})}function PT(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: ${CT(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 CT(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.3"}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 i=n[s]??0,a=r[s]??0;if(a>i)return!0;if(a<i)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=`
|
|
1953
1953
|
const https = require('https');
|
|
1954
1954
|
const fs = require('fs');
|
|
1955
1955
|
const url = 'https://registry.npmjs.org/agent-afk/latest';
|