agent-afk 2.25.2 → 2.25.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/dist/index.mjs +1 -1
- package/dist/telegram.mjs +1 -1
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -1726,7 +1726,7 @@ ${m}`}}catch(l){return{content:`Error: ${l instanceof Error?l.message:String(l)}
|
|
|
1726
1726
|
[output truncated]`),c({content:S})}),u.on("error",b=>{c({content:`Failed to execute grep: ${b.message}`,isError:!0})})})}}var ud=Ki();import{promises as sS}from"fs";var dd=async(e,t,n)=>{if(!e||typeof e!="object")throw new Error("Invalid input: expected an object");let o=e.path;if(typeof o!="string")throw new Error("Invalid input: path must be a string");let s;try{s=Ke(o,n,"read")}catch(a){return{content:a instanceof Error?a.message:String(a),isError:!0}}try{let a=await sS.readdir(s,{withFileTypes:!0}),i=a.filter(u=>u.isDirectory()).map(u=>`${u.name}/`),l=a.filter(u=>!u.isDirectory()).map(u=>u.name);i.sort(),l.sort();let c=[...i,...l];return c.length===0?{content:"(empty directory)"}:{content:c.join(`
|
|
1727
1727
|
`)}}catch(a){if(a instanceof Error){let i=a;return i.code==="ENOENT"?{content:`Directory not found: ${s}`,isError:!0}:i.code==="ENOTDIR"?{content:`Not a directory: ${s}`,isError:!0}:i.code==="EACCES"?{content:`Permission denied: ${s}`,isError:!0}:{content:`Error listing directory: ${a.message}`,isError:!0}}return{content:"Unknown error listing directory",isError:!0}}};$o();Gi();var md=4096;function aS(e=Io){return async(t,n)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected an object",isError:!0};let o=t.message;if(typeof o!="string")return{content:"Invalid input: message must be a string",isError:!0};if(o.length===0)return{content:"Invalid input: message must be non-empty",isError:!0};if(o.length>md)return{content:`Invalid input: message exceeds Telegram's ${md}-character limit (got ${o.length}). Split into multiple sends or trim before calling.`,isError:!0};let s=process.env.TELEGRAM_BOT_TOKEN;if(!s)return{content:"Telegram is not configured: TELEGRAM_BOT_TOKEN is not set. Run the bot setup wizard or export the env var before using send_telegram.",isError:!0};let a=Po(process.env.AFK_TELEGRAM_ALLOWED_CHAT_IDS);if(a.size===0)return{content:"Telegram is not configured: AFK_TELEGRAM_ALLOWED_CHAT_IDS is empty or unset. Add the operator chat ID(s) before using send_telegram.",isError:!0};let i=[...a],l=[];for(let c of i){let d=await e({token:s,chatId:c,text:o});d.ok||l.push(`chat ${c}: ${d.errorMessage??`HTTP ${d.status}`}`)}return l.length===i.length?{content:`Failed to send Telegram message to any chat. ${l.join("; ")}`,isError:!0}:l.length>0?{content:`Sent Telegram message to ${i.length-l.length}/${i.length} chat(s); ${l.length} failed: ${l.join("; ")}`}:{content:i.length===1?`Sent Telegram message to chat ${i[0]}.`:`Sent Telegram message to ${i.length} chats.`}}}var fd=aS();var lS=`
|
|
1728
1728
|
|
|
1729
|
-
[\u2026truncated by agent-afk web_scrape]`,cS="https://r.jina.ai/",uS="https://s.jina.ai/";function dS(e){if(!e||typeof e!="object")return{error:"Invalid input: expected an object"};let t=e,n=t.mode??"markdown";if(n!=="markdown"&&n!=="raw"&&n!=="search")return{error:`Invalid input: mode must be one of "markdown", "raw", "search" (got ${JSON.stringify(n)})`};let r=n,o,s;if(r==="search"){if(typeof t.query!="string"||t.query.length===0)return{error:'Invalid input: search mode requires a non-empty "query" string'};s=t.query}else{if(typeof t.url!="string"||t.url.length===0)return{error:`Invalid input: ${r} mode requires a non-empty "url" string`};let l;try{l=new URL(t.url)}catch{return{error:`Invalid input: "${t.url}" is not a valid absolute URL`}}if(l.protocol!=="http:"&&l.protocol!=="https:")return{error:`Invalid input: protocol "${l.protocol}" not supported (http/https only)`};o=l.toString()}let a=3e4;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number"||!Number.isFinite(t.timeout_ms)||t.timeout_ms<=0)return{error:"Invalid input: timeout_ms must be a positive finite number"};a=Math.min(t.timeout_ms,12e4)}let i=1e6;if(t.max_bytes!==void 0){if(typeof t.max_bytes!="number"||!Number.isFinite(t.max_bytes)||t.max_bytes<=0)return{error:"Invalid input: max_bytes must be a positive finite number"};i=Math.min(t.max_bytes,1e7)}return{mode:r,url:o,query:s,timeoutMs:a,maxBytes:i}}function pS(e){return e.mode==="search"?`${uS}${encodeURIComponent(e.query)}`:e.mode==="markdown"?`${cS}${e.url}`:e.url}function mS(e,t){let n={"User-Agent":"agent-afk/web_scrape",Accept:e.mode==="raw"?"*/*":"text/plain, text/markdown, */*;q=0.5"};return(e.mode==="markdown"||e.mode==="search")&&t.JINA_API_KEY&&(n.Authorization=`Bearer ${t.JINA_API_KEY}`),n}function fS(e,t){let n=Buffer.from(e,"utf8");return n.byteLength<=t?e:n.subarray(0,t).toString("utf8")+lS}function gS(e={}){let t=e.fetchFn??globalThis.fetch,n=e.env??process.env;return async(r,o)=>{if(typeof t!="function")return{content:"web_scrape unavailable: global fetch() is not present in this runtime (agent-afk requires Node 20+).",isError:!0};let s=dS(r);if("error"in s)return{content:s.error,isError:!0};let a=pS(s),i=mS(s,n)
|
|
1729
|
+
[\u2026truncated by agent-afk web_scrape]`,cS="https://r.jina.ai/",uS="https://s.jina.ai/";function dS(e){if(!e||typeof e!="object")return{error:"Invalid input: expected an object"};let t=e,n=t.mode??"markdown";if(n!=="markdown"&&n!=="raw"&&n!=="search")return{error:`Invalid input: mode must be one of "markdown", "raw", "search" (got ${JSON.stringify(n)})`};let r=n,o,s;if(r==="search"){if(typeof t.query!="string"||t.query.length===0)return{error:'Invalid input: search mode requires a non-empty "query" string'};s=t.query}else{if(typeof t.url!="string"||t.url.length===0)return{error:`Invalid input: ${r} mode requires a non-empty "url" string`};let l;try{l=new URL(t.url)}catch{return{error:`Invalid input: "${t.url}" is not a valid absolute URL`}}if(l.protocol!=="http:"&&l.protocol!=="https:")return{error:`Invalid input: protocol "${l.protocol}" not supported (http/https only)`};o=l.toString()}let a=3e4;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number"||!Number.isFinite(t.timeout_ms)||t.timeout_ms<=0)return{error:"Invalid input: timeout_ms must be a positive finite number"};a=Math.min(t.timeout_ms,12e4)}let i=1e6;if(t.max_bytes!==void 0){if(typeof t.max_bytes!="number"||!Number.isFinite(t.max_bytes)||t.max_bytes<=0)return{error:"Invalid input: max_bytes must be a positive finite number"};i=Math.min(t.max_bytes,1e7)}return{mode:r,url:o,query:s,timeoutMs:a,maxBytes:i}}function pS(e){return e.mode==="search"?`${uS}${encodeURIComponent(e.query)}`:e.mode==="markdown"?`${cS}${e.url}`:e.url}function mS(e,t){let n={"User-Agent":"agent-afk/web_scrape",Accept:e.mode==="raw"?"*/*":"text/plain, text/markdown, */*;q=0.5"};return(e.mode==="markdown"||e.mode==="search")&&t.JINA_API_KEY&&(n.Authorization=`Bearer ${t.JINA_API_KEY}`),n}function fS(e,t){let n=Buffer.from(e,"utf8");return n.byteLength<=t?e:n.subarray(0,t).toString("utf8")+lS}function gS(e={}){let t=e.fetchFn??globalThis.fetch,n=e.env??process.env;return async(r,o)=>{if(typeof t!="function")return{content:"web_scrape unavailable: global fetch() is not present in this runtime (agent-afk requires Node 20+).",isError:!0};let s=dS(r);if("error"in s)return{content:s.error,isError:!0};let a=pS(s),i=mS(s,n);if(o.aborted){let u=o.reason;return{content:`web_scrape aborted: ${u instanceof Error?u.message:String(u??"aborted")}`,isError:!0}}let l=new AbortController,c=()=>{l.abort(o.reason)},d;try{o.addEventListener("abort",c,{once:!0}),d=setTimeout(()=>{l.abort(new Error(`web_scrape timeout after ${s.timeoutMs}ms`))},s.timeoutMs);let u;try{u=await t(a,{headers:i,signal:l.signal})}catch(g){if(l.signal.aborted){let b=l.signal.reason;return{content:`web_scrape aborted: ${b instanceof Error?b.message:String(b??"aborted")}`,isError:!0}}return{content:`web_scrape network error: ${g instanceof Error?g.message:String(g)}`,isError:!0}}if(!u.ok)return{content:`web_scrape HTTP ${u.status} ${u.statusText||""}`.trimEnd()+` for ${a}`,isError:!0};let m;try{m=await u.text()}catch(g){return{content:`web_scrape read error: ${g instanceof Error?g.message:String(g)}`,isError:!0}}return{content:fS(m,s.maxBytes)}}finally{d!==void 0&&clearTimeout(d),o.removeEventListener("abort",c)}}}var gd=gS();function hd(e,t){let n=e!==void 0?Co(e,t):t!==void 0?Co("default",t):nd,r=t!==void 0?Hi(t):cd,o=t!==void 0?Ki(t):ud;return new Map([["bash",n],["read_file",rd],["write_file",sd],["edit_file",id],["glob",r],["grep",o],["list_directory",dd],["send_telegram",fd],["web_scrape",gd]])}var zi=`You have access to tools for working with the filesystem and running commands. Follow these conventions:
|
|
1730
1730
|
|
|
1731
1731
|
- Use read_file before editing to verify the exact content you want to change.
|
|
1732
1732
|
- Prefer edit_file over write_file for modifying existing files \u2014 write_file is for new files or complete rewrites.
|
|
@@ -1961,7 +1961,7 @@ _ended: ${new Date().toISOString()}_
|
|
|
1961
1961
|
`)}function eA(e){let t=[],n=(r,o)=>{o&&o.trim().length>0&&t.push({label:r,value:o.trim()})};switch(e.kind){case"done":n("done",e.whatWasDone),n("evidence",e.evidence),n("deferred",e.deferred);break;case"blocked":n("blocks",e.whatBlocks),n("unblock",e.unblockCondition),n("progress",e.alreadyDone);break;case"asking":n("question",e.question),n("resolves",e.assumption),n("after",e.followup);break;case"interrupted":n("was doing",e.whatWasInProgress),n("saved at",e.stateLocation),n("resume",e.resumeRequires);break}return t}function tA(e,t){let n=[];e&&n.push({type:"text",text:e});for(let r of t)n.push({type:"image",source:{type:"base64",media_type:r.mediaType,data:r.bytes.toString("base64")}});return n}async function ag(e,t,n,r,o="summary",s,a){let i=Hf(e.text,e.attachments);r.setInFlight(!0);let l="",c=!1,d,u=!1,m=!1,f=!1,g,b=!1,S=[],h=new Map,k=e.text.startsWith("/")?e.text.split(/[\s:]/)[0]?.slice(1):void 0,w=new Wt({out:jn(),thinkingMode:o,...k?{activeSkillName:k}:{},onCancel:()=>{t.interrupt().catch(T=>{_e()&&console.error(" "+p.error("session.interrupt() failed:"),T)})},...a?{onBackground:()=>{b=!0}}:{}}),C=async()=>{if(!m){m=!0;try{await w.dispose()}catch{}}};try{console.log(),await w.arm();let T=w.getCompositor();if(s&&T){let v=T;s.fn=E=>v.commitAbove(E)}r.setActiveCompositor?.(T),r.rearmStatus?.();let _=e.attachments.length===0?e.text:tA(e.text,e.attachments),x=t.sendMessageStream(_);if(await vn(w.sink,async()=>{for await(let v of x){if(b&&a){let E=k??e.text.slice(0,40),I=a.register(E),P=is(I,a);as(x,l,i,I,a,P,n,r.onTurnComplete,t.abortSignal),await C(),console.log(p.dim(` \u2192 backgrounded as ${I.id}: ${I.label}`)),r.setInFlight(!1),r.rearmStatus?.();return}if(v.type==="chunk"&&v.chunk.type==="content"?(l+=v.chunk.content,c=!0):v.type==="message"&&!c&&(l=v.message.content),v.type==="chunk"&&v.chunk.type==="tool_use_detail"){let E=v.chunk,I={toolName:E.toolName,toolUseId:E.toolUseId,input:E.toolInput};h.set(E.toolUseId,I),S.push(I)}else if(v.type==="chunk"&&v.chunk.type==="tool_result"){let E=v.chunk,I=h.get(E.toolUseId);I&&(I.result=E.content,I.isError=E.isError,h.delete(E.toolUseId))}if(v.type==="paused"){await C(),console.log(tc({reason:v.reason,...v.resetsAt!==void 0?{resetsAt:v.resetsAt}:{},...v.accountId!==void 0?{accountId:v.accountId}:{}}));continue}if(v.type==="resumed"){let E=v.hotSwapped&&v.accountId?`\u25B6 Resumed on ${v.accountId}`:"\u25B6 Resumed";console.log(p.success(E));continue}if(v.type==="error"){await C(),kn(bn(v.error)),u=!0;continue}w.process(v),v.type==="done"&&(f=!0,g=v.metadata)}}),!m){let v=w.getCompositor();if(v)try{let{text:E,queued:I}=v.getBuffer();I&&E.length>0&&(d=E)}catch{}}if(await C(),f){es(n,i,l,g,S),r.onTurnComplete&&await r.onTurnComplete(i,l).catch(()=>{}),c&&console.log(`
|
|
1962
1962
|
`);let v=sg(l);if(v&&(console.log(ig(v)),console.log(),r.onTerminalState))try{r.onTerminalState(v)}catch{}if(nA(g,n),r.onAfterTurn){let E=r.onAfterTurn();E instanceof Promise&&await E.catch(()=>{})}}}catch(T){await C(),u||kn(bn(T))}finally{await C(),s&&(s.fn=T=>console.log(T)),r.setActiveCompositor?.(null),r.setInFlight(!1),r.rearmStatus?.()}return d}function nA(e,t){if(!e)return;let n=[];e.durationMs&&n.push(re(e.durationMs)),e.totalCostUsd!==void 0&&n.push(Me(e.totalCostUsd));let r=Number(e.usage?.input_tokens??0),o=Number(e.usage?.output_tokens??0);r+o>0&&n.push(H(r+o)+" tok"),n.length>0&&console.log(p.dim(" \u25E6 "+n.join(" \xB7 ")));let s=pa(t);if(s>.5){let a=s>.8?p.error:p.warning;console.log(a(` context ${Math.round(s*100)}% used of ${H(nt(t.model))}`))}console.log()}function lg(e={}){let t=e.load??rs,n=e.onResize??(a=>xt.subscribe(a)),r="",o,s=n(()=>{r=""});return{renderIfChanged(a){let i=a??"unbound",l=t(i),c=Vp(l);return i===o&&c===r?[]:(o=i,r=c,c===""?[]:os(l))},invalidate(){r=""},dispose(){try{s()}catch{}}}}var Ya={done:{glyph:"\u2713",color:p.success,label:"done"},blocked:{glyph:"\u2298",color:p.error,label:"blocked"},asking:{glyph:"?",color:p.warning,label:"asking"},interrupted:{glyph:"\u23F8",color:p.info,label:"interrupted"}};function cg(e={}){let t=Math.max(2,e.capacity??8),n=[];return{push(r){n.push(r.kind),n.length>t&&(n=n.slice(n.length-t))},reset(){n=[]},entries(){return n},render(){if(n.length===0)return null;let r=p.dim(" ledger "),o=p.dim(" \xB7 "),s=n.map(d=>{let u=Ya[d];return u.color(`${u.glyph} ${u.label}`)}),a=p.dim(` (${n.length} turn${n.length===1?"":"s"})`),i=r+s.join(o)+a,l=Math.max(20,ee()-2);if(U(i)<=l)return i;let c=r+n.map(d=>Ya[d].color(Ya[d].glyph)).join(p.dim(" "))+a;return ie(c,l)}}}var ug=["\u25D0","\u25D1","\u25D2","\u25D3"],Ns=class{stream;manager;throttleMs;started=!1;lastRepaint=0;spinnerIndex=0;spinnerInterval=null;resizeUnsub=null;updateHandler=null;rowCount=0;onRowCountChange;constructor(t,n={}){this.manager=t,this.stream=n.stream??process.stdout,this.throttleMs=n.throttleMs??200}setRowCountChangeHandler(t){this.onRowCountChange=t}start(){this.started||(this.started=!0,this.updateHandler=()=>this.scheduleRepaint(),this.manager.on("update",this.updateHandler),this.manager.on("complete",this.updateHandler),this.resizeUnsub=xt.subscribe(()=>this.repaint()),this.spinnerInterval=setInterval(()=>{this.spinnerIndex=(this.spinnerIndex+1)%ug.length,this.rowCount>0&&this.repaint()},Math.max(this.throttleMs,50)))}stop(){this.started&&(this.started=!1,this.updateHandler&&(this.manager.removeListener("update",this.updateHandler),this.manager.removeListener("complete",this.updateHandler),this.updateHandler=null),this.resizeUnsub&&(this.resizeUnsub(),this.resizeUnsub=null),this.spinnerInterval&&(clearInterval(this.spinnerInterval),this.spinnerInterval=null),this.rowCount>0&&(this.clearRows(),this.rowCount=0,this.onRowCountChange?.(0)))}scheduleRepaint(){Date.now()-this.lastRepaint<this.throttleMs||this.repaint()}repaint(){if(!this.started||!this.stream.isTTY)return;this.lastRepaint=Date.now();let t=this.manager.running(),n=t.length;if(n!==this.rowCount&&(this.rowCount>0&&this.clearRows(),this.rowCount=n,this.onRowCountChange?.(n)),n===0)return;let o=(this.stream.rows??24)-n;this.stream.write("\x1B[s");for(let s=0;s<t.length;s++){let a=t[s],i=o+s;this.stream.write(`\x1B[${i};1H`),this.stream.write("\x1B[2K"),this.stream.write(this.formatTaskLine(a))}this.stream.write("\x1B[u")}clearRows(){if(!this.stream.isTTY)return;let n=(this.stream.rows??24)-this.rowCount;this.stream.write("\x1B[s");for(let r=0;r<this.rowCount;r++)this.stream.write(`\x1B[${n+r};1H`),this.stream.write("\x1B[2K");this.stream.write("\x1B[u")}formatTaskLine(t){let n=Math.max(4,(this.stream.columns??80)-2),r=p.brand(ug[this.spinnerIndex]),o=p.dim(t.id),s=p.bold(t.label),a=[r,o,s];t.progressDescription&&a.push(p.dim(t.progressDescription));let i=[];t.stats.toolUses>0&&i.push(`${t.stats.toolUses} tool${t.stats.toolUses===1?"":"s"}`),t.stats.tokens>0&&i.push(`${H(t.stats.tokens)} tok`);let l=Date.now()-t.startedAt;return i.push(re(l)),i.length>0&&a.push(p.dim(i.join(" \xB7 "))),ie(" "+a.join(" "),n)}};function dg(e,t){let n=p.brand("afk")+p.dim(` (${e})`),r=t?p.warning(" \u25CF plan"):"";return n+r+p.dim(" \u203A ")}async function pg(e,t,n,r){let o=null,s=[];e.session.waitForInitialization().then(async g=>{_e()&&(o=ns(g)),await cf(e.session),_e()&&(s=lf())}).catch(()=>{});let a=await og(),i,l=lg(),c=cg(),d=new ss;im(d),pm(d),fm(d);let u=new Ns(d);u.setRowCountChangeHandler(g=>{e.statusLine.setExtraRows(g)}),u.start();let m=50,f=[];d.on("complete",g=>{f.length>=m&&f.shift(),f.push(g)});try{for(;;){if(o&&(e.replRenderer.writeLine(o),e.replRenderer.writeLine(""),o=null),s.length>0){for(let w of s)e.replRenderer.writeLine(w);e.replRenderer.writeLine(""),s=[]}for(;f.length>0;){let w=f.shift(),C=w.status==="succeeded"?"\u2713":"\u2717",T=[];if(w.resultText){let x=w.resultText.trim().split(`
|
|
1963
1963
|
`)[0]?.slice(0,80)??"";x&&T.push(x)}w.error&&T.push(w.error.message);let _=[w.stats.toolUses>0?`${w.stats.toolUses} tools`:"",w.stats.tokens>0?`${Math.round(w.stats.tokens/1e3)}k tok`:"",w.stats.durationMs>0?`${Math.round(w.stats.durationMs/1e3)}s`:""].filter(Boolean).join(" \xB7 ");_&&T.push(_),e.replRenderer.writeLine(Et({kind:w.status==="succeeded"?"checkpoint":"diagnosis",title:`${C} ${w.id} ${w.label}`,body:T})),e.replRenderer.writeLine("")}let g=l.renderIfChanged(e.stats.sessionId);if(g.length>0){for(let w of g)e.replRenderer.writeLine(w);e.replRenderer.writeLine("")}let b=c.render();b&&e.replRenderer.writeLine(b);let S,h;if(i!==void 0){let w=i;i=void 0;let C=dg(e.stats.model,e.stats.planMode),T=_r({buffer:w,promptText:C,isTTY:!!process.stdout.isTTY});e.replRenderer.writeLine(T),S=w.trim(),h=[]}else{let w=await eg({rl:e.rl,promptFn:()=>dg(e.stats.model,e.stats.planMode),onSigint:r,statusLine:e.statusLine,compositor:n.activeCompositor??void 0,history:a,onShiftTab:()=>{let C=e.slashCtx;C.stats.planMode&&C.stats.pendingPlanExit?(C.stats.pendingPlanExit=!1,ht(C,!1,{closureSummarySkipped:!0}).catch(()=>{})):ht(C).catch(()=>{}),e.statusLine.rearm()}});S=w.text.trim(),h=w.attachments}if(!S&&h.length===0)continue;if(S.startsWith("/")){let w=await Op(S,e.slashCtx);if(w.handled){if(w.result==="exit"){e.rl.close();return}if((S==="/clear"||S.startsWith("/clear "))&&(await t.rotateOnClear(),e.replRenderer.writeLine(p.dim(` transcript: ${t.path()}`)),c.reset()),w.result!==null&&typeof w.result=="object"&&"kind"in w.result&&w.result.kind==="submit"){i=w.result.message,e.statusLine.rearm();continue}e.statusLine.rearm();continue}}a.push(S);let k;if(e.firstTurnHook&&e.stats.totalTurns===0){let w=e.firstTurnHook;e.firstTurnHook=void 0,k=Promise.resolve().then(()=>w(S)).catch(C=>{console.warn(p.warning("\u26A0 ")+"first-turn hook failed: "+(C instanceof Error?C.message:String(C)))})}i=await ag({text:S,attachments:h},e.session,e.stats,{setInFlight(w){n.turnInFlight=w},async onTurnComplete(w,C){await t.appendTurn(w,C)},async onAfterTurn(){await e.contextSampler.onTurn(e.stats.totalTurns),await jp(e.slashCtx),e.statusLine.rearm()},rearmStatus:()=>e.statusLine.rearm(),onTerminalState:w=>c.push(w),setActiveCompositor:w=>{n.activeCompositor=w,e.replRenderer.setCompositor(w)}},e.options.thinkingUi,e.completionWriter,d),k!==void 0&&await k}}finally{u.stop(),l.dispose()}}import{promises as oA}from"node:fs";import{dirname as sA,join as iA}from"node:path";import{randomBytes as aA}from"node:crypto";import rA from"@anthropic-ai/sdk";import{randomUUID as mg}from"node:crypto";async function fg(e){let{token:t,model:n,system:r,user:o,maxTokens:s=64,signal:a,clientFactory:i}=e;if(!t)throw new Error("oneShotCompletion: token required");let l=Qr(t),c=tr(t,l),d=i?i(c):new rA(c),u=mg(),m=mg(),f=Zt(l,u,m),g={};Object.keys(f).length>0&&(g.headers=f),a&&(g.signal=a);let b=await d.messages.create({model:n,max_tokens:s,system:r,messages:[{role:"user",content:o}]},Object.keys(g).length>0?g:void 0),S=[];for(let k of b.content)k.type==="text"&&S.push(k.text);let h=S.join("").trim();return h.length===0&&console.warn("oneShotCompletion: response contained no text blocks \u2014 returning empty string"),h}var lA=["Generate a 2-4 word kebab-case slug describing this work request.","Rules:","- ASCII lowercase letters and digits only, separated by single hyphens","- 2 to 4 hyphen-separated words","- Maximum 30 characters total","- No prefix, no quotes, no punctuation other than hyphens","- Output ONLY the slug \u2014 no explanation, no preamble","Examples: fix-cleanup-race, add-telegram-allowlist, refactor-prompt-loader, debug-flaky-test"].join(`
|
|
1964
|
-
`),gg=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,Va=30,cA=1024,uA=8e3,dA="haiku";async function pA(e,t){let n=e.trim();if(n.length===0||n.startsWith("/"))return null;let r=hA(n,cA),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??uA),a=t.signal?yA([t.signal,o.signal]):o.signal,i;try{t.slugGenerator?i=await t.slugGenerator(r,a):i=await fg({token:t.token,model:t.model??dA,system:lA,user:r,maxTokens:32,signal:a})}catch{return null}finally{clearTimeout(s)}let l=mA(i);if(l===null)return null;let c=sA(t.worktreePath);return await fA(l,c)}function mA(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(gg.test(t)&&t.length<=Va)return t;let n=t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(n.length===0)return null;let r=n.split("-").filter(s=>s.length>0).slice(0,4);if(r.length<2)return null;let o=r[0];for(let s=1;s<r.length;s++){let a=`${o}-${r[s]}`;if(a.length>Va)break;o=a}return gg.test(o)?o:null}async function fA(e,t){if(!await gA(iA(t,e)))return e;let n=aA(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,Va-5)}-${n}`}async function gA(e){try{return await oA.access(e),!0}catch{return!1}}function hA(e,t){let n=Buffer.from(e,"utf8");if(n.length<=t)return e;let r=t;for(;r>0&&n[r]!==void 0&&(n[r]&192)===128;)r--;return n.slice(0,r).toString("utf8")}function yA(e){let t=AbortSignal.any;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController;for(let r of e){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>n.abort(r.reason),{once:!0})}return n.signal}async function hg(e){let t=await pA(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:e.handle.path,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{}});if(t===null)return{status:"skipped",reason:"slug generation returned null"};let r=await(e.renameFn??bp)(e.handle,t,e.branchPrefix!==void 0?{branchPrefix:e.branchPrefix}:void 0);return r.ok?(e.session&&e.session.setCwd(r.newPath),{status:"renamed",oldPath:r.oldPath,newPath:r.newPath,oldBranch:r.oldBranch,newBranch:r.newBranch}):(r.partial==="branch"&&e.session&&e.session.setCwd(e.handle.path),{status:"failed",reason:r.reason,...r.partial!==void 0?{partial:r.partial}:{}})}import{spawn as yg}from"child_process";import{existsSync as vA,mkdirSync as TA,readFileSync as bg,unlinkSync as xA,writeFileSync as EA}from"fs";import{get as CA}from"https";import{join as kg}from"path";import{readFileSync as bA}from"fs";import{dirname as kA,join as wA}from"path";import{fileURLToPath as SA}from"url";function fn(){try{return"2.25.
|
|
1964
|
+
`),gg=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,Va=30,cA=1024,uA=8e3,dA="haiku";async function pA(e,t){let n=e.trim();if(n.length===0||n.startsWith("/"))return null;let r=hA(n,cA),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??uA),a=t.signal?yA([t.signal,o.signal]):o.signal,i;try{t.slugGenerator?i=await t.slugGenerator(r,a):i=await fg({token:t.token,model:t.model??dA,system:lA,user:r,maxTokens:32,signal:a})}catch{return null}finally{clearTimeout(s)}let l=mA(i);if(l===null)return null;let c=sA(t.worktreePath);return await fA(l,c)}function mA(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(gg.test(t)&&t.length<=Va)return t;let n=t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(n.length===0)return null;let r=n.split("-").filter(s=>s.length>0).slice(0,4);if(r.length<2)return null;let o=r[0];for(let s=1;s<r.length;s++){let a=`${o}-${r[s]}`;if(a.length>Va)break;o=a}return gg.test(o)?o:null}async function fA(e,t){if(!await gA(iA(t,e)))return e;let n=aA(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,Va-5)}-${n}`}async function gA(e){try{return await oA.access(e),!0}catch{return!1}}function hA(e,t){let n=Buffer.from(e,"utf8");if(n.length<=t)return e;let r=t;for(;r>0&&n[r]!==void 0&&(n[r]&192)===128;)r--;return n.slice(0,r).toString("utf8")}function yA(e){let t=AbortSignal.any;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController;for(let r of e){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>n.abort(r.reason),{once:!0})}return n.signal}async function hg(e){let t=await pA(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:e.handle.path,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{}});if(t===null)return{status:"skipped",reason:"slug generation returned null"};let r=await(e.renameFn??bp)(e.handle,t,e.branchPrefix!==void 0?{branchPrefix:e.branchPrefix}:void 0);return r.ok?(e.session&&e.session.setCwd(r.newPath),{status:"renamed",oldPath:r.oldPath,newPath:r.newPath,oldBranch:r.oldBranch,newBranch:r.newBranch}):(r.partial==="branch"&&e.session&&e.session.setCwd(e.handle.path),{status:"failed",reason:r.reason,...r.partial!==void 0?{partial:r.partial}:{}})}import{spawn as yg}from"child_process";import{existsSync as vA,mkdirSync as TA,readFileSync as bg,unlinkSync as xA,writeFileSync as EA}from"fs";import{get as CA}from"https";import{join as kg}from"path";import{readFileSync as bA}from"fs";import{dirname as kA,join as wA}from"path";import{fileURLToPath as SA}from"url";function fn(){try{return"2.25.3"}catch{}try{let e=kA(SA(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(bA(wA(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}var AA=64*1024,_A=1440*60*1e3,RA="update-check.json",PA="pending-update.json";function wg(){return kg(Hr(),RA)}function Ja(){return kg(Hr(),PA)}function Sg(){let e=Hr();vA(e)||TA(e,{recursive:!0})}function IA(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 MA(){try{let e=bg(wg(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function $A(){try{Sg();let e=`
|
|
1965
1965
|
const https = require('https');
|
|
1966
1966
|
const fs = require('fs');
|
|
1967
1967
|
const url = 'https://registry.npmjs.org/agent-afk/latest';
|
package/dist/index.mjs
CHANGED
|
@@ -1499,7 +1499,7 @@ ${p}`}}catch(c){return{content:`Error: ${c instanceof Error?c.message:String(c)}
|
|
|
1499
1499
|
[output truncated]`),l({content:S})}),u.on("error",m=>{l({content:`Failed to execute grep: ${m.message}`,isError:!0})})})}}var Zo=gn();import{promises as _l}from"fs";var es=async(t,e,n)=>{if(!t||typeof t!="object")throw new Error("Invalid input: expected an object");let o=t.path;if(typeof o!="string")throw new Error("Invalid input: path must be a string");let s;try{s=J(o,n,"read")}catch(i){return{content:i instanceof Error?i.message:String(i),isError:!0}}try{let i=await _l.readdir(s,{withFileTypes:!0}),a=i.filter(u=>u.isDirectory()).map(u=>`${u.name}/`),c=i.filter(u=>!u.isDirectory()).map(u=>u.name);a.sort(),c.sort();let l=[...a,...c];return l.length===0?{content:"(empty directory)"}:{content:l.join(`
|
|
1500
1500
|
`)}}catch(i){if(i instanceof Error){let a=i;return a.code==="ENOENT"?{content:`Directory not found: ${s}`,isError:!0}:a.code==="ENOTDIR"?{content:`Not a directory: ${s}`,isError:!0}:a.code==="EACCES"?{content:`Permission denied: ${s}`,isError:!0}:{content:`Error listing directory: ${i.message}`,isError:!0}}return{content:"Unknown error listing directory",isError:!0}}};function vt(t,e=()=>{}){let n=new Set;if(!t)return n;for(let r of t.split(",")){let o=r.trim();if(o){if(!/^-?\d+$/.test(o)){e("[allowlist] Ignoring non-numeric chat ID:",o);continue}n.add(Number(o))}}return n}function yn(t,e=()=>{}){return async(n,r)=>{let o=n.chat?.id;if(o===void 0||!t.has(o)){e("[allowlist] Rejecting update from chat:",o??"<unknown>");return}await r()}}var Al="https://api.telegram.org";async function ts(t){if(!t.token)throw new Error("push: token is required");if(t.chatId===""||t.chatId==null||t.chatId===0)throw new Error("push: chatId is required");let e=t.fetchImpl??fetch,r=`${t.apiBase??Al}/bot${t.token}/sendMessage`,o={chat_id:t.chatId,text:t.text.slice(0,4096)};t.parseMode&&(o.parse_mode=t.parseMode),t.replyMarkup&&(o.reply_markup=t.replyMarkup);let s=new AbortController,i=setTimeout(()=>s.abort(),1e4);try{let a=await e(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:s.signal});if(a.ok)return{ok:!0,status:a.status};let c;try{c=(await a.json()).description}catch{c=`HTTP ${a.status}`}return{ok:!1,status:a.status,...c!==void 0?{errorMessage:c}:{}}}catch(a){return{ok:!1,status:0,errorMessage:a instanceof Error?a.message:String(a)}}finally{clearTimeout(i)}}var ns=4096;function Rl(t=ts){return async(e,n)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected an object",isError:!0};let o=e.message;if(typeof o!="string")return{content:"Invalid input: message must be a string",isError:!0};if(o.length===0)return{content:"Invalid input: message must be non-empty",isError:!0};if(o.length>ns)return{content:`Invalid input: message exceeds Telegram's ${ns}-character limit (got ${o.length}). Split into multiple sends or trim before calling.`,isError:!0};let s=process.env.TELEGRAM_BOT_TOKEN;if(!s)return{content:"Telegram is not configured: TELEGRAM_BOT_TOKEN is not set. Run the bot setup wizard or export the env var before using send_telegram.",isError:!0};let i=vt(process.env.AFK_TELEGRAM_ALLOWED_CHAT_IDS);if(i.size===0)return{content:"Telegram is not configured: AFK_TELEGRAM_ALLOWED_CHAT_IDS is empty or unset. Add the operator chat ID(s) before using send_telegram.",isError:!0};let a=[...i],c=[];for(let l of a){let d=await t({token:s,chatId:l,text:o});d.ok||c.push(`chat ${l}: ${d.errorMessage??`HTTP ${d.status}`}`)}return c.length===a.length?{content:`Failed to send Telegram message to any chat. ${c.join("; ")}`,isError:!0}:c.length>0?{content:`Sent Telegram message to ${a.length-c.length}/${a.length} chat(s); ${c.length} failed: ${c.join("; ")}`}:{content:a.length===1?`Sent Telegram message to chat ${a[0]}.`:`Sent Telegram message to ${a.length} chats.`}}}var rs=Rl();var Cl=`
|
|
1501
1501
|
|
|
1502
|
-
[\u2026truncated by agent-afk web_scrape]`,Il="https://r.jina.ai/",Ml="https://s.jina.ai/";function Dl(t){if(!t||typeof t!="object")return{error:"Invalid input: expected an object"};let e=t,n=e.mode??"markdown";if(n!=="markdown"&&n!=="raw"&&n!=="search")return{error:`Invalid input: mode must be one of "markdown", "raw", "search" (got ${JSON.stringify(n)})`};let r=n,o,s;if(r==="search"){if(typeof e.query!="string"||e.query.length===0)return{error:'Invalid input: search mode requires a non-empty "query" string'};s=e.query}else{if(typeof e.url!="string"||e.url.length===0)return{error:`Invalid input: ${r} mode requires a non-empty "url" string`};let c;try{c=new URL(e.url)}catch{return{error:`Invalid input: "${e.url}" is not a valid absolute URL`}}if(c.protocol!=="http:"&&c.protocol!=="https:")return{error:`Invalid input: protocol "${c.protocol}" not supported (http/https only)`};o=c.toString()}let i=3e4;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:"Invalid input: timeout_ms must be a positive finite number"};i=Math.min(e.timeout_ms,12e4)}let a=1e6;if(e.max_bytes!==void 0){if(typeof e.max_bytes!="number"||!Number.isFinite(e.max_bytes)||e.max_bytes<=0)return{error:"Invalid input: max_bytes must be a positive finite number"};a=Math.min(e.max_bytes,1e7)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function Ol(t){return t.mode==="search"?`${Ml}${encodeURIComponent(t.query)}`:t.mode==="markdown"?`${Il}${t.url}`:t.url}function Fl(t,e){let n={"User-Agent":"agent-afk/web_scrape",Accept:t.mode==="raw"?"*/*":"text/plain, text/markdown, */*;q=0.5"};return(t.mode==="markdown"||t.mode==="search")&&e.JINA_API_KEY&&(n.Authorization=`Bearer ${e.JINA_API_KEY}`),n}function Ll(t,e){let n=Buffer.from(t,"utf8");return n.byteLength<=e?t:n.subarray(0,e).toString("utf8")+Cl}function $l(t={}){let e=t.fetchFn??globalThis.fetch,n=t.env??process.env;return async(r,o)=>{if(typeof e!="function")return{content:"web_scrape unavailable: global fetch() is not present in this runtime (agent-afk requires Node 20+).",isError:!0};let s=Dl(r);if("error"in s)return{content:s.error,isError:!0};let i=Ol(s),a=Fl(s,n)
|
|
1502
|
+
[\u2026truncated by agent-afk web_scrape]`,Il="https://r.jina.ai/",Ml="https://s.jina.ai/";function Dl(t){if(!t||typeof t!="object")return{error:"Invalid input: expected an object"};let e=t,n=e.mode??"markdown";if(n!=="markdown"&&n!=="raw"&&n!=="search")return{error:`Invalid input: mode must be one of "markdown", "raw", "search" (got ${JSON.stringify(n)})`};let r=n,o,s;if(r==="search"){if(typeof e.query!="string"||e.query.length===0)return{error:'Invalid input: search mode requires a non-empty "query" string'};s=e.query}else{if(typeof e.url!="string"||e.url.length===0)return{error:`Invalid input: ${r} mode requires a non-empty "url" string`};let c;try{c=new URL(e.url)}catch{return{error:`Invalid input: "${e.url}" is not a valid absolute URL`}}if(c.protocol!=="http:"&&c.protocol!=="https:")return{error:`Invalid input: protocol "${c.protocol}" not supported (http/https only)`};o=c.toString()}let i=3e4;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:"Invalid input: timeout_ms must be a positive finite number"};i=Math.min(e.timeout_ms,12e4)}let a=1e6;if(e.max_bytes!==void 0){if(typeof e.max_bytes!="number"||!Number.isFinite(e.max_bytes)||e.max_bytes<=0)return{error:"Invalid input: max_bytes must be a positive finite number"};a=Math.min(e.max_bytes,1e7)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function Ol(t){return t.mode==="search"?`${Ml}${encodeURIComponent(t.query)}`:t.mode==="markdown"?`${Il}${t.url}`:t.url}function Fl(t,e){let n={"User-Agent":"agent-afk/web_scrape",Accept:t.mode==="raw"?"*/*":"text/plain, text/markdown, */*;q=0.5"};return(t.mode==="markdown"||t.mode==="search")&&e.JINA_API_KEY&&(n.Authorization=`Bearer ${e.JINA_API_KEY}`),n}function Ll(t,e){let n=Buffer.from(t,"utf8");return n.byteLength<=e?t:n.subarray(0,e).toString("utf8")+Cl}function $l(t={}){let e=t.fetchFn??globalThis.fetch,n=t.env??process.env;return async(r,o)=>{if(typeof e!="function")return{content:"web_scrape unavailable: global fetch() is not present in this runtime (agent-afk requires Node 20+).",isError:!0};let s=Dl(r);if("error"in s)return{content:s.error,isError:!0};let i=Ol(s),a=Fl(s,n);if(o.aborted){let u=o.reason;return{content:`web_scrape aborted: ${u instanceof Error?u.message:String(u??"aborted")}`,isError:!0}}let c=new AbortController,l=()=>{c.abort(o.reason)},d;try{o.addEventListener("abort",l,{once:!0}),d=setTimeout(()=>{c.abort(new Error(`web_scrape timeout after ${s.timeoutMs}ms`))},s.timeoutMs);let u;try{u=await e(i,{headers:a,signal:c.signal})}catch(b){if(c.signal.aborted){let m=c.signal.reason;return{content:`web_scrape aborted: ${m instanceof Error?m.message:String(m??"aborted")}`,isError:!0}}return{content:`web_scrape network error: ${b instanceof Error?b.message:String(b)}`,isError:!0}}if(!u.ok)return{content:`web_scrape HTTP ${u.status} ${u.statusText||""}`.trimEnd()+` for ${i}`,isError:!0};let p;try{p=await u.text()}catch(b){return{content:`web_scrape read error: ${b instanceof Error?b.message:String(b)}`,isError:!0}}return{content:Ll(p,s.maxBytes)}}finally{d!==void 0&&clearTimeout(d),o.removeEventListener("abort",l)}}}var os=$l();function St(t,e){let n=t!==void 0?yt(t,e):e!==void 0?yt("default",e):Ko,r=e!==void 0?hn(e):Qo,o=e!==void 0?gn(e):Zo;return new Map([["bash",n],["read_file",qo],["write_file",Vo],["edit_file",Jo],["glob",r],["grep",o],["list_directory",es],["send_telegram",rs],["web_scrape",os]])}var bn=`You have access to tools for working with the filesystem and running commands. Follow these conventions:
|
|
1503
1503
|
|
|
1504
1504
|
- Use read_file before editing to verify the exact content you want to change.
|
|
1505
1505
|
- Prefer edit_file over write_file for modifying existing files \u2014 write_file is for new files or complete rewrites.
|
package/dist/telegram.mjs
CHANGED
|
@@ -1545,7 +1545,7 @@ ${p}`}}catch(c){return{content:`Error: ${c instanceof Error?c.message:String(c)}
|
|
|
1545
1545
|
[output truncated]`),l({content:w})}),d.on("error",g=>{l({content:`Failed to execute grep: ${g.message}`,isError:!0})})})}}var Js=Gn();import{promises as yu}from"fs";var Ys=async(t,e,n)=>{if(!t||typeof t!="object")throw new Error("Invalid input: expected an object");let o=t.path;if(typeof o!="string")throw new Error("Invalid input: path must be a string");let s;try{s=Z(o,n,"read")}catch(i){return{content:i instanceof Error?i.message:String(i),isError:!0}}try{let i=await yu.readdir(s,{withFileTypes:!0}),a=i.filter(d=>d.isDirectory()).map(d=>`${d.name}/`),c=i.filter(d=>!d.isDirectory()).map(d=>d.name);a.sort(),c.sort();let l=[...a,...c];return l.length===0?{content:"(empty directory)"}:{content:l.join(`
|
|
1546
1546
|
`)}}catch(i){if(i instanceof Error){let a=i;return a.code==="ENOENT"?{content:`Directory not found: ${s}`,isError:!0}:a.code==="ENOTDIR"?{content:`Not a directory: ${s}`,isError:!0}:a.code==="EACCES"?{content:`Permission denied: ${s}`,isError:!0}:{content:`Error listing directory: ${i.message}`,isError:!0}}return{content:"Unknown error listing directory",isError:!0}}};var bu="https://api.telegram.org";async function Xs(t){if(!t.token)throw new Error("push: token is required");if(t.chatId===""||t.chatId==null||t.chatId===0)throw new Error("push: chatId is required");let e=t.fetchImpl??fetch,r=`${t.apiBase??bu}/bot${t.token}/sendMessage`,o={chat_id:t.chatId,text:t.text.slice(0,4096)};t.parseMode&&(o.parse_mode=t.parseMode),t.replyMarkup&&(o.reply_markup=t.replyMarkup);let s=new AbortController,i=setTimeout(()=>s.abort(),1e4);try{let a=await e(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:s.signal});if(a.ok)return{ok:!0,status:a.status};let c;try{c=(await a.json()).description}catch{c=`HTTP ${a.status}`}return{ok:!1,status:a.status,...c!==void 0?{errorMessage:c}:{}}}catch(a){return{ok:!1,status:0,errorMessage:a instanceof Error?a.message:String(a)}}finally{clearTimeout(i)}}var Qs=4096;function wu(t=Xs){return async(e,n)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected an object",isError:!0};let o=e.message;if(typeof o!="string")return{content:"Invalid input: message must be a string",isError:!0};if(o.length===0)return{content:"Invalid input: message must be non-empty",isError:!0};if(o.length>Qs)return{content:`Invalid input: message exceeds Telegram's ${Qs}-character limit (got ${o.length}). Split into multiple sends or trim before calling.`,isError:!0};let s=process.env.TELEGRAM_BOT_TOKEN;if(!s)return{content:"Telegram is not configured: TELEGRAM_BOT_TOKEN is not set. Run the bot setup wizard or export the env var before using send_telegram.",isError:!0};let i=Be(process.env.AFK_TELEGRAM_ALLOWED_CHAT_IDS);if(i.size===0)return{content:"Telegram is not configured: AFK_TELEGRAM_ALLOWED_CHAT_IDS is empty or unset. Add the operator chat ID(s) before using send_telegram.",isError:!0};let a=[...i],c=[];for(let l of a){let u=await t({token:s,chatId:l,text:o});u.ok||c.push(`chat ${l}: ${u.errorMessage??`HTTP ${u.status}`}`)}return c.length===a.length?{content:`Failed to send Telegram message to any chat. ${c.join("; ")}`,isError:!0}:c.length>0?{content:`Sent Telegram message to ${a.length-c.length}/${a.length} chat(s); ${c.length} failed: ${c.join("; ")}`}:{content:a.length===1?`Sent Telegram message to chat ${a[0]}.`:`Sent Telegram message to ${a.length} chats.`}}}var Zs=wu();var ku=`
|
|
1547
1547
|
|
|
1548
|
-
[\u2026truncated by agent-afk web_scrape]`,vu="https://r.jina.ai/",Su="https://s.jina.ai/";function xu(t){if(!t||typeof t!="object")return{error:"Invalid input: expected an object"};let e=t,n=e.mode??"markdown";if(n!=="markdown"&&n!=="raw"&&n!=="search")return{error:`Invalid input: mode must be one of "markdown", "raw", "search" (got ${JSON.stringify(n)})`};let r=n,o,s;if(r==="search"){if(typeof e.query!="string"||e.query.length===0)return{error:'Invalid input: search mode requires a non-empty "query" string'};s=e.query}else{if(typeof e.url!="string"||e.url.length===0)return{error:`Invalid input: ${r} mode requires a non-empty "url" string`};let c;try{c=new URL(e.url)}catch{return{error:`Invalid input: "${e.url}" is not a valid absolute URL`}}if(c.protocol!=="http:"&&c.protocol!=="https:")return{error:`Invalid input: protocol "${c.protocol}" not supported (http/https only)`};o=c.toString()}let i=3e4;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:"Invalid input: timeout_ms must be a positive finite number"};i=Math.min(e.timeout_ms,12e4)}let a=1e6;if(e.max_bytes!==void 0){if(typeof e.max_bytes!="number"||!Number.isFinite(e.max_bytes)||e.max_bytes<=0)return{error:"Invalid input: max_bytes must be a positive finite number"};a=Math.min(e.max_bytes,1e7)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function Eu(t){return t.mode==="search"?`${Su}${encodeURIComponent(t.query)}`:t.mode==="markdown"?`${vu}${t.url}`:t.url}function Tu(t,e){let n={"User-Agent":"agent-afk/web_scrape",Accept:t.mode==="raw"?"*/*":"text/plain, text/markdown, */*;q=0.5"};return(t.mode==="markdown"||t.mode==="search")&&e.JINA_API_KEY&&(n.Authorization=`Bearer ${e.JINA_API_KEY}`),n}function _u(t,e){let n=Buffer.from(t,"utf8");return n.byteLength<=e?t:n.subarray(0,e).toString("utf8")+ku}function Au(t={}){let e=t.fetchFn??globalThis.fetch,n=t.env??process.env;return async(r,o)=>{if(typeof e!="function")return{content:"web_scrape unavailable: global fetch() is not present in this runtime (agent-afk requires Node 20+).",isError:!0};let s=xu(r);if("error"in s)return{content:s.error,isError:!0};let i=Eu(s),a=Tu(s,n)
|
|
1548
|
+
[\u2026truncated by agent-afk web_scrape]`,vu="https://r.jina.ai/",Su="https://s.jina.ai/";function xu(t){if(!t||typeof t!="object")return{error:"Invalid input: expected an object"};let e=t,n=e.mode??"markdown";if(n!=="markdown"&&n!=="raw"&&n!=="search")return{error:`Invalid input: mode must be one of "markdown", "raw", "search" (got ${JSON.stringify(n)})`};let r=n,o,s;if(r==="search"){if(typeof e.query!="string"||e.query.length===0)return{error:'Invalid input: search mode requires a non-empty "query" string'};s=e.query}else{if(typeof e.url!="string"||e.url.length===0)return{error:`Invalid input: ${r} mode requires a non-empty "url" string`};let c;try{c=new URL(e.url)}catch{return{error:`Invalid input: "${e.url}" is not a valid absolute URL`}}if(c.protocol!=="http:"&&c.protocol!=="https:")return{error:`Invalid input: protocol "${c.protocol}" not supported (http/https only)`};o=c.toString()}let i=3e4;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:"Invalid input: timeout_ms must be a positive finite number"};i=Math.min(e.timeout_ms,12e4)}let a=1e6;if(e.max_bytes!==void 0){if(typeof e.max_bytes!="number"||!Number.isFinite(e.max_bytes)||e.max_bytes<=0)return{error:"Invalid input: max_bytes must be a positive finite number"};a=Math.min(e.max_bytes,1e7)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function Eu(t){return t.mode==="search"?`${Su}${encodeURIComponent(t.query)}`:t.mode==="markdown"?`${vu}${t.url}`:t.url}function Tu(t,e){let n={"User-Agent":"agent-afk/web_scrape",Accept:t.mode==="raw"?"*/*":"text/plain, text/markdown, */*;q=0.5"};return(t.mode==="markdown"||t.mode==="search")&&e.JINA_API_KEY&&(n.Authorization=`Bearer ${e.JINA_API_KEY}`),n}function _u(t,e){let n=Buffer.from(t,"utf8");return n.byteLength<=e?t:n.subarray(0,e).toString("utf8")+ku}function Au(t={}){let e=t.fetchFn??globalThis.fetch,n=t.env??process.env;return async(r,o)=>{if(typeof e!="function")return{content:"web_scrape unavailable: global fetch() is not present in this runtime (agent-afk requires Node 20+).",isError:!0};let s=xu(r);if("error"in s)return{content:s.error,isError:!0};let i=Eu(s),a=Tu(s,n);if(o.aborted){let d=o.reason;return{content:`web_scrape aborted: ${d instanceof Error?d.message:String(d??"aborted")}`,isError:!0}}let c=new AbortController,l=()=>{c.abort(o.reason)},u;try{o.addEventListener("abort",l,{once:!0}),u=setTimeout(()=>{c.abort(new Error(`web_scrape timeout after ${s.timeoutMs}ms`))},s.timeoutMs);let d;try{d=await e(i,{headers:a,signal:c.signal})}catch(y){if(c.signal.aborted){let g=c.signal.reason;return{content:`web_scrape aborted: ${g instanceof Error?g.message:String(g??"aborted")}`,isError:!0}}return{content:`web_scrape network error: ${y instanceof Error?y.message:String(y)}`,isError:!0}}if(!d.ok)return{content:`web_scrape HTTP ${d.status} ${d.statusText||""}`.trimEnd()+` for ${i}`,isError:!0};let p;try{p=await d.text()}catch(y){return{content:`web_scrape read error: ${y instanceof Error?y.message:String(y)}`,isError:!0}}return{content:_u(p,s.maxBytes)}}finally{u!==void 0&&clearTimeout(u),o.removeEventListener("abort",l)}}}var ei=Au();function ti(t,e){let n=t!==void 0?Ht(t,e):e!==void 0?Ht("default",e):Hs,r=e!==void 0?Wn(e):Vs,o=e!==void 0?Gn(e):Js;return new Map([["bash",n],["read_file",Bs],["write_file",Gs],["edit_file",Ks],["glob",r],["grep",o],["list_directory",Ys],["send_telegram",Zs],["web_scrape",ei]])}var Kn=`You have access to tools for working with the filesystem and running commands. Follow these conventions:
|
|
1549
1549
|
|
|
1550
1550
|
- Use read_file before editing to verify the exact content you want to change.
|
|
1551
1551
|
- Prefer edit_file over write_file for modifying existing files \u2014 write_file is for new files or complete rewrites.
|