@kynver-app/runtime 0.2.174 → 0.2.175
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +2 -2
- package/dist/desktop-entry.js +2 -2
- package/dist/index.js +2 -2
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -617,9 +617,9 @@ ${e.slice(a)}`}let o=r[1]??"",s=["PATH","HOME"].filter(a=>!n(o,a));if(s.length==
|
|
|
617
617
|
<key>${a}</key>
|
|
618
618
|
<string>${j_(t[a])}</string>`).join("");return e.replace(r[0],r[0].replace(/<\/dict>$/,`${i}
|
|
619
619
|
</dict>`))}function _1(e={}){let t=e.platform??process.platform;if(t!=="darwin")return{status:"not_macos"};let r=e.env??process.env,n=e.home??(r.HOME?.trim()||yve());try{let o=e.plistFile===void 0?kr({platform:t,home:n,env:r}):null,s=e.plistFile===void 0?o?.supervisor==="launchd"?o.supervisorFile:void 0:e.plistFile;if(!s||!S1(s))return{status:"no_launchd_plist"};let i=si({env:r,home:n,platform:t}),a=bve(gve(s,"utf8"),{PATH:Yu(i,r,{home:n,platform:t}),HOME:n});return a?(S1(`${s}.bak`)||fve(s,`${s}.bak`),hve(s,a),{status:"repaired",file:s,claude:i}):{status:"already_ok",file:s,claude:i}}catch(o){return{status:"failed",detail:o?.message??String(o)}}}var x1=6e4,C1=5*6e4,vve=3,E1=5*6e4;async function V_(e){let t=await Tg(),r=()=>YR(S().agentOsId?.trim())&&!!S().agentOsId?.trim();for(t||console.error(JSON.stringify({event:"chat_claim_loop_waiting",reason:r()?"bridge_not_discovered (rollout off, discovery route missing/404, or API unreachable)":"machine_not_linked",rediscoverMs:C1}));!t&&!e.shouldStop();){if(!r()||(await Qa(C1,e.shouldStop),e.shouldStop()))return;t=await Tg()}if(!t||e.shouldStop())return;let n=JU(process.env,S()),o=new Ug;if(t.security&&(t.security.childEnv=await y1().catch(d=>({ok:!1,leaked:[],error:d instanceof Error?d.message:String(d),at:new Date().toISOString()})),t.security.childEnv.ok||console.error(JSON.stringify({event:"chat_child_env_selftest_failed",...t.security.childEnv}))),t.chatProvider==="anthropic"||!t.chatProvider){UU(t.agentOsId);let d=_1();(d.status==="repaired"||d.status==="failed")&&console.error(JSON.stringify({event:"launchd_plist_env",...d})),qu({force:!0}).then(p=>console.error(JSON.stringify({event:"claude_headless_check",...p}))).catch(()=>{})}console.error(JSON.stringify({event:"chat_claim_loop_start",bridgeUrl:t.bridgeUrl,agentOsId:t.agentOsId,boxId:t.boxId,model:t.model,chatProvider:t.chatProvider,capabilities:Pd(t.chatProvider),useClaudeOauth:t.useClaudeOauth,turnSignature:n,credentialStore:rd(),childEnvSafe:t.security?.childEnv?.ok??null,auth:t.auth?.describe().kind??"api_key"}));let s=0,i=0,a=new Pg,l=v1({target:t,capabilities:d=>{let p=S(),m=Wt(p);return Pd(m,rl(p),Xg(m,p),t.security?.report({policy:n,auth:d.kind,credentialStore:rd(),folderSandbox:oh(process.env,p)}),Nh(),ly(),ay())},onBeat:d=>XP({pid:process.pid,runtimeVersion:fe,at:new Date().toISOString(),heartbeatOk:d,chatTurns:Math.max(0,s-i),commandTurns:i})}),c=Promise.resolve(),u=Date.now()+E1;for(;!e.shouldStop();)try{if((t.chatProvider==="anthropic"||!t.chatProvider)&&Date.now()>=u&&(u=Date.now()+E1,$U().then(p=>p&&console.error(JSON.stringify({event:"claude_login_renewed",...p}))).catch(()=>{})),s>=vve){await Qa(250,e.shouldStop);continue}let d=await R1(t,e.shouldStop,a.snapshot(),n);if(d==="no_credential"){console.error(JSON.stringify({event:"chat_claim_loop_waiting",reason:"machine_not_linked"})),await Qa(x1,e.shouldStop);continue}if(d==="auth_error"){a.onAuthError();let p=t.auth?.describe().hasBoxCredential===!0;await Qa(p?5e3:x1,e.shouldStop);continue}if(a.onSuccess(),d){let p=await b1(t,d.turnId);if(!k1(p.outcome)){console.error(JSON.stringify({event:"chat_turn_receipt_rejected",turnId:d.turnId,requestId:d.requestId??null,status:p.status}));continue}p.outcome!=="accepted"&&console.error(JSON.stringify({event:"chat_turn_receipt_unconfirmed",turnId:d.turnId,outcome:p.outcome,status:p.status}));let m=d.payload?.kind;s+=1;let f;if(m==="command"){i+=1;let g=()=>RS(t,d);f=c.then(g,g),c=f.then(()=>{},()=>{})}else{let g=await wS(t,d,{policy:n,nonces:o});if(!g.ok){s-=1;continue}if(o.markStarted(d.turnId),m==="browser"){let y=await Go(t);f=e1({...t,apiKey:y.bearer},{turnId:d.turnId,payload:g.payload})}else m==="secret"?f=l1(y=>Fe(t,d.turnId,y),{turnId:d.turnId,payload:g.payload},{agentOsId:t.agentOsId,boxId:t.boxId}):m==="terminal"?f=h1(y=>Fe(t,d.turnId,y),{turnId:d.turnId,payload:g.payload},{agentOsId:t.agentOsId,boxId:t.boxId,signed:g.trust.signed},{redactor:()=>wr(t.agentOsId)}):m==="agent-tab"?f=$H(y=>Fe(t,d.turnId,y),{turnId:d.turnId,payload:g.payload,boxId:t.boxId},{late:$F(t),files:UF(t),redactor:wr(t.agentOsId)}):f=ZS(t,{...d,payload:g.payload},g.trust)}f.catch(g=>{console.error(JSON.stringify({event:"chat_turn_execution_crash",turnId:d.turnId,error:g instanceof Error?g.message:String(g)}))}).finally(()=>{s-=1,m==="command"&&(i-=1),m!=="command"&&o.markFinished(d.turnId)})}}catch(d){let{kind:p,consecutive:m,backoffMs:f}=a.onError(d),g=fU(p,m),y=JSON.stringify({event:g.event,level:g.level,error:d instanceof Error?d.message:String(d),kind:p,consecutive:m,retryInMs:f});g.level==="error"?console.error(y):console.log(y),f>0&&await Qa(f,e.shouldStop)}l(),await Yj(),console.error(JSON.stringify({event:"chat_claim_loop_stop"}))}import{existsSync as sV}from"node:fs";import{homedir as Lwe}from"node:os";F();import{readFileSync as I1}from"node:fs";Pt();import{createHash as wve,randomUUID as Rve}from"node:crypto";import{readFileSync as Sve,statSync as _ve}from"node:fs";import{homedir as xve}from"node:os";import A1,{basename as Id}from"node:path";var Cve=8*1024*1024,Eve=20*1024*1024,Ave=/^[\s*_>#~`-]*(?:ACTION NEEDED|NEEDS YOU)\b/im,Pve=new RegExp([String.raw`\b(?:re|h)?captcha\b`,String.raw`\b(?:verification|security|one[- ]time|2fa|two[- ]factor|sms|login|sign[- ]in|auth|authentication|mfa)[- ]code`,String.raw`\bneeds? your (?:approval|ok|go-ahead|sign-?off|reply|answer|decision|input|code)\b`,String.raw`\b(?:please|can you|could you|need you to) (?:approve|confirm|reply|solve|enter|type|send)\b`].join("|"),"i"),Ive=[/\b(?:nothing|none of (?:this|these|them|it))(?:\s+(?:here|else|new|today))?\s+(?:needs?|requires?)\s+(?:your|will'?s)\s+[\w-]+/gi,/\bno (?:action|reply|response|answer|decision|input|approval|sign-?off)s?(?: (?:is|are))? (?:needed|required|necessary)(?: (?:from|by|of) (?:you|will))?/gi,/\bnothing for (?:you|will) to (?:do|decide|answer|approve|reply to)\b/gi,/\b(?:no need to|(?:you|will) (?:don'?t|do not|doesn'?t|does not) need to) (?:reply|answer|respond|decide|approve|do anything)\b/gi,/\bno (?:automatic|auto)[- ]?(?:reply|response|answer)(?:\s+(?:was|has been|is))?(?:\s+sent)?/gi,/(?<!please |can you |could you |need you to )\breply here (?:to|if)\b[^.!?\n]*/gi];function Tve(e){let t=e.replace(/[*_`~]/g,"");for(let r of Ive)t=t.replace(r," ");return t}function Td(e){if(Ave.test(e)||Lve.test(e))return!0;if(Bve(e))return!1;let t=Tve(e);return Pve.test(t)||Dve(t)}var Ove=new RegExp([String.raw`\bneeds? your (?:approval|ok|go-ahead|sign-?off|reply|answer|decision|input|code|pick|choice)\b`,String.raw`\b(?:please|can you|could you|would you|need you to|you need to|(?:will|the user|the owner) needs? to) (?:approve|confirm|reply|answer|solve|enter|type|send|pick|choose|decide|log ?in|sign ?in|run|tap|click|check|review|say)\b`,String.raw`\b(?:approve|reject|ok) or (?:reject|hold|change|not)\b`,String.raw`\bpick one\b`,String.raw`\bwhich (?:one|option)\b`,String.raw`\b(?:it'?s|that'?s) your (?:call|pick|choice)\b|\byour (?:call|pick) on\b`,String.raw`\b(?:let me know|tell me|say) (?:which|whether|if you want)\b`,String.raw`\b(?:decide|choose|pick) (?:between|on|which)\b`,String.raw`\bwhich (?:\w+ ){0,2}(?:should (?:we|i)|do you want|would you like|to (?:use|pick|go with|order from))\b`].join("|"),"i"),Nve=/\b(?:still )?waiting (?:on|for) (?:you|will|the user|the owner)\b(?:\s*\([^)]*\))?[^.\n]*/gi;function Dve(e){let t=e.replace(/[*_`~]/g,"").replace(/https?:\/\/\S+|\]\([^)]*\)/g," ").replace(Nve," ");return t.includes("?")||Ove.test(t)}var Mve=/\b(?:for you:?\s*nothing (?:to do|needed|yet|for now|right now)|nothing (?:is )?(?:needed|required|to do) (?:from|for|by) (?:you|will)|nothing for (?:you|will) to do|no action (?:is )?(?:needed|required)(?: from you| by you| from will)?|you don't need to do anything|no decision (?:is )?needed)\b/i,Lve=/\b(?:re|h)?captcha\b|\b(?:verification|security|one[- ]time|2fa|two[- ]factor|sms|login|sign[- ]in|auth|authentication|mfa)[- ]code/i;function Bve(e){return Mve.test(e.replace(/[*_`~]/g,""))}function $ve(e){return e.ownerRouted===!0||!e.conversationId?!1:!(e.needsUser===!0||Td(e.text))}var J_=/^[A-Za-z0-9._:-]{4,128}$/,Uve=["update","failure","action_needed"];function P1(e){return typeof e=="string"&&Uve.includes(e)}var Fve=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,di=class extends Error{constructor(r,n,o){super(o);this.status=r;this.code=n}status;code},Kve=e=>e===429||e>=500;async function dy(e,t,r){let n=Math.max(1,e.attempts??4),o=e.sleep??(i=>new Promise(a=>setTimeout(a,i))),s=null;for(let i=0;i<n;i++){let a=1e3*2**i;try{let l=await ke(t,await r(),e.fetchImpl??fetch),c=await l.json().catch(()=>({}));if(s={status:l.status,body:c},!Kve(l.status))return s;let u=Number(l.headers.get("retry-after"));Number.isFinite(u)&&u>0&&(a=Math.min(u*1e3,6e4))}catch(l){if(l instanceof di)throw l;s={status:0,body:{code:"network_error",error:l instanceof Error?l.message:String(l)}}}i<n-1&&await o(a)}return s}function py(e,t){return`${e.apiBaseUrl.replace(/\/$/,"")}${t}`}async function G_(e,t={}){let r=await e.authorization();if(!r)throw new di(401,"no_chat_credential","This computer has no chat credential yet. Run `kynver start` (or `kynver setup`) and try again.");return{Authorization:`Bearer ${r}`,...t}}var my=(e,t)=>new di(e.status,String(e.body.code??t),String(e.body.error??`Request failed (${e.status||"network"}).`));async function Wve(e,t,r){let n=`/api/agent-os/by-id/${encodeURIComponent(e.agentOsId)}/agent-tabs/box/uploads`,o=await dy(e,py(e,n),async()=>({method:"POST",headers:await G_(e,{"Content-Type":"application/json"}),body:JSON.stringify({name:Id(t).slice(0,200),size:r.length,sha256:wve("sha256").update(r).digest("hex")})}));if(o.status!==201&&o.status!==200)throw my(o,"upload_failed");let s=Number(o.body.partBytes),i=Number(o.body.parts),a=String(o.body.partUrl??""),l=String(o.body.completeUrl??"");if(!s||!i||!a.includes("{index}")||!l)throw new di(502,"upload_failed","The upload could not be started.");for(let d=0;d<i;d++){let p=r.subarray(d*s,Math.min(r.length,(d+1)*s)),m=await dy(e,py(e,a.replace("{index}",String(d))),async()=>({method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:new Uint8Array(p)}));if(m.status!==200)throw my(m,"upload_failed")}let c=await dy(e,py(e,l),async()=>({method:"POST",headers:await G_(e)})),u=c.body.file;if(c.status!==200||typeof u?.id!="string")throw my(c,"upload_failed");return u.id}function Hve(e,t,r=xve()){let n=Hn(e);if(n.paths.length===0)return{text:e,files:[]};let o=[],s=[];for(let i of n.paths){let a=A1.resolve(dh(i,r)),l=sd(a,r);if(l.reason){s.push(`(${Id(a)} was not attached: ${l.reason.replace(/_/g," ")}.)`);continue}let c=l.real??a;try{t(c)>=0&&o.push(c)}catch{s.push(`(${Id(a)} could not be attached.)`)}}return{text:[n.text,...s].filter(Boolean).join(`
|
|
620
|
-
`),files:o}}async function vl(e,t){let r=e.idempotencyKey?.trim()||`tab-post.${Rve()}`,n=(u,d,p)=>({ok:!1,status:u,code:d,message:p,idempotencyKey:r}),o=e.conversationId?.trim()??"";if(o?!Fve.test(o):!e.target&&!e.topic&&!e.kind)return n(400,"conversation_required","Name the conversation that started the work (--conversation <id> or $KYNVER_CONVERSATION).");if(!J_.test(r))return n(400,"bad_idempotency_key","The key must be 4\u2013128 letters, digits, . _ : -");let s=t.readFile??(u=>Sve(u)),i=t.fileSize??(u=>_ve(u).size),a=Hve(e.text,i),l=[...e.files??[],...a.files.filter(u=>!(e.files??[]).includes(u))];for(let u of e.files??[]){let d=sd(A1.resolve(u)).reason;if(d)return n(400,"file_refused",`${Id(u)} can't be posted from this computer (${d.replace(/_/g," ")}).`)}let c=Lc(t.agentOsId,a.text);if(!c.trim()&&l.length===0)return n(400,"empty_post","Say something or attach a file.");try{let u=[],d=0;for(let k of l){let h,b;try{h=i(k),b=Mm(t.agentOsId,s(k))}catch{return n(400,"file_unreadable",`Can't read ${k}.`)}h<=Cve&&d+h<=Eve?(d+=b.length,u.push({name:Lc(t.agentOsId,Id(k)).slice(0,200),contentBase64:b.toString("base64")})):u.push({fileId:await Wve(t,k,b)})}let p=!e.kind&&$ve({...e,conversationId:o}),m=p?{target:"updates",originConversationId:o}:o?{conversationId:o}:e.topic?{topic:e.topic}:e.target?{target:e.target}:{},f=JSON.stringify({engine:e.engine??"hermes",idempotencyKey:r,...m,...e.kind?{kind:e.kind}:{},text:p?`[\u21B3 from chat](/dashboard/chat?tab=hermes&conversation=${o})
|
|
620
|
+
`),files:o}}async function vl(e,t){let r=e.idempotencyKey?.trim()||`tab-post.${Rve()}`,n=(u,d,p)=>({ok:!1,status:u,code:d,message:p,idempotencyKey:r}),o=e.conversationId?.trim()??"";if(o?!Fve.test(o):!e.target&&!e.topic&&!e.kind)return n(400,"conversation_required","Name the conversation that started the work (--conversation <id> or $KYNVER_CONVERSATION).");if(!J_.test(r))return n(400,"bad_idempotency_key","The key must be 4\u2013128 letters, digits, . _ : -");let s=t.readFile??(u=>Sve(u)),i=t.fileSize??(u=>_ve(u).size),a=Hve(e.text,i),l=[...e.files??[],...a.files.filter(u=>!(e.files??[]).includes(u))];for(let u of e.files??[]){let d=sd(A1.resolve(u)).reason;if(d)return n(400,"file_refused",`${Id(u)} can't be posted from this computer (${d.replace(/_/g," ")}).`)}let c=Lc(t.agentOsId,a.text);if(!c.trim()&&l.length===0)return n(400,"empty_post","Say something or attach a file.");try{let u=[],d=0;for(let k of l){let h,b;try{h=i(k),b=Mm(t.agentOsId,s(k))}catch{return n(400,"file_unreadable",`Can't read ${k}.`)}h<=Cve&&d+h<=Eve?(d+=b.length,u.push({name:Lc(t.agentOsId,Id(k)).slice(0,200),contentBase64:b.toString("base64")})):u.push({fileId:await Wve(t,k,b)})}let p=!e.kind&&!e.pinConversation&&$ve({...e,conversationId:o}),m=p?{target:"updates",originConversationId:o}:o?{conversationId:o}:e.topic?{topic:e.topic}:e.target?{target:e.target}:{},f=JSON.stringify({engine:e.engine??"hermes",idempotencyKey:r,...m,...e.kind?{kind:e.kind}:{},text:p?`[\u21B3 from chat](/dashboard/chat?tab=hermes&conversation=${o})
|
|
621
621
|
|
|
622
|
-
${c}`:c,attachments:u,...e.notify===!1||p?{notify:!1}:{},...e.needsUser?{needsUser:!0}:{},...e.final?{final:!0}:{},...e.ownerRouted?{ownerRouted:!0}:{}}),g=await dy(t,py(t,`/api/agent-os/by-id/${encodeURIComponent(t.agentOsId)}/agent-tabs/box/posts`),async()=>({method:"POST",headers:await G_(t,{"Content-Type":"application/json"}),body:f}));if(g.status===200||g.status===201)return{ok:!0,duplicate:g.body.duplicate===!0,messageId:typeof g.body.messageId=="string"?g.body.messageId:null,conversationId:String(g.body.conversationId??o),idempotencyKey:r};let y=my(g,"post_failed");return n(y.status,y.code,y.message)}catch(u){return u instanceof di?n(u.status,u.code,u.message):n(0,"post_failed",u instanceof Error?u.message:String(u))}}var jve=new Set(["--conversation","--file","--key","--engine","--kind"]);function Vve(e){let t=e?.trim().toLowerCase().replace(/-/g,"_");return P1(t)?t:"update"}function Gve(e,t,r){return e!=="failure"&&(t||Td(r))?"action_needed":e}function Jve(e,t){
|
|
622
|
+
${c}`:c,attachments:u,...e.notify===!1||p?{notify:!1}:{},...e.needsUser?{needsUser:!0}:{},...e.final?{final:!0}:{},...e.ownerRouted?{ownerRouted:!0}:{},...e.pinConversation&&o?{pinConversation:!0}:{}}),g=await dy(t,py(t,`/api/agent-os/by-id/${encodeURIComponent(t.agentOsId)}/agent-tabs/box/posts`),async()=>({method:"POST",headers:await G_(t,{"Content-Type":"application/json"}),body:f}));if(g.status===200||g.status===201)return{ok:!0,duplicate:g.body.duplicate===!0,messageId:typeof g.body.messageId=="string"?g.body.messageId:null,conversationId:String(g.body.conversationId??o),idempotencyKey:r};let y=my(g,"post_failed");return n(y.status,y.code,y.message)}catch(u){return u instanceof di?n(u.status,u.code,u.message):n(0,"post_failed",u instanceof Error?u.message:String(u))}}var jve=new Set(["--conversation","--file","--key","--engine","--kind"]);function Vve(e){let t=e?.trim().toLowerCase().replace(/-/g,"_");return P1(t)?t:"update"}function Gve(e,t,r){return e!=="failure"&&(t||Td(r))?"action_needed":e}function Jve(e,t){if(e.stay)return{kind:e.kind==="action_needed"?"update":e.kind,ownerRouted:!0,pinConversation:!0};let r=Gve(e.kind,e.needsUser,t);return e.explicitConversation&&r!=="action_needed"?{kind:r,pinConversation:!0}:{kind:r}}var Yve="KYNVER_POST_NEEDS_WILL";function qve(e,t=process.env){let r=[],n=[],o,s,i,a,l=!0,c=!1,u=!1,d=!1,p=!1;for(let k=0;k<e.length;k++){let h=e[k];if(jve.has(h)){let b=e[k+1];if(b===void 0||b.startsWith("--")&&b!=="-")return{ok:!1,error:`${h} needs a value`};k++,h==="--conversation"?o=b:h==="--file"?r.push(b):h==="--key"?s=b:h==="--kind"?a=b:i=b;continue}if(h==="--no-notify")l=!1;else if(h==="--needs-you")c=!0;else if(h==="--final")u=!0;else if(h==="--json")p=!0;else if(h==="--stay")d=!0;else{if(h.startsWith("--"))return{ok:!1,error:`unknown flag ${h}`};n.push(h)}}t[Yve]?.trim()==="1"&&(c=!0);let m=o!==void 0&&o.trim().toLowerCase()!=="main",f=o??t[Fg],g=null;if(f?.trim().toLowerCase()==="main")c=!0;else if(f?.trim()&&(g=jo(f),!g))return{ok:!1,error:"--conversation must be a conversation id (uuid)"};if(d&&!g)return{ok:!1,error:"--stay needs --conversation <id>"};let y=i??t[gS]??"hermes";return Zu(y)?{ok:!0,args:{kind:Vve(a),conversationId:g,explicitConversation:m&&g!==null,engine:y,files:r,key:s??null,notify:l,needsUser:c,...u?{final:u}:{},stay:d,json:p,text:n}}:{ok:!1,error:"--engine must be hermes, hermes:<profile>, openclaw, claude-code or grok-bot"}}function zve(e,t,r){return e.length===1&&e[0]==="-"?t():e.length===1&&e[0].startsWith("@")&&e[0].length>1?r(e[0].slice(1)):e.join(" ")}function wl(){let t=S().agentOsId?.trim(),r=Nt();if(!t||!r)return"This computer isn't connected to Kynver yet. Run `kynver setup` first.";let n=new Va({apiBaseUrl:r,agentOsId:t,boxLabel:()=>tn(process.env),loadApiKey:le,loadBoxCredential:()=>ho(t),saveBoxCredential:o=>cm(t,o),clearBoxCredential:um,log:()=>{}});return{apiBaseUrl:r,agentOsId:t,authorization:async()=>{let o=await n.authorization();return o?.kind==="box_token"?o.bearer:ho(t)??null}}}function Xve(e,t){if(t){console.log(JSON.stringify(e));return}e.ok?console.log(`${e.duplicate?"Already posted":"Posted"} to conversation ${e.conversationId} (key ${e.idempotencyKey}).`):console.error(`kynver tab post: ${e.message} (${e.code})${e.status?` \u2014 retry with --key ${e.idempotencyKey}`:""}`)}async function T1(e,t){let r=qve(e);if(!r.ok)return console.error(`kynver tab post: ${r.error}`),process.exitCode=2,null;let{args:n}=r,o;try{o=zve(n.text,()=>I1(0,"utf8"),a=>I1(a,"utf8"))}catch(a){return console.error(`kynver tab post: can't read the text (${a instanceof Error?a.message:String(a)})`),process.exitCode=2,null}let s=t??wl();if(typeof s=="string")return console.error(`kynver tab post: ${s}`),process.exitCode=1,null;let i=await vl({...n.conversationId?{conversationId:n.conversationId}:{},...Jve(n,o),engine:n.engine,text:o,files:n.files,...n.key?{idempotencyKey:n.key}:{},notify:n.notify,...n.final?{final:!0}:{}},s);return Xve(i,n.json),i.ok||(process.exitCode=1),i}import{existsSync as kat,mkdirSync as Qve,readFileSync as Zve,renameSync as ewe,writeFileSync as twe}from"node:fs";import{homedir as rwe}from"node:os";import O1 from"node:path";var nwe=720*60*60*1e3;function Y_(e=rwe()){return O1.join(e,".kynver","hermes-cron-forward.json")}var N1=(e,t)=>`${e}/${t}`;function fy(e,t,r=0){try{let n=JSON.parse(Zve(e,"utf8"));if(n?.version===1&&typeof n.startedAt=="string"&&n.runs&&typeof n.runs=="object")return n}catch{}return{version:1,startedAt:new Date(t-r).toISOString(),runs:{}}}function q_(e,t,r){let n=Object.fromEntries(Object.entries(t.runs).filter(([,s])=>r-Date.parse(s.at)<=nwe||!s.final));Qve(O1.dirname(e),{recursive:!0,mode:448});let o=`${e}.tmp`;twe(o,JSON.stringify({...t,runs:n},null,2),{mode:384}),ewe(o,e)}import{existsSync as owe,readFileSync as swe}from"node:fs";import{homedir as iwe}from"node:os";import awe from"node:path";var lwe="updates",cwe="*",uwe=/^[a-z0-9][a-z0-9._-]{0,63}$/,D1=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,dwe={skip:!1,destination:{kind:"updates"},notify:!0};function z_(e=iwe()){return awe.join(e,".kynver","hermes-cron-routes.json")}var pwe=e=>e.replace(/[._-]+/g," ").replace(/^\w/,t=>t.toUpperCase()).slice(0,80);function mwe(e){if(e==="skip")return{skip:!0};if(!e||typeof e!="object"||Array.isArray(e))return{invalid:'a route is {"topic"}, {"conversationId"} or "skip"'};let t=e,r=t.notify===void 0?!0:t.notify;if(typeof r!="boolean")return{invalid:"notify must be true or false"};if(t.main===!0||typeof t.conversationId=="string"&&t.conversationId.trim().toLowerCase()==="main"){let n=t.fallbackConversationId;return n===void 0?{skip:!1,destination:{kind:"main"},notify:r}:typeof n!="string"||!D1.test(n.trim())?{invalid:"fallbackConversationId must be a uuid"}:{skip:!1,destination:{kind:"main",fallbackConversationId:n.trim()},notify:r}}if(typeof t.conversationId=="string")return D1.test(t.conversationId.trim())?{skip:!1,destination:{kind:"conversation",conversationId:t.conversationId.trim()},notify:r}:{invalid:"conversationId must be a uuid"};if(typeof t.topic=="string"){let n=t.topic.trim();if(!uwe.test(n))return{invalid:"topic must be 1\u201364 lowercase letters, digits, . _ -"};if(n===lwe)return{skip:!1,destination:{kind:"updates"},notify:r};let o=typeof t.title=="string"&&t.title.trim()?t.title.trim().slice(0,80):pwe(n);return{skip:!1,destination:{kind:"topic",key:n,title:o},notify:r}}return{invalid:'a route needs "topic" or "conversationId"'}}function X_(e=z_()){let t={present:!1,fallback:dwe,jobs:new Map,fileError:null};if(!owe(e))return t;let r;try{r=JSON.parse(swe(e,"utf8"))}catch{return{...t,present:!0,fileError:"hermes-cron-routes.json is not valid JSON"}}if(!r||typeof r!="object"||Array.isArray(r))return{...t,present:!0,fileError:"hermes-cron-routes.json must be an object of jobId \u2192 route"};let n={...t,present:!0,jobs:new Map};for(let[o,s]of Object.entries(r)){let i=mwe(s);o===cwe?"invalid"in i?n.fileError=`"*": ${i.invalid}`:n.fallback=i:n.jobs.set(o,i)}return n}function M1(e,t){return e.fileError?{invalid:e.fileError}:e.jobs.get(t)??e.fallback}import{createHash as eV}from"node:crypto";import{existsSync as V1,readFileSync as tV,readdirSync as G1,statSync as J1}from"node:fs";import{homedir as rV}from"node:os";import Rl from"node:path";Pt();async function L1(e,t){try{let r=await t.authorization();if(!r)return{ok:!1,status:401,code:"no_chat_credential"};let n=await ke(`${t.apiBaseUrl.replace(/\/$/,"")}/api/agent-os/by-id/${encodeURIComponent(t.agentOsId)}/agent-tabs/box/telegram-receipts`,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(e)},t.fetchImpl??fetch);if(n.status===200||n.status===201)return{ok:!0};let o=await n.json().catch(()=>({}));return{ok:!1,status:n.status,code:typeof o.code=="string"?o.code:"receipt_failed"}}catch{return{ok:!1,status:0,code:"network_error"}}}var fwe={rate_limit:"the AI account was rate-limited; it'll retry on the next run",provider:"the AI provider couldn't be set up",timeout:"it timed out",other:"it hit an error (details in the log)"},gwe=60*6e4,hwe=3;function B1(e){let t=e.toLowerCase();return/rate[ _-]?limit|\b429\b|too many requests|quota|credential|unauthori[sz]ed|\b401\b|overloaded/.test(t)?"rate_limit":/timed? ?out|timeout|deadline exceeded/.test(t)?"timeout":/resolv\w*\s+(?:the\s+)?provider|provider\s+resol|no provider|unknown provider|provider.*not (?:found|configured)/.test(t)?"provider":"other"}function ywe(e,t){return(e??t).replace(/\s*\(FAILED\)\s*$/i,"").trim()||t}function $1(e,t,r,n,o){return`**${ywe(e,t)}** didn't run this time: ${fwe[r]}.
|
|
623
623
|
|
|
624
624
|
Log: \`${o}\` (run ${n})`}function U1(e,t,r){let o=e&&e.reason===t&&r-Date.parse(e.lastAt)<=gwe?e.count+1:1;return{streak:{reason:t,count:o,lastAt:new Date(r).toISOString()},post:o===1||o===hwe+1}}function F1(e){return/^#{1,3}\s*Prompt\s*$/m.test(e)||/^---\nname:/m.test(e)||/^\s*---\s*\nname:/.test(e)}var K1=3e4,kwe=/^#{1,3}\s*Response\s*$/im,bwe=/^#{1,3}\s*Error\s*$/im,vwe=/^#{1,3}\s*Prompt\s*$/im,wwe=/^#{1,3}\s+\S/m,Rwe=/^#\s*(?:Cron Job:\s*)?(.+?)\s*$/m,Swe=/^\*\*Status:\*\*\s*(?:silent|no_change)\b/im,_we=/^\*\*(?:Job ID|Mode|Run Time):\*\*/m,xwe=/^\*\*(?:Job ID|Run Time|Mode|Schedule):\*\*/;function W1(e){let t=e.replace(/\r\n/g,`
|
|
625
625
|
`),r=Rwe.exec(t)?.[1]?.slice(0,120)??null,n=kwe.exec(t),o=bwe.exec(t);if(!n&&(o||vwe.test(t))){let l=o?t.slice(o.index+o[0].length):"",c=wwe.exec(l.replace(/^\n/,"")),u=(c?l.slice(0,c.index+1):l).trim().slice(0,4e3);return{title:r,text:"",mediaPaths:[],silent:!1,failed:!0,errorText:u}}if(!n&&Swe.test(t))return{title:r,text:"",mediaPaths:[],silent:!0,failed:!1,errorText:""};let s=(n?t.slice(n.index+n[0].length):t).trim();if(!n&&_we.test(t)){let l=/^---\s*$/m.exec(t);s=l?t.slice(l.index+l[0].length).trim():t.split(`
|
package/dist/desktop-entry.js
CHANGED
|
@@ -593,9 +593,9 @@ ${e.slice(a)}`}let o=r[1]??"",s=["PATH","HOME"].filter(a=>!n(o,a));if(s.length==
|
|
|
593
593
|
<key>${a}</key>
|
|
594
594
|
<string>${S_(t[a])}</string>`).join("");return e.replace(r[0],r[0].replace(/<\/dict>$/,`${i}
|
|
595
595
|
</dict>`))}function vV(e={}){let t=e.platform??process.platform;if(t!=="darwin")return{status:"not_macos"};let r=e.env??process.env,n=e.home??(r.HOME?.trim()||mhe());try{let o=e.plistFile===void 0?_a({platform:t,home:n,env:r}):null,s=e.plistFile===void 0?o?.supervisor==="launchd"?o.supervisorFile:void 0:e.plistFile;if(!s||!bV(s))return{status:"no_launchd_plist"};let i=is({env:r,home:n,platform:t}),a=hhe(phe(s,"utf8"),{PATH:Mc(i,r,{home:n,platform:t}),HOME:n});return a?(bV(`${s}.bak`)||dhe(s,`${s}.bak`),fhe(s,a),{status:"repaired",file:s,claude:i}):{status:"already_ok",file:s,claude:i}}catch(o){return{status:"failed",detail:o?.message??String(o)}}}var wV=p(()=>{"use strict";ku();as()});async function __(e){let t=await ym(),r=()=>Ww(I().agentOsId?.trim())&&!!I().agentOsId?.trim();for(t||console.error(JSON.stringify({event:"chat_claim_loop_waiting",reason:r()?"bridge_not_discovered (rollout off, discovery route missing/404, or API unreachable)":"machine_not_linked",rediscoverMs:SV}));!t&&!e.shouldStop();){if(!r()||(await oa(SV,e.shouldStop),e.shouldStop()))return;t=await ym()}if(!t||e.shouldStop())return;let n=_U(process.env,I()),o=new Am;if(t.security&&(t.security.childEnv=await lV().catch(d=>({ok:!1,leaked:[],error:d instanceof Error?d.message:String(d),at:new Date().toISOString()})),t.security.childEnv.ok||console.error(JSON.stringify({event:"chat_child_env_selftest_failed",...t.security.childEnv}))),t.chatProvider==="anthropic"||!t.chatProvider){hU(t.agentOsId);let d=vV();(d.status==="repaired"||d.status==="failed")&&console.error(JSON.stringify({event:"launchd_plist_env",...d})),Dc({force:!0}).then(f=>console.error(JSON.stringify({event:"claude_headless_check",...f}))).catch(()=>{})}console.error(JSON.stringify({event:"chat_claim_loop_start",bridgeUrl:t.bridgeUrl,agentOsId:t.agentOsId,boxId:t.boxId,model:t.model,chatProvider:t.chatProvider,capabilities:vu(t.chatProvider),useClaudeOauth:t.useClaudeOauth,turnSignature:n,credentialStore:Wc(),childEnvSafe:t.security?.childEnv?.ok??null,auth:t.auth?.describe().kind??"api_key"}));let s=0,i=0,a=new mm,l=fV({target:t,capabilities:d=>{let f=I(),m=_r(f);return vu(m,aa(f),Fm(m,f),t.security?.report({policy:n,auth:d.kind,credentialStore:Wc(),folderSandbox:Ym(process.env,f)}),Pg(),sh(),oh())},onBeat:d=>b1({pid:process.pid,runtimeVersion:it,at:new Date().toISOString(),heartbeatOk:d,chatTurns:Math.max(0,s-i),commandTurns:i})}),c=Promise.resolve(),u=Date.now()+_V;for(;!e.shouldStop();)try{if((t.chatProvider==="anthropic"||!t.chatProvider)&&Date.now()>=u&&(u=Date.now()+_V,gU().then(f=>f&&console.error(JSON.stringify({event:"claude_login_renewed",...f}))).catch(()=>{})),s>=yhe){await oa(250,e.shouldStop);continue}let d=await yV(t,e.shouldStop,a.snapshot(),n);if(d==="no_credential"){console.error(JSON.stringify({event:"chat_claim_loop_waiting",reason:"machine_not_linked"})),await oa(RV,e.shouldStop);continue}if(d==="auth_error"){a.onAuthError();let f=t.auth?.describe().hasBoxCredential===!0;await oa(f?5e3:RV,e.shouldStop);continue}if(a.onSuccess(),d){let f=await dV(t,d.turnId);if(!uV(f.outcome)){console.error(JSON.stringify({event:"chat_turn_receipt_rejected",turnId:d.turnId,requestId:d.requestId??null,status:f.status}));continue}f.outcome!=="accepted"&&console.error(JSON.stringify({event:"chat_turn_receipt_unconfirmed",turnId:d.turnId,outcome:f.outcome,status:f.status}));let m=d.payload?.kind;s+=1;let g;if(m==="command"){i+=1;let h=()=>bR(t,d);g=c.then(h,h),c=g.then(()=>{},()=>{})}else{let h=await yR(t,d,{policy:n,nonces:o});if(!h.ok){s-=1;continue}if(o.markStarted(d.turnId),m==="browser"){let k=await no(t);g=N1({...t,apiKey:k.bearer},{turnId:d.turnId,payload:h.payload})}else m==="secret"?g=J1(k=>Ae(t,d.turnId,k),{turnId:d.turnId,payload:h.payload},{agentOsId:t.agentOsId,boxId:t.boxId}):m==="terminal"?g=oV(k=>Ae(t,d.turnId,k),{turnId:d.turnId,payload:h.payload},{agentOsId:t.agentOsId,boxId:t.boxId,signed:h.trust.signed},{redactor:()=>Qt(t.agentOsId)}):m==="agent-tab"?g=VH(k=>Ae(t,d.turnId,k),{turnId:d.turnId,payload:h.payload,boxId:t.boxId},{late:i$(t),files:a$(t),redactor:Qt(t.agentOsId)}):g=lS(t,{...d,payload:h.payload},h.trust)}g.catch(h=>{console.error(JSON.stringify({event:"chat_turn_execution_crash",turnId:d.turnId,error:h instanceof Error?h.message:String(h)}))}).finally(()=>{s-=1,m==="command"&&(i-=1),m!=="command"&&o.markFinished(d.turnId)})}}catch(d){let{kind:f,consecutive:m,backoffMs:g}=a.onError(d),h=WF(f,m),k=JSON.stringify({event:h.event,level:h.level,error:d instanceof Error?d.message:String(d),kind:f,consecutive:m,retryInMs:g});h.level==="error"?console.error(k):console.log(k),g>0&&await oa(g,e.shouldStop)}l(),await h1(),console.error(JSON.stringify({event:"chat_claim_loop_stop"}))}var RV,SV,yhe,_V,xV=p(()=>{"use strict";V();bS();GH();l_();Dn();v1();h_();k_();M1();Y1();sV();Zt();R_();cV();gm();Gc();pV();mV();Zc();eo();Pm();dR();km();cS();kV();vR();Hc();Um();kR();wV();as();RV=6e4,SV=5*6e4,yhe=3,_V=5*6e4});var x_=p(()=>{"use strict";gm();km();kR();vR();cS();xV()});import{createHash as khe,randomUUID as bhe}from"node:crypto";import{readFileSync as vhe,statSync as whe}from"node:fs";import{homedir as Rhe}from"node:os";import CV,{basename as wu}from"node:path";function Ahe(e){let t=e.replace(/[*_`~]/g,"");for(let r of Ehe)t=t.replace(r," ");return t}function uh(e){if(xhe.test(e)||Nhe.test(e))return!0;if(Mhe(e))return!1;let t=Ahe(e);return Che.test(t)||The(t)}function The(e){let t=e.replace(/[*_`~]/g,"").replace(/https?:\/\/\S+|\]\([^)]*\)/g," ").replace(Ihe," ");return t.includes("?")||Phe.test(t)}function Mhe(e){return Ohe.test(e.replace(/[*_`~]/g,""))}function Dhe(e){return e.ownerRouted===!0||!e.conversationId?!1:!(e.needsUser===!0||uh(e.text))}async function ah(e,t,r){let n=Math.max(1,e.attempts??4),o=e.sleep??(i=>new Promise(a=>setTimeout(a,i))),s=null;for(let i=0;i<n;i++){let a=1e3*2**i;try{let l=await we(t,await r(),e.fetchImpl??fetch),c=await l.json().catch(()=>({}));if(s={status:l.status,body:c},!Bhe(l.status))return s;let u=Number(l.headers.get("retry-after"));Number.isFinite(u)&&u>0&&(a=Math.min(u*1e3,6e4))}catch(l){if(l instanceof ys)throw l;s={status:0,body:{code:"network_error",error:l instanceof Error?l.message:String(l)}}}i<n-1&&await o(a)}return s}function lh(e,t){return`${e.apiBaseUrl.replace(/\/$/,"")}${t}`}async function C_(e,t={}){let r=await e.authorization();if(!r)throw new ys(401,"no_chat_credential","This computer has no chat credential yet. Run `kynver start` (or `kynver setup`) and try again.");return{Authorization:`Bearer ${r}`,...t}}async function Fhe(e,t,r){let n=`/api/agent-os/by-id/${encodeURIComponent(e.agentOsId)}/agent-tabs/box/uploads`,o=await ah(e,lh(e,n),async()=>({method:"POST",headers:await C_(e,{"Content-Type":"application/json"}),body:JSON.stringify({name:wu(t).slice(0,200),size:r.length,sha256:khe("sha256").update(r).digest("hex")})}));if(o.status!==201&&o.status!==200)throw ch(o,"upload_failed");let s=Number(o.body.partBytes),i=Number(o.body.parts),a=String(o.body.partUrl??""),l=String(o.body.completeUrl??"");if(!s||!i||!a.includes("{index}")||!l)throw new ys(502,"upload_failed","The upload could not be started.");for(let d=0;d<i;d++){let f=r.subarray(d*s,Math.min(r.length,(d+1)*s)),m=await ah(e,lh(e,a.replace("{index}",String(d))),async()=>({method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:new Uint8Array(f)}));if(m.status!==200)throw ch(m,"upload_failed")}let c=await ah(e,lh(e,l),async()=>({method:"POST",headers:await C_(e)})),u=c.body.file;if(c.status!==200||typeof u?.id!="string")throw ch(c,"upload_failed");return u.id}function Uhe(e,t,r=Rhe()){let n=pn(e);if(n.paths.length===0)return{text:e,files:[]};let o=[],s=[];for(let i of n.paths){let a=CV.resolve(tg(i,r)),l=Jc(a,r);if(l.reason){s.push(`(${wu(a)} was not attached: ${l.reason.replace(/_/g," ")}.)`);continue}let c=l.real??a;try{t(c)>=0&&o.push(c)}catch{s.push(`(${wu(a)} could not be attached.)`)}}return{text:[n.text,...s].filter(Boolean).join(`
|
|
596
|
-
`),files:o}}async function A_(e,t){let r=e.idempotencyKey?.trim()||`tab-post.${bhe()}`,n=(u,d,f)=>({ok:!1,status:u,code:d,message:f,idempotencyKey:r}),o=e.conversationId?.trim()??"";if(o?!Lhe.test(o):!e.target&&!e.topic&&!e.kind)return n(400,"conversation_required","Name the conversation that started the work (--conversation <id> or $KYNVER_CONVERSATION).");if(!E_.test(r))return n(400,"bad_idempotency_key","The key must be 4\u2013128 letters, digits, . _ : -");let s=t.readFile??(u=>vhe(u)),i=t.fileSize??(u=>whe(u).size),a=Uhe(e.text,i),l=[...e.files??[],...a.files.filter(u=>!(e.files??[]).includes(u))];for(let u of e.files??[]){let d=Jc(CV.resolve(u)).reason;if(d)return n(400,"file_refused",`${wu(u)} can't be posted from this computer (${d.replace(/_/g," ")}).`)}let c=_l(t.agentOsId,a.text);if(!c.trim()&&l.length===0)return n(400,"empty_post","Say something or attach a file.");try{let u=[],d=0;for(let v of l){let y,b;try{y=i(v),b=mp(t.agentOsId,s(v))}catch{return n(400,"file_unreadable",`Can't read ${v}.`)}y<=She&&d+y<=_he?(d+=b.length,u.push({name:_l(t.agentOsId,wu(v)).slice(0,200),contentBase64:b.toString("base64")})):u.push({fileId:await Fhe(t,v,b)})}let f=!e.kind&&Dhe({...e,conversationId:o}),m=f?{target:"updates",originConversationId:o}:o?{conversationId:o}:e.topic?{topic:e.topic}:e.target?{target:e.target}:{},g=JSON.stringify({engine:e.engine??"hermes",idempotencyKey:r,...m,...e.kind?{kind:e.kind}:{},text:f?`[\u21B3 from chat](/dashboard/chat?tab=hermes&conversation=${o})
|
|
596
|
+
`),files:o}}async function A_(e,t){let r=e.idempotencyKey?.trim()||`tab-post.${bhe()}`,n=(u,d,f)=>({ok:!1,status:u,code:d,message:f,idempotencyKey:r}),o=e.conversationId?.trim()??"";if(o?!Lhe.test(o):!e.target&&!e.topic&&!e.kind)return n(400,"conversation_required","Name the conversation that started the work (--conversation <id> or $KYNVER_CONVERSATION).");if(!E_.test(r))return n(400,"bad_idempotency_key","The key must be 4\u2013128 letters, digits, . _ : -");let s=t.readFile??(u=>vhe(u)),i=t.fileSize??(u=>whe(u).size),a=Uhe(e.text,i),l=[...e.files??[],...a.files.filter(u=>!(e.files??[]).includes(u))];for(let u of e.files??[]){let d=Jc(CV.resolve(u)).reason;if(d)return n(400,"file_refused",`${wu(u)} can't be posted from this computer (${d.replace(/_/g," ")}).`)}let c=_l(t.agentOsId,a.text);if(!c.trim()&&l.length===0)return n(400,"empty_post","Say something or attach a file.");try{let u=[],d=0;for(let v of l){let y,b;try{y=i(v),b=mp(t.agentOsId,s(v))}catch{return n(400,"file_unreadable",`Can't read ${v}.`)}y<=She&&d+y<=_he?(d+=b.length,u.push({name:_l(t.agentOsId,wu(v)).slice(0,200),contentBase64:b.toString("base64")})):u.push({fileId:await Fhe(t,v,b)})}let f=!e.kind&&!e.pinConversation&&Dhe({...e,conversationId:o}),m=f?{target:"updates",originConversationId:o}:o?{conversationId:o}:e.topic?{topic:e.topic}:e.target?{target:e.target}:{},g=JSON.stringify({engine:e.engine??"hermes",idempotencyKey:r,...m,...e.kind?{kind:e.kind}:{},text:f?`[\u21B3 from chat](/dashboard/chat?tab=hermes&conversation=${o})
|
|
597
597
|
|
|
598
|
-
${c}`:c,attachments:u,...e.notify===!1||f?{notify:!1}:{},...e.needsUser?{needsUser:!0}:{},...e.final?{final:!0}:{},...e.ownerRouted?{ownerRouted:!0}:{}}),h=await ah(t,lh(t,`/api/agent-os/by-id/${encodeURIComponent(t.agentOsId)}/agent-tabs/box/posts`),async()=>({method:"POST",headers:await C_(t,{"Content-Type":"application/json"}),body:g}));if(h.status===200||h.status===201)return{ok:!0,duplicate:h.body.duplicate===!0,messageId:typeof h.body.messageId=="string"?h.body.messageId:null,conversationId:String(h.body.conversationId??o),idempotencyKey:r};let k=ch(h,"post_failed");return n(k.status,k.code,k.message)}catch(u){return u instanceof ys?n(u.status,u.code,u.message):n(0,"post_failed",u instanceof Error?u.message:String(u))}}var She,_he,xhe,Che,Ehe,Phe,Ihe,Ohe,Nhe,E_,Lhe,ys,Bhe,ch,P_=p(()=>{"use strict";mt();Zt();io();She=8*1024*1024,_he=20*1024*1024,xhe=/^[\s*_>#~`-]*(?:ACTION NEEDED|NEEDS YOU)\b/im,Che=new RegExp([String.raw`\b(?:re|h)?captcha\b`,String.raw`\b(?:verification|security|one[- ]time|2fa|two[- ]factor|sms|login|sign[- ]in|auth|authentication|mfa)[- ]code`,String.raw`\bneeds? your (?:approval|ok|go-ahead|sign-?off|reply|answer|decision|input|code)\b`,String.raw`\b(?:please|can you|could you|need you to) (?:approve|confirm|reply|solve|enter|type|send)\b`].join("|"),"i"),Ehe=[/\b(?:nothing|none of (?:this|these|them|it))(?:\s+(?:here|else|new|today))?\s+(?:needs?|requires?)\s+(?:your|will'?s)\s+[\w-]+/gi,/\bno (?:action|reply|response|answer|decision|input|approval|sign-?off)s?(?: (?:is|are))? (?:needed|required|necessary)(?: (?:from|by|of) (?:you|will))?/gi,/\bnothing for (?:you|will) to (?:do|decide|answer|approve|reply to)\b/gi,/\b(?:no need to|(?:you|will) (?:don'?t|do not|doesn'?t|does not) need to) (?:reply|answer|respond|decide|approve|do anything)\b/gi,/\bno (?:automatic|auto)[- ]?(?:reply|response|answer)(?:\s+(?:was|has been|is))?(?:\s+sent)?/gi,/(?<!please |can you |could you |need you to )\breply here (?:to|if)\b[^.!?\n]*/gi];Phe=new RegExp([String.raw`\bneeds? your (?:approval|ok|go-ahead|sign-?off|reply|answer|decision|input|code|pick|choice)\b`,String.raw`\b(?:please|can you|could you|would you|need you to|you need to|(?:will|the user|the owner) needs? to) (?:approve|confirm|reply|answer|solve|enter|type|send|pick|choose|decide|log ?in|sign ?in|run|tap|click|check|review|say)\b`,String.raw`\b(?:approve|reject|ok) or (?:reject|hold|change|not)\b`,String.raw`\bpick one\b`,String.raw`\bwhich (?:one|option)\b`,String.raw`\b(?:it'?s|that'?s) your (?:call|pick|choice)\b|\byour (?:call|pick) on\b`,String.raw`\b(?:let me know|tell me|say) (?:which|whether|if you want)\b`,String.raw`\b(?:decide|choose|pick) (?:between|on|which)\b`,String.raw`\bwhich (?:\w+ ){0,2}(?:should (?:we|i)|do you want|would you like|to (?:use|pick|go with|order from))\b`].join("|"),"i"),Ihe=/\b(?:still )?waiting (?:on|for) (?:you|will|the user|the owner)\b(?:\s*\([^)]*\))?[^.\n]*/gi;Ohe=/\b(?:for you:?\s*nothing (?:to do|needed|yet|for now|right now)|nothing (?:is )?(?:needed|required|to do) (?:from|for|by) (?:you|will)|nothing for (?:you|will) to do|no action (?:is )?(?:needed|required)(?: from you| by you| from will)?|you don't need to do anything|no decision (?:is )?needed)\b/i,Nhe=/\b(?:re|h)?captcha\b|\b(?:verification|security|one[- ]time|2fa|two[- ]factor|sms|login|sign[- ]in|auth|authentication|mfa)[- ]code/i;E_=/^[A-Za-z0-9._:-]{4,128}$/,Lhe=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ys=class extends Error{constructor(r,n,o){super(o);this.status=r;this.code=n}status;code},Bhe=e=>e===429||e>=500;ch=(e,t)=>new ys(e.status,String(e.body.code??t),String(e.body.error??`Request failed (${e.status||"network"}).`))});function EV(){let t=I().agentOsId?.trim(),r=Tt();if(!t||!r)return"This computer isn't connected to Kynver yet. Run `kynver setup` first.";let n=new Yi({apiBaseUrl:r,agentOsId:t,boxLabel:()=>ss(process.env),loadApiKey:Re,loadBoxCredential:()=>Pn(t),saveBoxCredential:o=>Id(t,o),clearBoxCredential:Td,log:()=>{}});return{apiBaseUrl:r,agentOsId:t,authorization:async()=>{let o=await n.authorization();return o?.kind==="box_token"?o.bearer:Pn(t)??null}}}var AV=p(()=>{"use strict";V();Uw();x_();ea();cs();P_()});import{existsSync as LQe,mkdirSync as $he,readFileSync as Khe,renameSync as Whe,writeFileSync as Hhe}from"node:fs";import{homedir as jhe}from"node:os";import PV from"node:path";function IV(e=jhe()){return PV.join(e,".kynver","hermes-cron-forward.json")}function I_(e,t,r=0){try{let n=JSON.parse(Khe(e,"utf8"));if(n?.version===1&&typeof n.startedAt=="string"&&n.runs&&typeof n.runs=="object")return n}catch{}return{version:1,startedAt:new Date(t-r).toISOString(),runs:{}}}function T_(e,t,r){let n=Object.fromEntries(Object.entries(t.runs).filter(([,s])=>r-Date.parse(s.at)<=Vhe||!s.final));$he(PV.dirname(e),{recursive:!0,mode:448});let o=`${e}.tmp`;Hhe(o,JSON.stringify({...t,runs:n},null,2),{mode:384}),Whe(o,e)}var Vhe,TV,O_=p(()=>{"use strict";Vhe=720*60*60*1e3;TV=(e,t)=>`${e}/${t}`});import{existsSync as Ghe,readFileSync as Jhe}from"node:fs";import{homedir as Yhe}from"node:os";import qhe from"node:path";function N_(e=Yhe()){return qhe.join(e,".kynver","hermes-cron-routes.json")}function tye(e){if(e==="skip")return{skip:!0};if(!e||typeof e!="object"||Array.isArray(e))return{invalid:'a route is {"topic"}, {"conversationId"} or "skip"'};let t=e,r=t.notify===void 0?!0:t.notify;if(typeof r!="boolean")return{invalid:"notify must be true or false"};if(t.main===!0||typeof t.conversationId=="string"&&t.conversationId.trim().toLowerCase()==="main"){let n=t.fallbackConversationId;return n===void 0?{skip:!1,destination:{kind:"main"},notify:r}:typeof n!="string"||!OV.test(n.trim())?{invalid:"fallbackConversationId must be a uuid"}:{skip:!1,destination:{kind:"main",fallbackConversationId:n.trim()},notify:r}}if(typeof t.conversationId=="string")return OV.test(t.conversationId.trim())?{skip:!1,destination:{kind:"conversation",conversationId:t.conversationId.trim()},notify:r}:{invalid:"conversationId must be a uuid"};if(typeof t.topic=="string"){let n=t.topic.trim();if(!Qhe.test(n))return{invalid:"topic must be 1\u201364 lowercase letters, digits, . _ -"};if(n===zhe)return{skip:!1,destination:{kind:"updates"},notify:r};let o=typeof t.title=="string"&&t.title.trim()?t.title.trim().slice(0,80):eye(n);return{skip:!1,destination:{kind:"topic",key:n,title:o},notify:r}}return{invalid:'a route needs "topic" or "conversationId"'}}function NV(e=N_()){let t={present:!1,fallback:Zhe,jobs:new Map,fileError:null};if(!Ghe(e))return t;let r;try{r=JSON.parse(Jhe(e,"utf8"))}catch{return{...t,present:!0,fileError:"hermes-cron-routes.json is not valid JSON"}}if(!r||typeof r!="object"||Array.isArray(r))return{...t,present:!0,fileError:"hermes-cron-routes.json must be an object of jobId \u2192 route"};let n={...t,present:!0,jobs:new Map};for(let[o,s]of Object.entries(r)){let i=tye(s);o===Xhe?"invalid"in i?n.fileError=`"*": ${i.invalid}`:n.fallback=i:n.jobs.set(o,i)}return n}function MV(e,t){return e.fileError?{invalid:e.fileError}:e.jobs.get(t)??e.fallback}var zhe,Xhe,Qhe,OV,Zhe,eye,M_=p(()=>{"use strict";zhe="updates",Xhe="*",Qhe=/^[a-z0-9][a-z0-9._-]{0,63}$/,OV=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Zhe={skip:!1,destination:{kind:"updates"},notify:!0};eye=e=>e.replace(/[._-]+/g," ").replace(/^\w/,t=>t.toUpperCase()).slice(0,80)});async function DV(e,t){try{let r=await t.authorization();if(!r)return{ok:!1,status:401,code:"no_chat_credential"};let n=await we(`${t.apiBaseUrl.replace(/\/$/,"")}/api/agent-os/by-id/${encodeURIComponent(t.agentOsId)}/agent-tabs/box/telegram-receipts`,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(e)},t.fetchImpl??fetch);if(n.status===200||n.status===201)return{ok:!0};let o=await n.json().catch(()=>({}));return{ok:!1,status:n.status,code:typeof o.code=="string"?o.code:"receipt_failed"}}catch{return{ok:!1,status:0,code:"network_error"}}}var LV=p(()=>{"use strict";mt()});function BV(e){let t=e.toLowerCase();return/rate[ _-]?limit|\b429\b|too many requests|quota|credential|unauthori[sz]ed|\b401\b|overloaded/.test(t)?"rate_limit":/timed? ?out|timeout|deadline exceeded/.test(t)?"timeout":/resolv\w*\s+(?:the\s+)?provider|provider\s+resol|no provider|unknown provider|provider.*not (?:found|configured)/.test(t)?"provider":"other"}function sye(e,t){return(e??t).replace(/\s*\(FAILED\)\s*$/i,"").trim()||t}function FV(e,t,r,n,o){return`**${sye(e,t)}** didn't run this time: ${rye[r]}.
|
|
598
|
+
${c}`:c,attachments:u,...e.notify===!1||f?{notify:!1}:{},...e.needsUser?{needsUser:!0}:{},...e.final?{final:!0}:{},...e.ownerRouted?{ownerRouted:!0}:{},...e.pinConversation&&o?{pinConversation:!0}:{}}),h=await ah(t,lh(t,`/api/agent-os/by-id/${encodeURIComponent(t.agentOsId)}/agent-tabs/box/posts`),async()=>({method:"POST",headers:await C_(t,{"Content-Type":"application/json"}),body:g}));if(h.status===200||h.status===201)return{ok:!0,duplicate:h.body.duplicate===!0,messageId:typeof h.body.messageId=="string"?h.body.messageId:null,conversationId:String(h.body.conversationId??o),idempotencyKey:r};let k=ch(h,"post_failed");return n(k.status,k.code,k.message)}catch(u){return u instanceof ys?n(u.status,u.code,u.message):n(0,"post_failed",u instanceof Error?u.message:String(u))}}var She,_he,xhe,Che,Ehe,Phe,Ihe,Ohe,Nhe,E_,Lhe,ys,Bhe,ch,P_=p(()=>{"use strict";mt();Zt();io();She=8*1024*1024,_he=20*1024*1024,xhe=/^[\s*_>#~`-]*(?:ACTION NEEDED|NEEDS YOU)\b/im,Che=new RegExp([String.raw`\b(?:re|h)?captcha\b`,String.raw`\b(?:verification|security|one[- ]time|2fa|two[- ]factor|sms|login|sign[- ]in|auth|authentication|mfa)[- ]code`,String.raw`\bneeds? your (?:approval|ok|go-ahead|sign-?off|reply|answer|decision|input|code)\b`,String.raw`\b(?:please|can you|could you|need you to) (?:approve|confirm|reply|solve|enter|type|send)\b`].join("|"),"i"),Ehe=[/\b(?:nothing|none of (?:this|these|them|it))(?:\s+(?:here|else|new|today))?\s+(?:needs?|requires?)\s+(?:your|will'?s)\s+[\w-]+/gi,/\bno (?:action|reply|response|answer|decision|input|approval|sign-?off)s?(?: (?:is|are))? (?:needed|required|necessary)(?: (?:from|by|of) (?:you|will))?/gi,/\bnothing for (?:you|will) to (?:do|decide|answer|approve|reply to)\b/gi,/\b(?:no need to|(?:you|will) (?:don'?t|do not|doesn'?t|does not) need to) (?:reply|answer|respond|decide|approve|do anything)\b/gi,/\bno (?:automatic|auto)[- ]?(?:reply|response|answer)(?:\s+(?:was|has been|is))?(?:\s+sent)?/gi,/(?<!please |can you |could you |need you to )\breply here (?:to|if)\b[^.!?\n]*/gi];Phe=new RegExp([String.raw`\bneeds? your (?:approval|ok|go-ahead|sign-?off|reply|answer|decision|input|code|pick|choice)\b`,String.raw`\b(?:please|can you|could you|would you|need you to|you need to|(?:will|the user|the owner) needs? to) (?:approve|confirm|reply|answer|solve|enter|type|send|pick|choose|decide|log ?in|sign ?in|run|tap|click|check|review|say)\b`,String.raw`\b(?:approve|reject|ok) or (?:reject|hold|change|not)\b`,String.raw`\bpick one\b`,String.raw`\bwhich (?:one|option)\b`,String.raw`\b(?:it'?s|that'?s) your (?:call|pick|choice)\b|\byour (?:call|pick) on\b`,String.raw`\b(?:let me know|tell me|say) (?:which|whether|if you want)\b`,String.raw`\b(?:decide|choose|pick) (?:between|on|which)\b`,String.raw`\bwhich (?:\w+ ){0,2}(?:should (?:we|i)|do you want|would you like|to (?:use|pick|go with|order from))\b`].join("|"),"i"),Ihe=/\b(?:still )?waiting (?:on|for) (?:you|will|the user|the owner)\b(?:\s*\([^)]*\))?[^.\n]*/gi;Ohe=/\b(?:for you:?\s*nothing (?:to do|needed|yet|for now|right now)|nothing (?:is )?(?:needed|required|to do) (?:from|for|by) (?:you|will)|nothing for (?:you|will) to do|no action (?:is )?(?:needed|required)(?: from you| by you| from will)?|you don't need to do anything|no decision (?:is )?needed)\b/i,Nhe=/\b(?:re|h)?captcha\b|\b(?:verification|security|one[- ]time|2fa|two[- ]factor|sms|login|sign[- ]in|auth|authentication|mfa)[- ]code/i;E_=/^[A-Za-z0-9._:-]{4,128}$/,Lhe=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ys=class extends Error{constructor(r,n,o){super(o);this.status=r;this.code=n}status;code},Bhe=e=>e===429||e>=500;ch=(e,t)=>new ys(e.status,String(e.body.code??t),String(e.body.error??`Request failed (${e.status||"network"}).`))});function EV(){let t=I().agentOsId?.trim(),r=Tt();if(!t||!r)return"This computer isn't connected to Kynver yet. Run `kynver setup` first.";let n=new Yi({apiBaseUrl:r,agentOsId:t,boxLabel:()=>ss(process.env),loadApiKey:Re,loadBoxCredential:()=>Pn(t),saveBoxCredential:o=>Id(t,o),clearBoxCredential:Td,log:()=>{}});return{apiBaseUrl:r,agentOsId:t,authorization:async()=>{let o=await n.authorization();return o?.kind==="box_token"?o.bearer:Pn(t)??null}}}var AV=p(()=>{"use strict";V();Uw();x_();ea();cs();P_()});import{existsSync as LQe,mkdirSync as $he,readFileSync as Khe,renameSync as Whe,writeFileSync as Hhe}from"node:fs";import{homedir as jhe}from"node:os";import PV from"node:path";function IV(e=jhe()){return PV.join(e,".kynver","hermes-cron-forward.json")}function I_(e,t,r=0){try{let n=JSON.parse(Khe(e,"utf8"));if(n?.version===1&&typeof n.startedAt=="string"&&n.runs&&typeof n.runs=="object")return n}catch{}return{version:1,startedAt:new Date(t-r).toISOString(),runs:{}}}function T_(e,t,r){let n=Object.fromEntries(Object.entries(t.runs).filter(([,s])=>r-Date.parse(s.at)<=Vhe||!s.final));$he(PV.dirname(e),{recursive:!0,mode:448});let o=`${e}.tmp`;Hhe(o,JSON.stringify({...t,runs:n},null,2),{mode:384}),Whe(o,e)}var Vhe,TV,O_=p(()=>{"use strict";Vhe=720*60*60*1e3;TV=(e,t)=>`${e}/${t}`});import{existsSync as Ghe,readFileSync as Jhe}from"node:fs";import{homedir as Yhe}from"node:os";import qhe from"node:path";function N_(e=Yhe()){return qhe.join(e,".kynver","hermes-cron-routes.json")}function tye(e){if(e==="skip")return{skip:!0};if(!e||typeof e!="object"||Array.isArray(e))return{invalid:'a route is {"topic"}, {"conversationId"} or "skip"'};let t=e,r=t.notify===void 0?!0:t.notify;if(typeof r!="boolean")return{invalid:"notify must be true or false"};if(t.main===!0||typeof t.conversationId=="string"&&t.conversationId.trim().toLowerCase()==="main"){let n=t.fallbackConversationId;return n===void 0?{skip:!1,destination:{kind:"main"},notify:r}:typeof n!="string"||!OV.test(n.trim())?{invalid:"fallbackConversationId must be a uuid"}:{skip:!1,destination:{kind:"main",fallbackConversationId:n.trim()},notify:r}}if(typeof t.conversationId=="string")return OV.test(t.conversationId.trim())?{skip:!1,destination:{kind:"conversation",conversationId:t.conversationId.trim()},notify:r}:{invalid:"conversationId must be a uuid"};if(typeof t.topic=="string"){let n=t.topic.trim();if(!Qhe.test(n))return{invalid:"topic must be 1\u201364 lowercase letters, digits, . _ -"};if(n===zhe)return{skip:!1,destination:{kind:"updates"},notify:r};let o=typeof t.title=="string"&&t.title.trim()?t.title.trim().slice(0,80):eye(n);return{skip:!1,destination:{kind:"topic",key:n,title:o},notify:r}}return{invalid:'a route needs "topic" or "conversationId"'}}function NV(e=N_()){let t={present:!1,fallback:Zhe,jobs:new Map,fileError:null};if(!Ghe(e))return t;let r;try{r=JSON.parse(Jhe(e,"utf8"))}catch{return{...t,present:!0,fileError:"hermes-cron-routes.json is not valid JSON"}}if(!r||typeof r!="object"||Array.isArray(r))return{...t,present:!0,fileError:"hermes-cron-routes.json must be an object of jobId \u2192 route"};let n={...t,present:!0,jobs:new Map};for(let[o,s]of Object.entries(r)){let i=tye(s);o===Xhe?"invalid"in i?n.fileError=`"*": ${i.invalid}`:n.fallback=i:n.jobs.set(o,i)}return n}function MV(e,t){return e.fileError?{invalid:e.fileError}:e.jobs.get(t)??e.fallback}var zhe,Xhe,Qhe,OV,Zhe,eye,M_=p(()=>{"use strict";zhe="updates",Xhe="*",Qhe=/^[a-z0-9][a-z0-9._-]{0,63}$/,OV=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Zhe={skip:!1,destination:{kind:"updates"},notify:!0};eye=e=>e.replace(/[._-]+/g," ").replace(/^\w/,t=>t.toUpperCase()).slice(0,80)});async function DV(e,t){try{let r=await t.authorization();if(!r)return{ok:!1,status:401,code:"no_chat_credential"};let n=await we(`${t.apiBaseUrl.replace(/\/$/,"")}/api/agent-os/by-id/${encodeURIComponent(t.agentOsId)}/agent-tabs/box/telegram-receipts`,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(e)},t.fetchImpl??fetch);if(n.status===200||n.status===201)return{ok:!0};let o=await n.json().catch(()=>({}));return{ok:!1,status:n.status,code:typeof o.code=="string"?o.code:"receipt_failed"}}catch{return{ok:!1,status:0,code:"network_error"}}}var LV=p(()=>{"use strict";mt()});function BV(e){let t=e.toLowerCase();return/rate[ _-]?limit|\b429\b|too many requests|quota|credential|unauthori[sz]ed|\b401\b|overloaded/.test(t)?"rate_limit":/timed? ?out|timeout|deadline exceeded/.test(t)?"timeout":/resolv\w*\s+(?:the\s+)?provider|provider\s+resol|no provider|unknown provider|provider.*not (?:found|configured)/.test(t)?"provider":"other"}function sye(e,t){return(e??t).replace(/\s*\(FAILED\)\s*$/i,"").trim()||t}function FV(e,t,r,n,o){return`**${sye(e,t)}** didn't run this time: ${rye[r]}.
|
|
599
599
|
|
|
600
600
|
Log: \`${o}\` (run ${n})`}function UV(e,t,r){let o=e&&e.reason===t&&r-Date.parse(e.lastAt)<=nye?e.count+1:1;return{streak:{reason:t,count:o,lastAt:new Date(r).toISOString()},post:o===1||o===oye+1}}function $V(e){return/^#{1,3}\s*Prompt\s*$/m.test(e)||/^---\nname:/m.test(e)||/^\s*---\s*\nname:/.test(e)}var rye,nye,oye,KV=p(()=>{"use strict";rye={rate_limit:"the AI account was rate-limited; it'll retry on the next run",provider:"the AI provider couldn't be set up",timeout:"it timed out",other:"it hit an error (details in the log)"},nye=60*6e4,oye=3});function HV(e){let t=e.replace(/\r\n/g,`
|
|
601
601
|
`),r=uye.exec(t)?.[1]?.slice(0,120)??null,n=iye.exec(t),o=aye.exec(t);if(!n&&(o||lye.test(t))){let l=o?t.slice(o.index+o[0].length):"",c=cye.exec(l.replace(/^\n/,"")),u=(c?l.slice(0,c.index+1):l).trim().slice(0,4e3);return{title:r,text:"",mediaPaths:[],silent:!1,failed:!0,errorText:u}}if(!n&&dye.test(t))return{title:r,text:"",mediaPaths:[],silent:!0,failed:!1,errorText:""};let s=(n?t.slice(n.index+n[0].length):t).trim();if(!n&&pye.test(t)){let l=/^---\s*$/m.exec(t);s=l?t.slice(l.index+l[0].length).trim():t.split(`
|
package/dist/index.js
CHANGED
|
@@ -635,9 +635,9 @@ ${e.slice(a)}`}let o=r[1]??"",s=["PATH","HOME"].filter(a=>!n(o,a));if(s.length==
|
|
|
635
635
|
<key>${a}</key>
|
|
636
636
|
<string>${jE(t[a])}</string>`).join("");return e.replace(r[0],r[0].replace(/<\/dict>$/,`${i}
|
|
637
637
|
</dict>`))}function w2(e={}){let t=e.platform??process.platform;if(t!=="darwin")return{status:"not_macos"};let r=e.env??process.env,n=e.home??(r.HOME?.trim()||PSe());try{let o=e.plistFile===void 0?Br({platform:t,home:n,env:r}):null,s=e.plistFile===void 0?o?.supervisor==="launchd"?o.supervisorFile:void 0:e.plistFile;if(!s||!b2(s))return{status:"no_launchd_plist"};let i=Di({env:r,home:n,platform:t}),a=TSe(ESe(s,"utf8"),{PATH:$d(i,r,{home:n,platform:t}),HOME:n});return a?(b2(`${s}.bak`)||xSe(s,`${s}.bak`),ASe(s,a),{status:"repaired",file:s,claude:i}):{status:"already_ok",file:s,claude:i}}catch(o){return{status:"failed",detail:o?.message??String(o)}}}var R2=6e4,S2=5*6e4,OSe=3,_2=5*6e4;async function VE(e){let t=await dy(),r=()=>YC(S().agentOsId?.trim())&&!!S().agentOsId?.trim();for(t||console.error(JSON.stringify({event:"chat_claim_loop_waiting",reason:r()?"bridge_not_discovered (rollout off, discovery route missing/404, or API unreachable)":"machine_not_linked",rediscoverMs:S2}));!t&&!e.shouldStop();){if(!r()||(await Bl(S2,e.shouldStop),e.shouldStop()))return;t=await dy()}if(!t||e.shouldStop())return;let n=jW(process.env,S()),o=new vy;if(t.security&&(t.security.childEnv=await f2().catch(d=>({ok:!1,leaked:[],error:d instanceof Error?d.message:String(d),at:new Date().toISOString()})),t.security.childEnv.ok||console.error(JSON.stringify({event:"chat_child_env_selftest_failed",...t.security.childEnv}))),t.chatProvider==="anthropic"||!t.chatProvider){LW(t.agentOsId);let d=w2();(d.status==="repaired"||d.status==="failed")&&console.error(JSON.stringify({event:"launchd_plist_env",...d})),Fd({force:!0}).then(p=>console.error(JSON.stringify({event:"claude_headless_check",...p}))).catch(()=>{})}console.error(JSON.stringify({event:"chat_claim_loop_start",bridgeUrl:t.bridgeUrl,agentOsId:t.agentOsId,boxId:t.boxId,model:t.model,chatProvider:t.chatProvider,capabilities:bp(t.chatProvider),useClaudeOauth:t.useClaudeOauth,turnSignature:n,credentialStore:Jd(),childEnvSafe:t.security?.childEnv?.ok??null,auth:t.auth?.describe().kind??"api_key"}));let s=0,i=0,a=new cy,l=y2({target:t,capabilities:d=>{let p=S(),m=Yt(p);return bp(m,Kl(p),Ty(m,p),t.security?.report({policy:n,auth:d.kind,credentialStore:Jd(),folderSandbox:Uy(process.env,p)}),mk(),Wk(),Kk())},onBeat:d=>nF({pid:process.pid,runtimeVersion:fe,at:new Date().toISOString(),heartbeatOk:d,chatTurns:Math.max(0,s-i),commandTurns:i})}),c=Promise.resolve(),u=Date.now()+_2;for(;!e.shouldStop();)try{if((t.chatProvider==="anthropic"||!t.chatProvider)&&Date.now()>=u&&(u=Date.now()+_2,MW().then(p=>p&&console.error(JSON.stringify({event:"claude_login_renewed",...p}))).catch(()=>{})),s>=OSe){await Bl(250,e.shouldStop);continue}let d=await v2(t,e.shouldStop,a.snapshot(),n);if(d==="no_credential"){console.error(JSON.stringify({event:"chat_claim_loop_waiting",reason:"machine_not_linked"})),await Bl(R2,e.shouldStop);continue}if(d==="auth_error"){a.onAuthError();let p=t.auth?.describe().hasBoxCredential===!0;await Bl(p?5e3:R2,e.shouldStop);continue}if(a.onSuccess(),d){let p=await h2(t,d.turnId);if(!g2(p.outcome)){console.error(JSON.stringify({event:"chat_turn_receipt_rejected",turnId:d.turnId,requestId:d.requestId??null,status:p.status}));continue}p.outcome!=="accepted"&&console.error(JSON.stringify({event:"chat_turn_receipt_unconfirmed",turnId:d.turnId,outcome:p.outcome,status:p.status}));let m=d.payload?.kind;s+=1;let f;if(m==="command"){i+=1;let g=()=>Rx(t,d);f=c.then(g,g),c=f.then(()=>{},()=>{})}else{let g=await wx(t,d,{policy:n,nonces:o});if(!g.ok){s-=1;continue}if(o.markStarted(d.turnId),m==="browser"){let y=await ds(t);f=XG({...t,apiKey:y.bearer},{turnId:d.turnId,payload:g.payload})}else m==="secret"?f=s2(y=>je(t,d.turnId,y),{turnId:d.turnId,payload:g.payload},{agentOsId:t.agentOsId,boxId:t.boxId}):m==="terminal"?f=m2(y=>je(t,d.turnId,y),{turnId:d.turnId,payload:g.payload},{agentOsId:t.agentOsId,boxId:t.boxId,signed:g.trust.signed},{redactor:()=>Mr(t.agentOsId)}):m==="agent-tab"?f=M1(y=>je(t,d.turnId,y),{turnId:d.turnId,payload:g.payload,boxId:t.boxId},{late:MH(t),files:LH(t),redactor:Mr(t.agentOsId)}):f=Zx(t,{...d,payload:g.payload},g.trust)}f.catch(g=>{console.error(JSON.stringify({event:"chat_turn_execution_crash",turnId:d.turnId,error:g instanceof Error?g.message:String(g)}))}).finally(()=>{s-=1,m==="command"&&(i-=1),m!=="command"&&o.markFinished(d.turnId)})}}catch(d){let{kind:p,consecutive:m,backoffMs:f}=a.onError(d),g=pW(p,m),y=JSON.stringify({event:g.event,level:g.level,error:d instanceof Error?d.message:String(d),kind:p,consecutive:m,retryInMs:f});g.level==="error"?console.error(y):console.log(y),f>0&&await Bl(f,e.shouldStop)}l(),await VG(),console.error(JSON.stringify({event:"chat_claim_loop_stop"}))}import{existsSync as rJ}from"node:fs";import{homedir as Y_e}from"node:os";$();import{readFileSync as E2}from"node:fs";$t();import{createHash as NSe,randomUUID as DSe}from"node:crypto";import{readFileSync as MSe,statSync as LSe}from"node:fs";import{homedir as BSe}from"node:os";import C2,{basename as wp}from"node:path";var USe=8*1024*1024,$Se=20*1024*1024,FSe=/^[\s*_>#~`-]*(?:ACTION NEEDED|NEEDS YOU)\b/im,KSe=new RegExp([String.raw`\b(?:re|h)?captcha\b`,String.raw`\b(?:verification|security|one[- ]time|2fa|two[- ]factor|sms|login|sign[- ]in|auth|authentication|mfa)[- ]code`,String.raw`\bneeds? your (?:approval|ok|go-ahead|sign-?off|reply|answer|decision|input|code)\b`,String.raw`\b(?:please|can you|could you|need you to) (?:approve|confirm|reply|solve|enter|type|send)\b`].join("|"),"i"),WSe=[/\b(?:nothing|none of (?:this|these|them|it))(?:\s+(?:here|else|new|today))?\s+(?:needs?|requires?)\s+(?:your|will'?s)\s+[\w-]+/gi,/\bno (?:action|reply|response|answer|decision|input|approval|sign-?off)s?(?: (?:is|are))? (?:needed|required|necessary)(?: (?:from|by|of) (?:you|will))?/gi,/\bnothing for (?:you|will) to (?:do|decide|answer|approve|reply to)\b/gi,/\b(?:no need to|(?:you|will) (?:don'?t|do not|doesn'?t|does not) need to) (?:reply|answer|respond|decide|approve|do anything)\b/gi,/\bno (?:automatic|auto)[- ]?(?:reply|response|answer)(?:\s+(?:was|has been|is))?(?:\s+sent)?/gi,/(?<!please |can you |could you |need you to )\breply here (?:to|if)\b[^.!?\n]*/gi];function HSe(e){let t=e.replace(/[*_`~]/g,"");for(let r of WSe)t=t.replace(r," ");return t}function Rp(e){if(FSe.test(e)||YSe.test(e))return!0;if(qSe(e))return!1;let t=HSe(e);return KSe.test(t)||GSe(t)}var jSe=new RegExp([String.raw`\bneeds? your (?:approval|ok|go-ahead|sign-?off|reply|answer|decision|input|code|pick|choice)\b`,String.raw`\b(?:please|can you|could you|would you|need you to|you need to|(?:will|the user|the owner) needs? to) (?:approve|confirm|reply|answer|solve|enter|type|send|pick|choose|decide|log ?in|sign ?in|run|tap|click|check|review|say)\b`,String.raw`\b(?:approve|reject|ok) or (?:reject|hold|change|not)\b`,String.raw`\bpick one\b`,String.raw`\bwhich (?:one|option)\b`,String.raw`\b(?:it'?s|that'?s) your (?:call|pick|choice)\b|\byour (?:call|pick) on\b`,String.raw`\b(?:let me know|tell me|say) (?:which|whether|if you want)\b`,String.raw`\b(?:decide|choose|pick) (?:between|on|which)\b`,String.raw`\bwhich (?:\w+ ){0,2}(?:should (?:we|i)|do you want|would you like|to (?:use|pick|go with|order from))\b`].join("|"),"i"),VSe=/\b(?:still )?waiting (?:on|for) (?:you|will|the user|the owner)\b(?:\s*\([^)]*\))?[^.\n]*/gi;function GSe(e){let t=e.replace(/[*_`~]/g,"").replace(/https?:\/\/\S+|\]\([^)]*\)/g," ").replace(VSe," ");return t.includes("?")||jSe.test(t)}var JSe=/\b(?:for you:?\s*nothing (?:to do|needed|yet|for now|right now)|nothing (?:is )?(?:needed|required|to do) (?:from|for|by) (?:you|will)|nothing for (?:you|will) to do|no action (?:is )?(?:needed|required)(?: from you| by you| from will)?|you don't need to do anything|no decision (?:is )?needed)\b/i,YSe=/\b(?:re|h)?captcha\b|\b(?:verification|security|one[- ]time|2fa|two[- ]factor|sms|login|sign[- ]in|auth|authentication|mfa)[- ]code/i;function qSe(e){return JSe.test(e.replace(/[*_`~]/g,""))}function zSe(e){return e.ownerRouted===!0||!e.conversationId?!1:!(e.needsUser===!0||Rp(e.text))}var JE=/^[A-Za-z0-9._:-]{4,128}$/,XSe=["update","failure","action_needed"];function x2(e){return typeof e=="string"&&XSe.includes(e)}var QSe=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Fi=class extends Error{constructor(r,n,o){super(o);this.status=r;this.code=n}status;code},ZSe=e=>e===429||e>=500;async function Vk(e,t,r){let n=Math.max(1,e.attempts??4),o=e.sleep??(i=>new Promise(a=>setTimeout(a,i))),s=null;for(let i=0;i<n;i++){let a=1e3*2**i;try{let l=await ke(t,await r(),e.fetchImpl??fetch),c=await l.json().catch(()=>({}));if(s={status:l.status,body:c},!ZSe(l.status))return s;let u=Number(l.headers.get("retry-after"));Number.isFinite(u)&&u>0&&(a=Math.min(u*1e3,6e4))}catch(l){if(l instanceof Fi)throw l;s={status:0,body:{code:"network_error",error:l instanceof Error?l.message:String(l)}}}i<n-1&&await o(a)}return s}function Gk(e,t){return`${e.apiBaseUrl.replace(/\/$/,"")}${t}`}async function GE(e,t={}){let r=await e.authorization();if(!r)throw new Fi(401,"no_chat_credential","This computer has no chat credential yet. Run `kynver start` (or `kynver setup`) and try again.");return{Authorization:`Bearer ${r}`,...t}}var Jk=(e,t)=>new Fi(e.status,String(e.body.code??t),String(e.body.error??`Request failed (${e.status||"network"}).`));async function e_e(e,t,r){let n=`/api/agent-os/by-id/${encodeURIComponent(e.agentOsId)}/agent-tabs/box/uploads`,o=await Vk(e,Gk(e,n),async()=>({method:"POST",headers:await GE(e,{"Content-Type":"application/json"}),body:JSON.stringify({name:wp(t).slice(0,200),size:r.length,sha256:NSe("sha256").update(r).digest("hex")})}));if(o.status!==201&&o.status!==200)throw Jk(o,"upload_failed");let s=Number(o.body.partBytes),i=Number(o.body.parts),a=String(o.body.partUrl??""),l=String(o.body.completeUrl??"");if(!s||!i||!a.includes("{index}")||!l)throw new Fi(502,"upload_failed","The upload could not be started.");for(let d=0;d<i;d++){let p=r.subarray(d*s,Math.min(r.length,(d+1)*s)),m=await Vk(e,Gk(e,a.replace("{index}",String(d))),async()=>({method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:new Uint8Array(p)}));if(m.status!==200)throw Jk(m,"upload_failed")}let c=await Vk(e,Gk(e,l),async()=>({method:"POST",headers:await GE(e)})),u=c.body.file;if(c.status!==200||typeof u?.id!="string")throw Jk(c,"upload_failed");return u.id}function t_e(e,t,r=BSe()){let n=lo(e);if(n.paths.length===0)return{text:e,files:[]};let o=[],s=[];for(let i of n.paths){let a=C2.resolve(Vy(i,r)),l=zd(a,r);if(l.reason){s.push(`(${wp(a)} was not attached: ${l.reason.replace(/_/g," ")}.)`);continue}let c=l.real??a;try{t(c)>=0&&o.push(c)}catch{s.push(`(${wp(a)} could not be attached.)`)}}return{text:[n.text,...s].filter(Boolean).join(`
|
|
638
|
-
`),files:o}}async function sc(e,t){let r=e.idempotencyKey?.trim()||`tab-post.${DSe()}`,n=(u,d,p)=>({ok:!1,status:u,code:d,message:p,idempotencyKey:r}),o=e.conversationId?.trim()??"";if(o?!QSe.test(o):!e.target&&!e.topic&&!e.kind)return n(400,"conversation_required","Name the conversation that started the work (--conversation <id> or $KYNVER_CONVERSATION).");if(!JE.test(r))return n(400,"bad_idempotency_key","The key must be 4\u2013128 letters, digits, . _ : -");let s=t.readFile??(u=>MSe(u)),i=t.fileSize??(u=>LSe(u).size),a=t_e(e.text,i),l=[...e.files??[],...a.files.filter(u=>!(e.files??[]).includes(u))];for(let u of e.files??[]){let d=zd(C2.resolve(u)).reason;if(d)return n(400,"file_refused",`${wp(u)} can't be posted from this computer (${d.replace(/_/g," ")}).`)}let c=Ju(t.agentOsId,a.text);if(!c.trim()&&l.length===0)return n(400,"empty_post","Say something or attach a file.");try{let u=[],d=0;for(let k of l){let h,v;try{h=i(k),v=Hg(t.agentOsId,s(k))}catch{return n(400,"file_unreadable",`Can't read ${k}.`)}h<=USe&&d+h<=$Se?(d+=v.length,u.push({name:Ju(t.agentOsId,wp(k)).slice(0,200),contentBase64:v.toString("base64")})):u.push({fileId:await e_e(t,k,v)})}let p=!e.kind&&zSe({...e,conversationId:o}),m=p?{target:"updates",originConversationId:o}:o?{conversationId:o}:e.topic?{topic:e.topic}:e.target?{target:e.target}:{},f=JSON.stringify({engine:e.engine??"hermes",idempotencyKey:r,...m,...e.kind?{kind:e.kind}:{},text:p?`[\u21B3 from chat](/dashboard/chat?tab=hermes&conversation=${o})
|
|
638
|
+
`),files:o}}async function sc(e,t){let r=e.idempotencyKey?.trim()||`tab-post.${DSe()}`,n=(u,d,p)=>({ok:!1,status:u,code:d,message:p,idempotencyKey:r}),o=e.conversationId?.trim()??"";if(o?!QSe.test(o):!e.target&&!e.topic&&!e.kind)return n(400,"conversation_required","Name the conversation that started the work (--conversation <id> or $KYNVER_CONVERSATION).");if(!JE.test(r))return n(400,"bad_idempotency_key","The key must be 4\u2013128 letters, digits, . _ : -");let s=t.readFile??(u=>MSe(u)),i=t.fileSize??(u=>LSe(u).size),a=t_e(e.text,i),l=[...e.files??[],...a.files.filter(u=>!(e.files??[]).includes(u))];for(let u of e.files??[]){let d=zd(C2.resolve(u)).reason;if(d)return n(400,"file_refused",`${wp(u)} can't be posted from this computer (${d.replace(/_/g," ")}).`)}let c=Ju(t.agentOsId,a.text);if(!c.trim()&&l.length===0)return n(400,"empty_post","Say something or attach a file.");try{let u=[],d=0;for(let k of l){let h,v;try{h=i(k),v=Hg(t.agentOsId,s(k))}catch{return n(400,"file_unreadable",`Can't read ${k}.`)}h<=USe&&d+h<=$Se?(d+=v.length,u.push({name:Ju(t.agentOsId,wp(k)).slice(0,200),contentBase64:v.toString("base64")})):u.push({fileId:await e_e(t,k,v)})}let p=!e.kind&&!e.pinConversation&&zSe({...e,conversationId:o}),m=p?{target:"updates",originConversationId:o}:o?{conversationId:o}:e.topic?{topic:e.topic}:e.target?{target:e.target}:{},f=JSON.stringify({engine:e.engine??"hermes",idempotencyKey:r,...m,...e.kind?{kind:e.kind}:{},text:p?`[\u21B3 from chat](/dashboard/chat?tab=hermes&conversation=${o})
|
|
639
639
|
|
|
640
|
-
${c}`:c,attachments:u,...e.notify===!1||p?{notify:!1}:{},...e.needsUser?{needsUser:!0}:{},...e.final?{final:!0}:{},...e.ownerRouted?{ownerRouted:!0}:{}}),g=await Vk(t,Gk(t,`/api/agent-os/by-id/${encodeURIComponent(t.agentOsId)}/agent-tabs/box/posts`),async()=>({method:"POST",headers:await GE(t,{"Content-Type":"application/json"}),body:f}));if(g.status===200||g.status===201)return{ok:!0,duplicate:g.body.duplicate===!0,messageId:typeof g.body.messageId=="string"?g.body.messageId:null,conversationId:String(g.body.conversationId??o),idempotencyKey:r};let y=Jk(g,"post_failed");return n(y.status,y.code,y.message)}catch(u){return u instanceof Fi?n(u.status,u.code,u.message):n(0,"post_failed",u instanceof Error?u.message:String(u))}}var r_e=new Set(["--conversation","--file","--key","--engine","--kind"]);function n_e(e){let t=e?.trim().toLowerCase().replace(/-/g,"_");return x2(t)?t:"update"}function o_e(e,t,r){return e!=="failure"&&(t||Rp(r))?"action_needed":e}function s_e(e,t){
|
|
640
|
+
${c}`:c,attachments:u,...e.notify===!1||p?{notify:!1}:{},...e.needsUser?{needsUser:!0}:{},...e.final?{final:!0}:{},...e.ownerRouted?{ownerRouted:!0}:{},...e.pinConversation&&o?{pinConversation:!0}:{}}),g=await Vk(t,Gk(t,`/api/agent-os/by-id/${encodeURIComponent(t.agentOsId)}/agent-tabs/box/posts`),async()=>({method:"POST",headers:await GE(t,{"Content-Type":"application/json"}),body:f}));if(g.status===200||g.status===201)return{ok:!0,duplicate:g.body.duplicate===!0,messageId:typeof g.body.messageId=="string"?g.body.messageId:null,conversationId:String(g.body.conversationId??o),idempotencyKey:r};let y=Jk(g,"post_failed");return n(y.status,y.code,y.message)}catch(u){return u instanceof Fi?n(u.status,u.code,u.message):n(0,"post_failed",u instanceof Error?u.message:String(u))}}var r_e=new Set(["--conversation","--file","--key","--engine","--kind"]);function n_e(e){let t=e?.trim().toLowerCase().replace(/-/g,"_");return x2(t)?t:"update"}function o_e(e,t,r){return e!=="failure"&&(t||Rp(r))?"action_needed":e}function s_e(e,t){if(e.stay)return{kind:e.kind==="action_needed"?"update":e.kind,ownerRouted:!0,pinConversation:!0};let r=o_e(e.kind,e.needsUser,t);return e.explicitConversation&&r!=="action_needed"?{kind:r,pinConversation:!0}:{kind:r}}var i_e="KYNVER_POST_NEEDS_WILL";function a_e(e,t=process.env){let r=[],n=[],o,s,i,a,l=!0,c=!1,u=!1,d=!1,p=!1;for(let k=0;k<e.length;k++){let h=e[k];if(r_e.has(h)){let v=e[k+1];if(v===void 0||v.startsWith("--")&&v!=="-")return{ok:!1,error:`${h} needs a value`};k++,h==="--conversation"?o=v:h==="--file"?r.push(v):h==="--key"?s=v:h==="--kind"?a=v:i=v;continue}if(h==="--no-notify")l=!1;else if(h==="--needs-you")c=!0;else if(h==="--final")u=!0;else if(h==="--json")p=!0;else if(h==="--stay")d=!0;else{if(h.startsWith("--"))return{ok:!1,error:`unknown flag ${h}`};n.push(h)}}t[i_e]?.trim()==="1"&&(c=!0);let m=o!==void 0&&o.trim().toLowerCase()!=="main",f=o??t[by],g=null;if(f?.trim().toLowerCase()==="main")c=!0;else if(f?.trim()&&(g=cs(f),!g))return{ok:!1,error:"--conversation must be a conversation id (uuid)"};if(d&&!g)return{ok:!1,error:"--stay needs --conversation <id>"};let y=i??t[gx]??"hermes";return jd(y)?{ok:!0,args:{kind:n_e(a),conversationId:g,explicitConversation:m&&g!==null,engine:y,files:r,key:s??null,notify:l,needsUser:c,...u?{final:u}:{},stay:d,json:p,text:n}}:{ok:!1,error:"--engine must be hermes, hermes:<profile>, openclaw, claude-code or grok-bot"}}function l_e(e,t,r){return e.length===1&&e[0]==="-"?t():e.length===1&&e[0].startsWith("@")&&e[0].length>1?r(e[0].slice(1)):e.join(" ")}function ic(){let t=S().agentOsId?.trim(),r=Pt();if(!t||!r)return"This computer isn't connected to Kynver yet. Run `kynver setup` first.";let n=new Il({apiBaseUrl:r,agentOsId:t,boxLabel:()=>dn(process.env),loadApiKey:ce,loadBoxCredential:()=>Oo(t),saveBoxCredential:o=>hf(t,o),clearBoxCredential:yf,log:()=>{}});return{apiBaseUrl:r,agentOsId:t,authorization:async()=>{let o=await n.authorization();return o?.kind==="box_token"?o.bearer:Oo(t)??null}}}function c_e(e,t){if(t){console.log(JSON.stringify(e));return}e.ok?console.log(`${e.duplicate?"Already posted":"Posted"} to conversation ${e.conversationId} (key ${e.idempotencyKey}).`):console.error(`kynver tab post: ${e.message} (${e.code})${e.status?` \u2014 retry with --key ${e.idempotencyKey}`:""}`)}async function A2(e,t){let r=a_e(e);if(!r.ok)return console.error(`kynver tab post: ${r.error}`),process.exitCode=2,null;let{args:n}=r,o;try{o=l_e(n.text,()=>E2(0,"utf8"),a=>E2(a,"utf8"))}catch(a){return console.error(`kynver tab post: can't read the text (${a instanceof Error?a.message:String(a)})`),process.exitCode=2,null}let s=t??ic();if(typeof s=="string")return console.error(`kynver tab post: ${s}`),process.exitCode=1,null;let i=await sc({...n.conversationId?{conversationId:n.conversationId}:{},...s_e(n,o),engine:n.engine,text:o,files:n.files,...n.key?{idempotencyKey:n.key}:{},notify:n.notify,...n.final?{final:!0}:{}},s);return c_e(i,n.json),i.ok||(process.exitCode=1),i}import{existsSync as opt,mkdirSync as u_e,readFileSync as d_e,renameSync as p_e,writeFileSync as m_e}from"node:fs";import{homedir as f_e}from"node:os";import P2 from"node:path";var g_e=720*60*60*1e3;function YE(e=f_e()){return P2.join(e,".kynver","hermes-cron-forward.json")}var I2=(e,t)=>`${e}/${t}`;function Yk(e,t,r=0){try{let n=JSON.parse(d_e(e,"utf8"));if(n?.version===1&&typeof n.startedAt=="string"&&n.runs&&typeof n.runs=="object")return n}catch{}return{version:1,startedAt:new Date(t-r).toISOString(),runs:{}}}function qE(e,t,r){let n=Object.fromEntries(Object.entries(t.runs).filter(([,s])=>r-Date.parse(s.at)<=g_e||!s.final));u_e(P2.dirname(e),{recursive:!0,mode:448});let o=`${e}.tmp`;m_e(o,JSON.stringify({...t,runs:n},null,2),{mode:384}),p_e(o,e)}import{existsSync as h_e,readFileSync as y_e}from"node:fs";import{homedir as k_e}from"node:os";import v_e from"node:path";var b_e="updates",w_e="*",R_e=/^[a-z0-9][a-z0-9._-]{0,63}$/,T2=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,S_e={skip:!1,destination:{kind:"updates"},notify:!0};function zE(e=k_e()){return v_e.join(e,".kynver","hermes-cron-routes.json")}var __e=e=>e.replace(/[._-]+/g," ").replace(/^\w/,t=>t.toUpperCase()).slice(0,80);function C_e(e){if(e==="skip")return{skip:!0};if(!e||typeof e!="object"||Array.isArray(e))return{invalid:'a route is {"topic"}, {"conversationId"} or "skip"'};let t=e,r=t.notify===void 0?!0:t.notify;if(typeof r!="boolean")return{invalid:"notify must be true or false"};if(t.main===!0||typeof t.conversationId=="string"&&t.conversationId.trim().toLowerCase()==="main"){let n=t.fallbackConversationId;return n===void 0?{skip:!1,destination:{kind:"main"},notify:r}:typeof n!="string"||!T2.test(n.trim())?{invalid:"fallbackConversationId must be a uuid"}:{skip:!1,destination:{kind:"main",fallbackConversationId:n.trim()},notify:r}}if(typeof t.conversationId=="string")return T2.test(t.conversationId.trim())?{skip:!1,destination:{kind:"conversation",conversationId:t.conversationId.trim()},notify:r}:{invalid:"conversationId must be a uuid"};if(typeof t.topic=="string"){let n=t.topic.trim();if(!R_e.test(n))return{invalid:"topic must be 1\u201364 lowercase letters, digits, . _ -"};if(n===b_e)return{skip:!1,destination:{kind:"updates"},notify:r};let o=typeof t.title=="string"&&t.title.trim()?t.title.trim().slice(0,80):__e(n);return{skip:!1,destination:{kind:"topic",key:n,title:o},notify:r}}return{invalid:'a route needs "topic" or "conversationId"'}}function XE(e=zE()){let t={present:!1,fallback:S_e,jobs:new Map,fileError:null};if(!h_e(e))return t;let r;try{r=JSON.parse(y_e(e,"utf8"))}catch{return{...t,present:!0,fileError:"hermes-cron-routes.json is not valid JSON"}}if(!r||typeof r!="object"||Array.isArray(r))return{...t,present:!0,fileError:"hermes-cron-routes.json must be an object of jobId \u2192 route"};let n={...t,present:!0,jobs:new Map};for(let[o,s]of Object.entries(r)){let i=C_e(s);o===w_e?"invalid"in i?n.fileError=`"*": ${i.invalid}`:n.fallback=i:n.jobs.set(o,i)}return n}function O2(e,t){return e.fileError?{invalid:e.fileError}:e.jobs.get(t)??e.fallback}import{createHash as X2}from"node:crypto";import{existsSync as W2,readFileSync as Q2,readdirSync as H2,statSync as j2}from"node:fs";import{homedir as Z2}from"node:os";import ac from"node:path";$t();async function N2(e,t){try{let r=await t.authorization();if(!r)return{ok:!1,status:401,code:"no_chat_credential"};let n=await ke(`${t.apiBaseUrl.replace(/\/$/,"")}/api/agent-os/by-id/${encodeURIComponent(t.agentOsId)}/agent-tabs/box/telegram-receipts`,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(e)},t.fetchImpl??fetch);if(n.status===200||n.status===201)return{ok:!0};let o=await n.json().catch(()=>({}));return{ok:!1,status:n.status,code:typeof o.code=="string"?o.code:"receipt_failed"}}catch{return{ok:!1,status:0,code:"network_error"}}}var x_e={rate_limit:"the AI account was rate-limited; it'll retry on the next run",provider:"the AI provider couldn't be set up",timeout:"it timed out",other:"it hit an error (details in the log)"},E_e=60*6e4,A_e=3;function D2(e){let t=e.toLowerCase();return/rate[ _-]?limit|\b429\b|too many requests|quota|credential|unauthori[sz]ed|\b401\b|overloaded/.test(t)?"rate_limit":/timed? ?out|timeout|deadline exceeded/.test(t)?"timeout":/resolv\w*\s+(?:the\s+)?provider|provider\s+resol|no provider|unknown provider|provider.*not (?:found|configured)/.test(t)?"provider":"other"}function P_e(e,t){return(e??t).replace(/\s*\(FAILED\)\s*$/i,"").trim()||t}function M2(e,t,r,n,o){return`**${P_e(e,t)}** didn't run this time: ${x_e[r]}.
|
|
641
641
|
|
|
642
642
|
Log: \`${o}\` (run ${n})`}function L2(e,t,r){let o=e&&e.reason===t&&r-Date.parse(e.lastAt)<=E_e?e.count+1:1;return{streak:{reason:t,count:o,lastAt:new Date(r).toISOString()},post:o===1||o===A_e+1}}function B2(e){return/^#{1,3}\s*Prompt\s*$/m.test(e)||/^---\nname:/m.test(e)||/^\s*---\s*\nname:/.test(e)}var U2=3e4,I_e=/^#{1,3}\s*Response\s*$/im,T_e=/^#{1,3}\s*Error\s*$/im,O_e=/^#{1,3}\s*Prompt\s*$/im,N_e=/^#{1,3}\s+\S/m,D_e=/^#\s*(?:Cron Job:\s*)?(.+?)\s*$/m,M_e=/^\*\*Status:\*\*\s*(?:silent|no_change)\b/im,L_e=/^\*\*(?:Job ID|Mode|Run Time):\*\*/m,B_e=/^\*\*(?:Job ID|Run Time|Mode|Schedule):\*\*/;function $2(e){let t=e.replace(/\r\n/g,`
|
|
643
643
|
`),r=D_e.exec(t)?.[1]?.slice(0,120)??null,n=I_e.exec(t),o=T_e.exec(t);if(!n&&(o||O_e.test(t))){let l=o?t.slice(o.index+o[0].length):"",c=N_e.exec(l.replace(/^\n/,"")),u=(c?l.slice(0,c.index+1):l).trim().slice(0,4e3);return{title:r,text:"",mediaPaths:[],silent:!1,failed:!0,errorText:u}}if(!n&&M_e.test(t))return{title:r,text:"",mediaPaths:[],silent:!0,failed:!1,errorText:""};let s=(n?t.slice(n.index+n[0].length):t).trim();if(!n&&L_e.test(t)){let l=/^---\s*$/m.exec(t);s=l?t.slice(l.index+l[0].length).trim():t.split(`
|