tg-agent 1.9.7 → 1.10.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/README.md +2 -0
- package/dist/cli.js +2 -2
- package/package.json +4 -4
package/README.md
CHANGED
package/dist/cli.js
CHANGED
|
@@ -35,7 +35,7 @@ Risk levels:
|
|
|
35
35
|
- "critical": High risk (secrets exposure, destructive ops, network attacks, privilege escalation)
|
|
36
36
|
|
|
37
37
|
Reply format (ONLY this JSON, nothing else):
|
|
38
|
-
{"riskLevel":"none|low|critical","reason":"brief explanation"}`;zn=Kn.join(p.sessionDir,"audit-logs")});import{readFileSync as Fr,existsSync as zr,chmodSync as Kr}from"node:fs";import Jn from"node:path";import{getOAuthProvider as Br}from"@mariozechner/pi-ai";function Z(){return xt||(xt=new St),xt}var St,xt,$t=F(()=>{"use strict";K();J();St=class{filePath;data={};constructor(t){this.filePath=t??Jn.join(p.agentDir,"multi-auth.json"),this.reload()}reload(){if(!zr(this.filePath)){this.data={};return}try{let t=Fr(this.filePath,"utf8");this.data=JSON.parse(t)}catch{this.data={}}}async save(){let t=Jn.dirname(this.filePath);await C(t),await ye(this.filePath,this.data);try{Kr(this.filePath,384)}catch{}}listAccounts(t){let n=this.data[t];return n?Object.entries(n.accounts).map(([r,o])=>({id:r,email:o.email,isDefault:n.defaultAccountId===r,lastUsedAt:o.lastUsedAt})):[]}async addAccount(t,n,r){this.data[t]||(this.data[t]={accounts:{}});let o=`acc_${re()}`,i=n,c=typeof r?.email=="string"?r.email:typeof i.email=="string"?i.email:void 0;return this.data[t].accounts[o]={type:"oauth",refresh:n.refresh,access:n.access,expires:n.expires,email:c,projectId:i.projectId,createdAt:Date.now(),lastUsedAt:Date.now()},this.data[t].defaultAccountId||(this.data[t].defaultAccountId=o),await this.save(),o}getAccount(t,n){return this.data[t]?.accounts[n]??null}getDefaultAccount(t){let n=this.data[t];if(!n?.defaultAccountId)return null;let r=n.accounts[n.defaultAccountId];return r?{id:n.defaultAccountId,credential:r}:null}async setDefaultAccount(t,n){let r=this.data[t];return r?.accounts[n]?(r.defaultAccountId=n,await this.save(),!0):!1}async removeAccount(t,n){let r=this.data[t];if(!r?.accounts[n])return!1;if(delete r.accounts[n],r.defaultAccountId===n){let o=Object.keys(r.accounts);r.defaultAccountId=o[0]}return Object.keys(r.accounts).length===0&&delete this.data[t],await this.save(),!0}async removeAllAccounts(t){let n=this.data[t];if(!n)return 0;let r=Object.keys(n.accounts).length;return delete this.data[t],await this.save(),r}async updateCredential(t,n,r){let o=this.data[t]?.accounts[n];if(!o)return;o.refresh=r.refresh,o.access=r.access,o.expires=r.expires,o.lastUsedAt=Date.now();let i=r;i.projectId!==void 0&&(o.projectId=i.projectId),await this.save()}async getApiKey(t,n){let r=this.data[t]?.accounts[n];if(!r)return null;let o=Br(t);if(!o)return null;let i=Date.now(),c=300*1e3;if(r.expires-i<c)try{let u={refresh:r.refresh,access:r.access,expires:r.expires,...r.projectId!==void 0&&{projectId:r.projectId}},l=await o.refreshToken(u);return await this.updateCredential(t,n,l),o.getApiKey(l)}catch(u){return console.warn(`[multi-auth] token refresh failed for ${t}/${n}:`,u),r.expires>i?o.getApiKey(r):null}return o.getApiKey(r)}hasMultipleAccounts(t){let n=this.data[t]?.accounts;return n?Object.keys(n).length>1:!1}hasAccounts(t){let n=this.data[t]?.accounts;return n?Object.keys(n).length>0:!1}},xt=null});import{chmodSync as Wr,existsSync as Jr,readFileSync as Hr}from"node:fs";import Hn from"node:path";function qr(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,n=typeof t.apiKey=="string"?t.apiKey.trim():"",r=typeof t.baseUrl=="string"?t.baseUrl.trim():"",o=typeof t.updatedAt=="number"?t.updatedAt:Date.now();return!n&&!r?null:{...n?{apiKey:n}:{},...r?{baseUrl:r}:{},updatedAt:o}}function se(){return At||(At=new Mt),At}var Mt,At,kt=F(()=>{"use strict";K();J();Mt=class{filePath;data={};constructor(t){this.filePath=t??Hn.join(p.agentDir,"api-key-auth.json"),this.reload()}reload(){if(!Jr(this.filePath)){this.data={};return}try{let t=JSON.parse(Hr(this.filePath,"utf8"));if(!t||typeof t!="object"||Array.isArray(t)){this.data={};return}let n={};for(let[r,o]of Object.entries(t)){let i=qr(o);i&&(n[r]=i)}this.data=n}catch{this.data={}}}async save(){await C(Hn.dirname(this.filePath)),await ye(this.filePath,this.data);try{Wr(this.filePath,384)}catch{}}upsert(t){let n=this.data[t];if(n)return n;let r={updatedAt:Date.now()};return this.data[t]=r,r}cleanup(t){let n=this.data[t];n&&!n.apiKey&&!n.baseUrl&&delete this.data[t]}listProviders(){return Object.keys(this.data).sort((t,n)=>t.localeCompare(n))}getProviderConfig(t){let n=this.data[t];return n?{...n}:null}hasApiKey(t){return!!this.data[t]?.apiKey}async setApiKey(t,n){let r=this.upsert(t);r.apiKey=n.trim(),r.updatedAt=Date.now(),this.cleanup(t),await this.save()}async clearApiKey(t){let n=this.data[t];return n?.apiKey?(delete n.apiKey,n.updatedAt=Date.now(),this.cleanup(t),await this.save(),!0):!1}async setBaseUrl(t,n){let r=this.upsert(t);r.baseUrl=n.trim(),r.updatedAt=Date.now(),this.cleanup(t),await this.save()}async clearBaseUrl(t){let n=this.data[t];return n?.baseUrl?(delete n.baseUrl,n.updatedAt=Date.now(),this.cleanup(t),await this.save(),!0):!1}},At=null});import{createAgentSession as Vr,AuthStorage as Gr,ModelRegistry as Yr,SessionManager as Xr,SettingsManager as Qr,DefaultResourceLoader as Zr}from"@mariozechner/pi-coding-agent";import qe from"node:fs/promises";import Ve from"node:path";function qn(e){let t=e.trim().toLowerCase();return t==="codex"?"openai-codex":t}function ts(e){if(!e)return;let t=e.trim().toLowerCase();if(t==="oauth")return"oauth";if(t==="api_key"||t==="apikey")return"api_key"}function ns(e,t){let n=e.trim();if(!n)return{provider:t,modelId:""};if(n.includes("/")){let[r,o]=n.split("/",2);return{provider:r.trim()||t,modelId:o.trim()}}return{provider:t,modelId:n}}function os(e,t){return e!=="openai-codex"?t:es[t]??t}function Vn(e,t){let n=e.getAvailable().filter(o=>o.provider===t);return n.length>0?n[0]:e.getAll().filter(o=>o.provider===t)[0]}function rs(e,t,n){let r=Vn(e,t);if(r)return{...r,id:n,name:n}}function ss(e,t){let n=!!t?.provider?.trim(),r=!!t?.modelId?.trim(),o=qn(t?.provider||p.modelProvider||"openai-codex"),i=n||r?"":p.modelRef||"",{provider:c,modelId:u}=ns(i,o),l=t?.provider?o:qn(c),m=r?t?.modelId?.trim()||"":u;if(!m){let f=Vn(e,l);return f?{model:f,provider:l,modelId:f.id,syntheticModel:!1}:{model:void 0,provider:l,modelId:"",syntheticModel:!1}}let s=os(l,m),a=e.find(l,s);if(a)return{model:a,provider:l,modelId:s,syntheticModel:!1};let d=rs(e,l,s);return d?{model:d,provider:l,modelId:s,syntheticModel:!0}:{model:void 0,provider:l,modelId:s,syntheticModel:!1}}function is(e){let t=Q();return t?(e.setRuntimeApiKey("openai-codex",t.accessToken),{source:t.source,expiresAt:t.expiresAt}):null}function as(e){if(e?.role!=="assistant")return"";let n=e.content;if(typeof n=="string")return n.trim();if(!Array.isArray(n))return"";let r=n.filter(i=>typeof i=="object"&&i&&i.type==="text").map(i=>i.text??"").map(i=>i.trim()).filter(Boolean);if(r.length>0)return r.join(`
|
|
38
|
+
{"riskLevel":"none|low|critical","reason":"brief explanation"}`;zn=Kn.join(p.sessionDir,"audit-logs")});import{readFileSync as Fr,existsSync as zr,chmodSync as Kr}from"node:fs";import Jn from"node:path";import{getOAuthProvider as Br}from"@mariozechner/pi-ai/oauth";function Z(){return xt||(xt=new St),xt}var St,xt,$t=F(()=>{"use strict";K();J();St=class{filePath;data={};constructor(t){this.filePath=t??Jn.join(p.agentDir,"multi-auth.json"),this.reload()}reload(){if(!zr(this.filePath)){this.data={};return}try{let t=Fr(this.filePath,"utf8");this.data=JSON.parse(t)}catch{this.data={}}}async save(){let t=Jn.dirname(this.filePath);await C(t),await ye(this.filePath,this.data);try{Kr(this.filePath,384)}catch{}}listAccounts(t){let n=this.data[t];return n?Object.entries(n.accounts).map(([r,o])=>({id:r,email:o.email,isDefault:n.defaultAccountId===r,lastUsedAt:o.lastUsedAt})):[]}async addAccount(t,n,r){this.data[t]||(this.data[t]={accounts:{}});let o=`acc_${re()}`,i=n,c=typeof r?.email=="string"?r.email:typeof i.email=="string"?i.email:void 0;return this.data[t].accounts[o]={type:"oauth",refresh:n.refresh,access:n.access,expires:n.expires,email:c,projectId:i.projectId,createdAt:Date.now(),lastUsedAt:Date.now()},this.data[t].defaultAccountId||(this.data[t].defaultAccountId=o),await this.save(),o}getAccount(t,n){return this.data[t]?.accounts[n]??null}getDefaultAccount(t){let n=this.data[t];if(!n?.defaultAccountId)return null;let r=n.accounts[n.defaultAccountId];return r?{id:n.defaultAccountId,credential:r}:null}async setDefaultAccount(t,n){let r=this.data[t];return r?.accounts[n]?(r.defaultAccountId=n,await this.save(),!0):!1}async removeAccount(t,n){let r=this.data[t];if(!r?.accounts[n])return!1;if(delete r.accounts[n],r.defaultAccountId===n){let o=Object.keys(r.accounts);r.defaultAccountId=o[0]}return Object.keys(r.accounts).length===0&&delete this.data[t],await this.save(),!0}async removeAllAccounts(t){let n=this.data[t];if(!n)return 0;let r=Object.keys(n.accounts).length;return delete this.data[t],await this.save(),r}async updateCredential(t,n,r){let o=this.data[t]?.accounts[n];if(!o)return;o.refresh=r.refresh,o.access=r.access,o.expires=r.expires,o.lastUsedAt=Date.now();let i=r;i.projectId!==void 0&&(o.projectId=i.projectId),await this.save()}async getApiKey(t,n){let r=this.data[t]?.accounts[n];if(!r)return null;let o=Br(t);if(!o)return null;let i=Date.now(),c=300*1e3;if(r.expires-i<c)try{let u={refresh:r.refresh,access:r.access,expires:r.expires,...r.projectId!==void 0&&{projectId:r.projectId}},l=await o.refreshToken(u);return await this.updateCredential(t,n,l),o.getApiKey(l)}catch(u){return console.warn(`[multi-auth] token refresh failed for ${t}/${n}:`,u),r.expires>i?o.getApiKey(r):null}return o.getApiKey(r)}hasMultipleAccounts(t){let n=this.data[t]?.accounts;return n?Object.keys(n).length>1:!1}hasAccounts(t){let n=this.data[t]?.accounts;return n?Object.keys(n).length>0:!1}},xt=null});import{chmodSync as Wr,existsSync as Jr,readFileSync as Hr}from"node:fs";import Hn from"node:path";function qr(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,n=typeof t.apiKey=="string"?t.apiKey.trim():"",r=typeof t.baseUrl=="string"?t.baseUrl.trim():"",o=typeof t.updatedAt=="number"?t.updatedAt:Date.now();return!n&&!r?null:{...n?{apiKey:n}:{},...r?{baseUrl:r}:{},updatedAt:o}}function se(){return At||(At=new Mt),At}var Mt,At,kt=F(()=>{"use strict";K();J();Mt=class{filePath;data={};constructor(t){this.filePath=t??Hn.join(p.agentDir,"api-key-auth.json"),this.reload()}reload(){if(!Jr(this.filePath)){this.data={};return}try{let t=JSON.parse(Hr(this.filePath,"utf8"));if(!t||typeof t!="object"||Array.isArray(t)){this.data={};return}let n={};for(let[r,o]of Object.entries(t)){let i=qr(o);i&&(n[r]=i)}this.data=n}catch{this.data={}}}async save(){await C(Hn.dirname(this.filePath)),await ye(this.filePath,this.data);try{Wr(this.filePath,384)}catch{}}upsert(t){let n=this.data[t];if(n)return n;let r={updatedAt:Date.now()};return this.data[t]=r,r}cleanup(t){let n=this.data[t];n&&!n.apiKey&&!n.baseUrl&&delete this.data[t]}listProviders(){return Object.keys(this.data).sort((t,n)=>t.localeCompare(n))}getProviderConfig(t){let n=this.data[t];return n?{...n}:null}hasApiKey(t){return!!this.data[t]?.apiKey}async setApiKey(t,n){let r=this.upsert(t);r.apiKey=n.trim(),r.updatedAt=Date.now(),this.cleanup(t),await this.save()}async clearApiKey(t){let n=this.data[t];return n?.apiKey?(delete n.apiKey,n.updatedAt=Date.now(),this.cleanup(t),await this.save(),!0):!1}async setBaseUrl(t,n){let r=this.upsert(t);r.baseUrl=n.trim(),r.updatedAt=Date.now(),this.cleanup(t),await this.save()}async clearBaseUrl(t){let n=this.data[t];return n?.baseUrl?(delete n.baseUrl,n.updatedAt=Date.now(),this.cleanup(t),await this.save(),!0):!1}},At=null});import{createAgentSession as Vr,AuthStorage as Gr,ModelRegistry as Yr,SessionManager as Xr,SettingsManager as Qr,DefaultResourceLoader as Zr}from"@mariozechner/pi-coding-agent";import qe from"node:fs/promises";import Ve from"node:path";function qn(e){let t=e.trim().toLowerCase();return t==="codex"?"openai-codex":t}function ts(e){if(!e)return;let t=e.trim().toLowerCase();if(t==="oauth")return"oauth";if(t==="api_key"||t==="apikey")return"api_key"}function ns(e,t){let n=e.trim();if(!n)return{provider:t,modelId:""};if(n.includes("/")){let[r,o]=n.split("/",2);return{provider:r.trim()||t,modelId:o.trim()}}return{provider:t,modelId:n}}function os(e,t){return e!=="openai-codex"?t:es[t]??t}function Vn(e,t){let n=e.getAvailable().filter(o=>o.provider===t);return n.length>0?n[0]:e.getAll().filter(o=>o.provider===t)[0]}function rs(e,t,n){let r=Vn(e,t);if(r)return{...r,id:n,name:n}}function ss(e,t){let n=!!t?.provider?.trim(),r=!!t?.modelId?.trim(),o=qn(t?.provider||p.modelProvider||"openai-codex"),i=n||r?"":p.modelRef||"",{provider:c,modelId:u}=ns(i,o),l=t?.provider?o:qn(c),m=r?t?.modelId?.trim()||"":u;if(!m){let f=Vn(e,l);return f?{model:f,provider:l,modelId:f.id,syntheticModel:!1}:{model:void 0,provider:l,modelId:"",syntheticModel:!1}}let s=os(l,m),a=e.find(l,s);if(a)return{model:a,provider:l,modelId:s,syntheticModel:!1};let d=rs(e,l,s);return d?{model:d,provider:l,modelId:s,syntheticModel:!0}:{model:void 0,provider:l,modelId:s,syntheticModel:!1}}function is(e){let t=Q();return t?(e.setRuntimeApiKey("openai-codex",t.accessToken),{source:t.source,expiresAt:t.expiresAt}):null}function as(e){if(e?.role!=="assistant")return"";let n=e.content;if(typeof n=="string")return n.trim();if(!Array.isArray(n))return"";let r=n.filter(i=>typeof i=="object"&&i&&i.type==="text").map(i=>i.text??"").map(i=>i.trim()).filter(Boolean);if(r.length>0)return r.join(`
|
|
39
39
|
|
|
40
40
|
`);let o=n.filter(i=>typeof i=="object"&&i&&i.type==="thinking").map(i=>i.thinking??"").map(i=>i.trim()).filter(Boolean);return o.length>0?o.join(`
|
|
41
41
|
|
|
@@ -84,7 +84,7 @@ Guidelines:
|
|
|
84
84
|
- Each memory should be self-contained and specific
|
|
85
85
|
- Focus on information that would help Shawn in the future
|
|
86
86
|
- Keep each memory concise (one sentence)
|
|
87
|
-
- Prioritize what matters for Shawn's growth and wellbeing`;ks={"codex-mini-latest":"gpt-5.1-codex-mini","codex-max-latest":"gpt-5.1-codex-max","codex-latest":"gpt-5.2-codex"}});var ki={};import Se from"node:path";import{spawn as Ts}from"node:child_process";import oo from"node:fs/promises";import Es from"node-telegram-bot-api";import{AuthStorage as Ds,ModelRegistry as Os}from"@mariozechner/pi-coding-agent";import{getOAuthProviders as ro,getOAuthProvider as Ns}from"@mariozechner/pi-ai";function Ls(e,t){De.set(e,t)}function Ft(e){De.delete(e)}function Us(e){let t=e.trim();if(t){if(t==="Markdown"||t==="MarkdownV2"||t==="HTML")return t;console.warn(`[tg-agent] invalid TELEGRAM_PARSE_MODE=${t}, ignoring`)}}function Fs(){return Se.join(p.agentDir,"uploads")}function zs(e){return e.length===0?null:e.reduce((t,n)=>{let r=t.file_size??t.width*t.height;return(n.file_size??n.width*n.height)>r?n:t})}function Ks(e){return!!e?.startsWith("image/")}function Bs(e){switch(Se.extname(e).toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".webp":return"image/webp";case".gif":return"image/gif";default:return}}function Ws(e){if(!Number.isFinite(e)||e<=0)return"0 B";let t=["B","KB","MB","GB"],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return`${n.toFixed(n>=10||r===0?0:1)} ${t[r]}`}function Js(e){return e.length===0?"":e.map(t=>{let n=[];t.mimeType&&n.push(t.mimeType),t.bytes>0&&n.push(Ws(t.bytes));let r=n.length>0?` (${n.join(", ")})`:"";return`Attachment saved: ${t.path}${r}`}).join(`
|
|
87
|
+
- Prioritize what matters for Shawn's growth and wellbeing`;ks={"codex-mini-latest":"gpt-5.1-codex-mini","codex-max-latest":"gpt-5.1-codex-max","codex-latest":"gpt-5.2-codex"}});var ki={};import Se from"node:path";import{spawn as Ts}from"node:child_process";import oo from"node:fs/promises";import Es from"node-telegram-bot-api";import{AuthStorage as Ds,ModelRegistry as Os}from"@mariozechner/pi-coding-agent";import{getOAuthProviders as ro,getOAuthProvider as Ns}from"@mariozechner/pi-ai/oauth";function Ls(e,t){De.set(e,t)}function Ft(e){De.delete(e)}function Us(e){let t=e.trim();if(t){if(t==="Markdown"||t==="MarkdownV2"||t==="HTML")return t;console.warn(`[tg-agent] invalid TELEGRAM_PARSE_MODE=${t}, ignoring`)}}function Fs(){return Se.join(p.agentDir,"uploads")}function zs(e){return e.length===0?null:e.reduce((t,n)=>{let r=t.file_size??t.width*t.height;return(n.file_size??n.width*n.height)>r?n:t})}function Ks(e){return!!e?.startsWith("image/")}function Bs(e){switch(Se.extname(e).toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".webp":return"image/webp";case".gif":return"image/gif";default:return}}function Ws(e){if(!Number.isFinite(e)||e<=0)return"0 B";let t=["B","KB","MB","GB"],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return`${n.toFixed(n>=10||r===0?0:1)} ${t[r]}`}function Js(e){return e.length===0?"":e.map(t=>{let n=[];t.mimeType&&n.push(t.mimeType),t.bytes>0&&n.push(Ws(t.bytes));let r=n.length>0?` (${n.join(", ")})`:"";return`Attachment saved: ${t.path}${r}`}).join(`
|
|
88
88
|
`)}function Hs(e){let t=[];if(e.photo&&e.photo.length>0){let n=zs(e.photo);n&&t.push({kind:"photo",fileId:n.file_id,fileSize:n.file_size})}if(e.document&&t.push({kind:"document",fileId:e.document.file_id,fileName:e.document.file_name,mimeType:e.document.mime_type,fileSize:e.document.file_size}),e.audio){let n=e.audio.mime_type?.split("/")[1]??"mp3",r=e.audio.title??e.audio.performer??"audio";t.push({kind:"document",fileId:e.audio.file_id,fileName:`${r}.${n}`,mimeType:e.audio.mime_type,fileSize:e.audio.file_size})}if(e.voice&&t.push({kind:"document",fileId:e.voice.file_id,fileName:`voice.${e.voice.mime_type?.split("/")[1]??"ogg"}`,mimeType:e.voice.mime_type,fileSize:e.voice.file_size}),e.video){let n=e.video.mime_type?.split("/")[1]??"mp4";t.push({kind:"document",fileId:e.video.file_id,fileName:`video.${n}`,mimeType:e.video.mime_type,fileSize:e.video.file_size})}return e.video_note&&t.push({kind:"document",fileId:e.video_note.file_id,fileName:"video_note.mp4",mimeType:"video/mp4",fileSize:e.video_note.file_size}),t}async function qs(e){if(e.length===0)return{resolved:[],images:[]};let t=Fs();await C(t);let n=[],r=[];for(let o of e)try{let i=await N.downloadFile(o.fileId,t),c=await oo.stat(i),u=o.fileName??Se.basename(i),l=o.mimeType??Bs(i),m=o.kind==="photo"||Ks(l),s={path:i,name:u,mimeType:l,bytes:c.size,isImage:m};if(n.push(s),m){let a=await oo.readFile(i);r.push({type:"image",data:a.toString("base64"),mimeType:l??Is})}}catch(i){console.warn("[tg-agent] attachment download failed",i)}return{resolved:n,images:r}}function Re(e,t){let n=0;for(let r=0;r<e.length;r+=1){let o=e[r];if(o==="\\"){r+=1;continue}o===t&&(n+=1)}return n}function Gs(e){if(Re(e,"*")%2!==0||Re(e,"_")%2!==0||Re(e,"`")%2!==0)return!1;let o=Re(e,"["),i=Re(e,"]");return o===i}function Ys(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(n==="\\"){t+=1;continue}if(Vs.has(n))return!1}return!0}function yo(e){let t=Us(p.telegramParseMode);return t?[t]:Ys(e)?["MarkdownV2","Markdown"]:Gs(e)?["Markdown"]:[]}function Ee(e,t){let n=Te.get(e);return n?(clearTimeout(n.timeoutId),Te.delete(e),n.messageId&&N.editMessageReplyMarkup({inline_keyboard:[]},{chat_id:n.chatId,message_id:n.messageId}).catch(()=>{}),n.resolve(t),!0):!1}async function so(e,t,n,r,o){if(Te.has(e))throw new Error("Audit confirmation already pending.");let i=Bt([{label:"Approve",command:"/approve"},{label:"Stop",command:"/stop"}],2),c=await Wt(t,n,i,o);return await new Promise((u,l)=>{let m=setTimeout(()=>{Te.delete(e),N.editMessageText(`${n}
|
|
89
89
|
|
|
90
90
|
[Timed out - Operation blocked]`,{chat_id:t,message_id:c.message_id}).catch(()=>{}),l(new Error("Audit confirmation timed out."))},r);Te.set(e,{resolve:u,reject:l,timeoutId:m,chatId:t,messageThreadId:o,messageId:c.message_id})})}function U(e){let t=e.trim().toLowerCase();return Qs.get(t)??t}function io(e,t){return e!=="openai-codex"?t:Zs[t]??t}async function X(){await C(p.agentDir);let e=Se.join(p.agentDir,"auth.json"),t=new Ds(e),n=Q();n&&t.setRuntimeApiKey("openai-codex",n.accessToken);let r=Se.join(p.agentDir,"models.json"),o=new Os(t,r);return{authStorage:t,modelRegistry:o}}function ho(e){let t=de.get(e);t&&(clearTimeout(t.timeoutId),de.delete(e))}function ei(e,t){let n=de.get(e);n&&(clearTimeout(n.timeoutId),de.delete(e),n.reject(new Error(t)))}async function ao(e,t,n,r){if(de.has(e))throw new Error("Login is already awaiting input.");let o=n.placeholder?`${n.message} (${n.placeholder})`:n.message;return await g(t,o,r),await new Promise((i,c)=>{let u=setTimeout(()=>{de.delete(e),c(new Error("Login prompt timed out."))},Xs);de.set(e,{resolve:i,reject:c,timeoutId:u,chatId:t})})}async function wo(e,t,n){let r=De.get(t);if(!r){await g(e,"No active request to stop.",n);return}r.cancelRequested=!0,r.abortRequested=!0,r.status&&r.status.update("Cancelled by user.",!0),r.abort&&r.abort(),(!r.status||r.chatId!==e)&&await g(e,"Stopping current request...",n)}async function bo(e,t,n,r){let o=await Je(t),i=n||o.activeSessionId;if(!i){await g(e,"No active session to close.",r);return}let c=o.sessions[i];if(c&&c.messages.length>0)try{await g(e,"Reflecting on session memory...",r);let s=await et(c,c.modelProvider,c.modelId);s.reflected?await g(e,"Memory archived successfully.",r):s.error?await g(e,`Memory saved (reflection failed: ${s.error})`,r):await g(e,"Memory saved (no reflection).",r)}catch(s){console.warn("[tg-agent] memory archival failed",s),await g(e,`Memory archival failed: ${ie(s)}`,r)}let u=De.get(t);if(u){if(u.cancelRequested=!0,u.abortRequested=!0,u.status&&u.status.update("Cancelled by user.",!0),u.abort)try{u.abort()}catch(s){console.warn("[tg-agent] abort callback failed during force close",s)}Ft(t)}if(!wt(o,i)){await g(e,`Session not found: ${i}`,r);return}await T(o),await ve(t,i).catch(s=>{console.warn(`[tg-agent] delete session file failed id=${i}`,s)});let m=u?`Force-closed session ${i} (interrupted running task).`:`Closed session ${i}.`;await g(e,m,r)}function ti(){console.log(`[tg-agent] modelProvider=${p.modelProvider} modelRef=${p.modelRef} sessionDir=${p.sessionDir} maxConcurrent=${p.maxConcurrent}`),console.log(`[tg-agent] agentDir=${p.agentDir} workspaceDir=${p.workspaceDir}`);let e=ze(p.agentDir),t=e.length>0?`on (${e.length})`:"off";console.log(`[tg-agent] tools fetchMaxBytes=${p.fetchMaxBytes} fetchTimeoutMs=${p.fetchTimeoutMs} mcp=${t}`),console.log(`[tg-agent] proxy url=${p.proxyUrl||"(none)"} fetchProxy=${p.fetchProxyUrl||"(none)"}`),console.log(`[tg-agent] tls extra_ca=${p.tlsExtraCaCerts||"(empty)"} reject_unauthorized=${p.tlsRejectUnauthorized===null?"(unset)":String(p.tlsRejectUnauthorized)}`);try{let{source:r}=gn(p.modelProvider);console.log(`[tg-agent] authSource=${r}`)}catch(r){let o=r instanceof Error?r.message:String(r);console.warn(`[tg-agent] authSource=missing (${o})`)}let n=hn();console.log(n?`[tg-agent] proxyUrl=${n.url} kind=${n.kind} source=${n.source}`:"[tg-agent] proxyUrl=(none)")}function zt(e){if(!e.startsWith("/"))return null;let t=e.trim(),[n,...r]=t.split(" ");return{command:n.split("@")[0].slice(1).toLowerCase(),args:r.join(" ").trim()}}async function ge(e,t,n){let r=fe(e);return r||(r=He(e,""),await T(e),await g(t,`Created session ${r.id}.`,n)),r}function oi(e,t){let n=se(),r=e.getAll(),o=new Map;for(let i of r){let c=o.get(i.provider)??{count:0,auth:t.hasAuth(i.provider)||n.hasApiKey(i.provider)};c.count+=1,o.set(i.provider,c)}return Array.from(o.entries()).filter(([i])=>ni.has(i)).sort((i,c)=>i[0].localeCompare(c[0])).map(([i,c])=>({label:`${i} (${c.count}, ${c.auth?"ok":"no auth"})`,command:`/provider ${i}`}))}function ri(e,t,n=[]){let r=e.getAll().filter(u=>u.provider===t).sort((u,l)=>u.id.localeCompare(l.id));if(n.length===0)return r.map(u=>({label:u.id,command:`/model ${t}/${u.id}`}));let o=new Map(r.map(u=>[u.id,u])),i=new Set,c=[];for(let u of n){let l=o.get(u);!l||i.has(l.id)||(i.add(l.id),c.push(l))}for(let u of r)i.has(u.id)||c.push(u);return c.map(u=>({label:u.id,command:`/model ${t}/${u.id}`}))}function si(e,t,n=3){let r=new Set,o=[],i=yt(e);for(let c of i){if(c.modelProvider!==t)continue;let u=c.modelId;if(!(!u||r.has(u))&&(r.add(u),o.push(u),o.length>=n))break}return o}function co(e){let t=e.trim();if(!t)return null;let n=t.indexOf(" ");if(n>0){let r=t.slice(0,n).trim(),o=t.slice(n+1).trim();return!r||!o?null:{provider:U(r),modelId:o}}if(t.includes("/")){let r=t.indexOf("/"),o=t.slice(0,r).trim(),i=t.slice(r+1).trim();return!o||!i?null:{provider:U(o),modelId:i}}return{modelId:t}}function Ut(e){if(!e)return;let t=e.trim().toLowerCase();if(t==="oauth")return"oauth";if(t==="api_key"||t==="apikey")return"api_key"}function jt(e){let t=e.trim();return t?t.startsWith("!")?"command(...)":/^[A-Z][A-Z0-9_]{2,}$/.test(t)?`env:${t}`:t.length<=8?`${"*".repeat(Math.max(0,t.length-2))}${t.slice(-2)}`:`${t.slice(0,4)}...${t.slice(-4)}`:"(empty)"}function lo(e){let t=e.trim().toLowerCase();return t==="clear"||t==="remove"||t==="unset"}function uo(e){let t=e.trim();if(!t)return null;let n=t.indexOf(" ");if(n<=0)return null;let r=U(t.slice(0,n)),o=t.slice(n+1).trim();return!r||!o?null:{provider:r,value:o}}function ii(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function vo(e,t){let n=Date.now(),r=mo.get(e)??0;n-r<ai||(mo.set(e,n),console.warn(`[tg-agent] unauthorized user=${e} chat=${t}`))}function xo(e){let t=p.telegramAllowedUsers;return!t||t.size===0?!0:t.has(e)}function ci(e){return e.length===0?"No sessions found.":["Sessions:",...e.map(n=>{let r=new Date(n.updatedAt).toISOString();return`- ${n.id} | ${n.title} | updated ${r}`})].join(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tg-agent",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.10.1",
|
|
4
4
|
"description": "Telegram Agent Bot",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -22,8 +22,8 @@
|
|
|
22
22
|
"dependencies": {
|
|
23
23
|
"@iarna/toml": "^2.2.5",
|
|
24
24
|
"@lancedb/lancedb": "^0.22.3",
|
|
25
|
-
"@mariozechner/pi-ai": "^0.
|
|
26
|
-
"@mariozechner/pi-coding-agent": "^0.
|
|
25
|
+
"@mariozechner/pi-ai": "^0.61.1",
|
|
26
|
+
"@mariozechner/pi-coding-agent": "^0.61.1",
|
|
27
27
|
"@sinclair/typebox": "^0.32.35",
|
|
28
28
|
"https-proxy-agent": "^7.0.5",
|
|
29
29
|
"node-telegram-bot-api": "^0.64.0",
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
"typescript": "^5.6.3"
|
|
40
40
|
},
|
|
41
41
|
"engines": {
|
|
42
|
-
"node": ">=
|
|
42
|
+
"node": ">=20"
|
|
43
43
|
},
|
|
44
44
|
"optionalDependencies": {
|
|
45
45
|
"@lancedb/lancedb-darwin-arm64": "^0.22.3"
|