agentix-cli 0.69.4 → 0.70.0
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/{agent-IDAWXA3K.js → agent-V223TG6H.js} +2 -2
- package/dist/{board-dashboard-MAP6A2N7.js → board-dashboard-HR3PQPFW.js} +2 -2
- package/dist/{board-dashboard-MAP6A2N7.js.map → board-dashboard-HR3PQPFW.js.map} +1 -1
- package/dist/{chunk-CKBAVCGU.js → chunk-3IY2YWXP.js} +2 -2
- package/dist/{chunk-J7HA7ZTU.js → chunk-3RC4LO2G.js} +2 -2
- package/dist/{chunk-M6GPRMCQ.js → chunk-6QDOUOKD.js} +2 -2
- package/dist/{chunk-64P4QHSZ.js → chunk-CECHWYJ2.js} +1 -1
- package/dist/{chunk-64P4QHSZ.js.map → chunk-CECHWYJ2.js.map} +1 -1
- package/dist/{chunk-K63IOY6A.js → chunk-FBDIJEKL.js} +4 -4
- package/dist/chunk-FBDIJEKL.js.map +1 -0
- package/dist/{chunk-OHRTBD7U.js → chunk-LHLNARRW.js} +9 -9
- package/dist/chunk-ML6CNRBK.js +105 -0
- package/dist/chunk-ML6CNRBK.js.map +1 -0
- package/dist/{chunk-5ONI54E6.js → chunk-PHDS2HIN.js} +118 -118
- package/dist/chunk-PHDS2HIN.js.map +1 -0
- package/dist/{chunk-2UYV24UD.js → chunk-SN5N2FPG.js} +2 -2
- package/dist/chunk-TLDQWTSW.js +49 -0
- package/dist/chunk-TLDQWTSW.js.map +1 -0
- package/dist/chunk-TTVVXBCM.js +2 -0
- package/dist/chunk-TTVVXBCM.js.map +1 -0
- package/dist/{chunk-IU6L4V3A.js → chunk-W7SEPJFH.js} +2 -2
- package/dist/chunk-WLMQ5JMX.js +6 -0
- package/dist/chunk-WLMQ5JMX.js.map +1 -0
- package/dist/{chunk-DQQ3BCJW.js → chunk-YK7GFEGO.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/graph-FJ53FDWK.js +2 -0
- package/dist/index.d.ts +20 -4
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/migrate-v2-ZOIMGITH.js +4 -0
- package/dist/{migrate-v2-KOMPDC6U.js.map → migrate-v2-ZOIMGITH.js.map} +1 -1
- package/dist/program-UTELWTXC.js +2 -0
- package/dist/promote-B5AOKPQR.js +2 -0
- package/dist/query-QLJNQUUP.js +2 -0
- package/dist/registry-CTZFLXGB.js +2 -0
- package/dist/types-NZOBHQGS.js +2 -0
- package/dist/wiki-X76JUHXT.js +2 -0
- package/dist/wiki-X76JUHXT.js.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-4DRNEOOW.js +0 -2
- package/dist/chunk-4DRNEOOW.js.map +0 -1
- package/dist/chunk-535MLOSB.js +0 -109
- package/dist/chunk-535MLOSB.js.map +0 -1
- package/dist/chunk-5ONI54E6.js.map +0 -1
- package/dist/chunk-K63IOY6A.js.map +0 -1
- package/dist/chunk-V2TLFYKH.js +0 -45
- package/dist/chunk-V2TLFYKH.js.map +0 -1
- package/dist/migrate-v2-KOMPDC6U.js +0 -4
- package/dist/program-T275Y2V6.js +0 -2
- package/dist/promote-VZAUTV6E.js +0 -2
- package/dist/query-7QQZPMXM.js +0 -2
- package/dist/registry-WQ65MQEY.js +0 -2
- package/dist/types-S6NHM5C3.js +0 -2
- package/dist/wiki-J4MMCONT.js +0 -2
- /package/dist/{agent-IDAWXA3K.js.map → agent-V223TG6H.js.map} +0 -0
- /package/dist/{chunk-CKBAVCGU.js.map → chunk-3IY2YWXP.js.map} +0 -0
- /package/dist/{chunk-J7HA7ZTU.js.map → chunk-3RC4LO2G.js.map} +0 -0
- /package/dist/{chunk-M6GPRMCQ.js.map → chunk-6QDOUOKD.js.map} +0 -0
- /package/dist/{chunk-OHRTBD7U.js.map → chunk-LHLNARRW.js.map} +0 -0
- /package/dist/{chunk-2UYV24UD.js.map → chunk-SN5N2FPG.js.map} +0 -0
- /package/dist/{chunk-IU6L4V3A.js.map → chunk-W7SEPJFH.js.map} +0 -0
- /package/dist/{chunk-DQQ3BCJW.js.map → chunk-YK7GFEGO.js.map} +0 -0
- /package/dist/{program-T275Y2V6.js.map → graph-FJ53FDWK.js.map} +0 -0
- /package/dist/{promote-VZAUTV6E.js.map → program-UTELWTXC.js.map} +0 -0
- /package/dist/{query-7QQZPMXM.js.map → promote-B5AOKPQR.js.map} +0 -0
- /package/dist/{registry-WQ65MQEY.js.map → query-QLJNQUUP.js.map} +0 -0
- /package/dist/{types-S6NHM5C3.js.map → registry-CTZFLXGB.js.map} +0 -0
- /package/dist/{wiki-J4MMCONT.js.map → types-NZOBHQGS.js.map} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{t as nt,u as rt}from"./chunk-
|
|
1
|
+
import{t as nt,u as rt}from"./chunk-YK7GFEGO.js";import{d as et,e as tt}from"./chunk-AQASR6KR.js";import{b as ie,t as Xe,v as H,w as oe,y as ae}from"./chunk-W7SEPJFH.js";import{g as qe,h as Je,i as Ye,k as Ze,l as Qe}from"./chunk-FSYA4GNU.js";import{q as Ge}from"./chunk-OPUPVGYP.js";import{w as Ke,z as An}from"./chunk-DTX4I5LQ.js";import{existsSync as _n,readdirSync as Rn,readFileSync as Cn,statSync as Tn}from"fs";import{resolve as En}from"path";function st(t,e,n=Date.now(),s=7){let r=s*864e5,i=new Map;for(let o of e){let a=i.get(o.workflowId);a?a.push(o):i.set(o.workflowId,[o])}return t.map(o=>{let a=i.get(o.id)??[],c=a.filter(m=>n-m.at<=r),l=a.filter(m=>n-m.at>r&&n-m.at<=r*2),u=c.filter(m=>m.status==="failed").length,d=a.filter(m=>m.status==="paused").length,g=a.length?Math.max(...a.map(m=>m.at)):null,f=a.length?l.length>0&&c.length===0?"dormant":c.length>0&&u*2>=c.length?"failing":c.length>0?"active":"quiet":"never";return{id:o.id,name:o.name||o.id,state:f,lastRunAt:g,recent:c.length,prior:l.length,failed:u,paused:d}}).sort((o,a)=>{let c={dormant:0,failing:1,active:2,quiet:3,never:4};return c[o.state]-c[a.state]||(a.lastRunAt??0)-(o.lastRunAt??0)})}var z=new Map;function wi(t,e=1e3){if(!_n(t))return[];let n=Rn(t).filter(i=>i.endsWith(".jsonl")).map(i=>{let o=En(t,i);return{path:o,mtime:Tn(o).mtimeMs}}).sort((i,o)=>o.mtime-i.mtime).slice(0,e),s=new Set(n.map(i=>i.path));for(let i of z.keys())s.has(i)||z.delete(i);let r=[];for(let{path:i,mtime:o}of n){let a=z.get(i);if(a&&a.mtime===o){a.summary&&r.push(a.summary);continue}let c=Dn(i,o);z.set(i,{mtime:o,summary:c}),c&&r.push(c)}return r}function Dn(t,e){try{let n=Cn(t,"utf-8").split(`
|
|
2
2
|
`).filter(Boolean);if(!n.length)return null;let s=JSON.parse(n[0]),r=s.run?.workflowId;if(!r)return null;let i=s.run?.status??"unknown";for(let o=n.length-1;o>=0;o--){let a=JSON.parse(n[o]),c=a.status??a.run?.status;if(c){i=c;break}}return{workflowId:r,status:i,at:e}}catch{return null}}var Ln={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},w={routines:200,summary:160,filters:6,filterValue:60,text:120},Pn=(t,e,n)=>{try{return Ge(t,e,n)}catch{return null}},it=864e5;function vi(t){let e=t.now??Date.now(),n={...Ln,...t.thresholds},s=t.nextFire??Pn,r=[];for(let a of t.crons){let c=t.cronRuns.get(a.id)??[],l=a.timezone||"UTC",u=c.map(f=>({at:Date.parse(f.startedAt),status:f.status})),d=c[0],g={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:$(a.id,w.text),trigger:{schedule:$(a.schedule,w.text),timezone:l},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?le(a.nextRun)??le(s(a.schedule,new Date(e),l)):null,lastRun:d?{at:d.startedAt,status:d.status,summary:Un(d.status==="success"?void 0:d.errorSummary,w.summary)}:null,lastSuccessAt:c.find(f=>f.status==="success")?.startedAt??null,consecutiveFailures:ot(u),sampledRuns:c.length,flags:[],attention:null};g.flags=at(g,u,a.schedule,l,null,e,n,s),r.push(lt(g))}let i=new Map(st(t.workflows.map(a=>({id:a.id,name:a.title})),t.workflowRuns,e).map(a=>[a.id,a])),o=new Map;for(let a of t.workflowRuns){let c=o.get(a.workflowId);c?c.push(a):o.set(a.workflowId,[a])}for(let a of t.workflows){let c=a.nodes.find(A=>A.type.startsWith("trigger."));if(!c||c.type!=="trigger.cron"&&c.type!=="trigger.hook")continue;let l=c.config??{},u=a.state||"active",d=u==="active",g=(o.get(a.id)??[]).slice().sort((A,se)=>se.at-A.at),f=g.map(A=>({at:A.at,status:Nn(A.status)})),m=f[0],h=c.type==="trigger.cron",y=typeof l.spec=="string"?l.spec:"",R=typeof l.timezone=="string"?l.timezone:"UTC",E={id:`workflow:${a.id}`,source:"workflow",kind:h?"schedule":"event",name:$(a.title||a.id,w.text),trigger:h?{schedule:$(y,w.text),timezone:R}:{event:$(typeof l.event=="string"?l.event:"",w.text),filters:Vn(l.filter,a)},agent:Mn(a),enabled:d,state:u,nextRunAt:h&&d&&y?le(s(y,new Date(e),R)):null,lastRun:m?{at:new Date(m.at).toISOString(),status:m.status}:null,lastSuccessAt:(()=>{let A=f.find(se=>se.status==="success");return A?new Date(A.at).toISOString():null})(),consecutiveFailures:ot(f),sampledRuns:g.length,flags:[],attention:null},W=Date.parse(a.updated||a.created||"");E.flags=h?at(E,f,y,R,Number.isFinite(W)?W:null,e,n,s):On(E,i.get(a.id)?.state==="dormant",Number.isFinite(W)?W:null,e,n),r.push(lt(E))}return r.sort(jn).slice(0,w.routines)}function ot(t){let e=0;for(let n of t)if(!(n.status==="running"||n.status==="paused"||n.status==="unknown"))if(n.status==="failed"||n.status==="timeout")e++;else break;return e}function at(t,e,n,s,r,i,o,a){let c=[],l=e.length?e[0].at:null;if(!t.enabled){let g=ut(l,r,i,o);return g&&c.push(g),c}if(t.consecutiveFailures>=o.failStreak&&c.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),l===null)return c.push({reason:"never-ran",detail:"No persisted attempt"}),c;let u=new Date(l),d=null;for(let g=0;g<o.missedFires&&(d=a(n,u,s),!!d);g++)u=d;return d&&i>d.getTime()+o.graceMs&&c.push({reason:"overdue",detail:`No attempt since ${new Date(l).toISOString()}; ${o.missedFires} scheduled fires missed`}),c}function On(t,e,n,s,r){let i=[],o=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=ut(o,n,s,r);return a&&i.push(a),i}return t.consecutiveFailures>=r.failStreak&&i.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),o===null?i.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&i.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),i}function ut(t,e,n,s){let r=Math.max(t??0,e??0);return r&&n-r<s.disabledDays*it?null:{reason:"disabled-long",detail:r?`Disabled; no activity for ${Math.floor((n-r)/it)} days`:"Disabled and never ran"}}function lt(t){let e=new Set(t.flags.map(n=>n.reason));return t.attention=e.has("failing")?"critical":e.has("overdue")||e.has("dormant")||e.has("never-ran")?"warning":e.has("disabled-long")?"info":null,t}var ct={critical:0,warning:1,info:2};function jn(t,e){let n=t.attention?ct[t.attention]:3,s=e.attention?ct[e.attention]:3;return n-s||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function Nn(t){switch(t){case"completed":case"ok":return"success";case"failed":return"failed";case"timeout":return"timeout";case"canceled":return"canceled";case"running":return"running";case"paused":return"paused";default:return"unknown"}}function Mn(t){if(t.ownerAgent)return $(t.ownerAgent,w.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?$(String(e.config.agentId),w.text):null}function Vn(t,e){let n=[],s=e?.project;if(s&&n.push($(`project=${s}`,w.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[r,i]of Object.entries(t)){let o=Array.isArray(i)?i.map(String):i==null?[]:[String(i)];o.length&&n.push($(`${r}=${o.join(",")}`,w.filterValue))}return n.slice(0,w.filters)}function le(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function $(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function Un(t,e){return t===void 0?void 0:$(t,e)}import{createHash as Fn,randomBytes as dt}from"crypto";import{existsSync as Bn,mkdirSync as Wn,readFileSync as Hn,writeFileSync as zn}from"fs";import{resolve as Kn,dirname as Gn}from"path";var ce="agx_live_",Xn=".agentx/tokens.json",gt=class{file;constructor(e=process.cwd(),n=Xn){this.file=Kn(e,n)}load(){if(!Bn(this.file))return[];try{return JSON.parse(Hn(this.file,"utf-8"))}catch{return[]}}save(e){Wn(Gn(this.file),{recursive:!0}),zn(this.file,JSON.stringify(e,null,2)+`
|
|
3
3
|
`,"utf-8")}create(e){if(!e.name?.trim())throw new Error("Token name is required.");if(!Array.isArray(e.scopes)||e.scopes.length===0)throw new Error("At least one scope is required.");for(let o of e.scopes)if(!qn(o))throw new Error(`Invalid scope: ${o}`);let n=dt(32).toString("hex"),s=ce+n,r={id:"tok_"+dt(4).toString("hex"),name:e.name.trim(),prefix:ce+n.slice(0,4),hash:ft(s),scopes:[...e.scopes],createdAt:new Date().toISOString(),expiresAt:e.expiresInDays?new Date(Date.now()+e.expiresInDays*86400*1e3).toISOString():void 0},i=this.load();return i.push(r),this.save(i),{token:s,record:r}}list(){return this.load()}revoke(e){let n=this.load(),s=n.find(r=>r.id===e);return s?(s.revokedAt=new Date().toISOString(),this.save(n),s):null}isActive(e){let n=this.load().find(s=>s.id===e);return!!n&&!n.revokedAt&&!(n.expiresAt&&Date.parse(n.expiresAt)<Date.now())}verify(e){if(!e||!e.startsWith(ce))return null;let n=ft(e),s=this.load(),r=s.find(a=>a.hash===n);if(!r||r.revokedAt||r.expiresAt&&Date.parse(r.expiresAt)<Date.now())return null;let i=Date.now(),o=r.lastUsedAt?Date.parse(r.lastUsedAt):0;if(i-o>6e4){r.lastUsedAt=new Date(i).toISOString();try{this.save(s)}catch{}}return r}};function Ci(t,e){return!!(t.scopes.includes(e)||e.startsWith("agent:")&&t.scopes.includes("agent:*")||e==="dashboard:read"&&t.scopes.includes("dashboard:write"))}function qn(t){return t==="dashboard:read"||t==="dashboard:write"||t==="agent:*"||/^agent:[a-z0-9][a-z0-9_-]*$/.test(t)||t==="mesh:peer"||t==="app"}function ft(t){return"sha256:"+Fn("sha256").update(t).digest("hex")}function Ti(t){let e=t.headers.authorization,n=Array.isArray(e)?e[0]:e;if(n&&n.toLowerCase().startsWith("bearer "))return n.slice(7).trim();if(t.url)try{let r=new URL(t.url,"http://localhost").searchParams.get("token");if(r)return r}catch{}return null}import{existsSync as ue,readdirSync as gr,readFileSync as fr}from"fs";import{resolve as L}from"path";import{existsSync as Jn,mkdirSync as Yn,readdirSync as Zn,readFileSync as Qn,renameSync as er,writeFileSync as tr}from"fs";import{resolve as pt}from"path";var mt=["discard","keep","pause","approve"],v={title:120,ask:300,recommend:300,source:500,note:500,pendingPerAgent:25},nr={defaultExpiryDays:3,maxExpiryDays:30};function D(t){return pt(t,".agentx","approvals")}var rr=/^[a-z0-9][a-z0-9-]{0,80}$/;function ht(t){return rr.test(t)}function yt(t,e){if(!ht(e))throw new Error(`invalid card id: ${e}`);return pt(D(t),`${e}.json`)}function sr(t,e){let n=new Date(t).toISOString().slice(0,10),s=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40);return`${n}-${s||"card"}-${Math.random().toString(36).slice(2,6)}`}function K(t,e){Yn(D(t),{recursive:!0});let n=yt(t,e.id),s=`${n}.${process.pid}.tmp`;tr(s,JSON.stringify(e,null,2)+`
|
|
4
4
|
`),er(s,n)}function M(t,e){if(!ht(e))return null;try{return JSON.parse(Qn(yt(t,e),"utf-8"))}catch{return null}}function V(t,e){let n=D(t);if(!Jn(n))return[];let s=[];for(let r of Zn(n).filter(i=>i.endsWith(".json")&&!i.startsWith("_")).sort()){let i=M(t,r.slice(0,-5));i&&(!e||i.status===e)&&s.push(i)}return s}function k(t){return typeof t=="string"?t.replace(/\s+/g," ").trim():""}function ir(t,e,n){let s=e+n.maxExpiryDays*864e5,r,i=k(t);if(!i)r=e+n.defaultExpiryDays*864e5;else{let o=/^(\d+)\s*([hd])$/i.exec(i);if(o)r=e+Number(o[1])*(o[2].toLowerCase()==="d"?864e5:36e5);else if(r=Date.parse(i),Number.isNaN(r))return{ok:!1,error:`expires must be an ISO date or time, or like "12h" / "3d" (got "${i}")`}}return r<=e?{ok:!1,error:"expires must be in the future"}:{ok:!0,at:new Date(Math.min(r,s)).toISOString()}}function or(t,e={}){let n=e.now??Date.now(),s=e.settings??nr,r=k(t.title),i=k(t.ask),o=k(t.recommend),a=k(t.raised_by);if(!r)return{ok:!1,error:"title is required"};if(!i)return{ok:!1,error:"ask is required: the yes/no question"};if(!o)return{ok:!1,error:"recommend is required: your advice and why, in one line"};if(!a)return{ok:!1,error:"raised_by is required: the agent id"};if(r.length>v.title)return{ok:!1,error:`title is longer than ${v.title} characters`};if(i.length>v.ask)return{ok:!1,error:`ask is longer than ${v.ask} characters`};if(o.length>v.recommend)return{ok:!1,error:`recommend is longer than ${v.recommend} characters`};let c=k(t.if_silent).toLowerCase();if(!mt.includes(c))return{ok:!1,error:`if_silent must be one of ${mt.join(", ")}`};let l=ir(t.expires,n,s);if(!l.ok)return l;let u=k(t.source);if(u.length>v.source)return{ok:!1,error:`source is longer than ${v.source} characters`};if(u&&/^[a-z][a-z0-9+.-]*:/i.test(u)&&!/^https?:\/\//i.test(u))return{ok:!1,error:"source must be an http(s) link or a plain reference"};let d,g=t.reply;return g&&typeof g=="object"&&k(g.channel)&&k(g.chatId)&&(d={channel:k(g.channel),chatId:k(g.chatId),...k(g.accountId)?{accountId:k(g.accountId)}:{}}),{ok:!0,card:{id:sr(n,r),title:r,ask:i,recommend:o,if_silent:c,expires:l.at,...u?{source:u}:{},raised_by:a,created_at:new Date(n).toISOString(),...d?{reply:d}:{},status:"pending"}}}function Pi(t,e,n={}){let s=or(e,n);if(!s.ok)return s;let r=V(t,"pending").filter(i=>i.raised_by===s.card.raised_by).length;return r>=v.pendingPerAgent?{ok:!1,error:`${s.card.raised_by} already has ${r} cards waiting; wait for decisions before raising more`}:(K(t,s.card),s)}function bt(t,e,n,s={}){let r=M(t,e);if(!r)return{ok:!1,error:`no card "${e}"`};if(r.status!=="pending")return{ok:!1,error:`card "${e}" is already ${r.status}`};let i=k(s.note).slice(0,v.note),o={...r,status:"decided",verdict:n,decided_by:s.by??"operator",decided_at:new Date(s.now??Date.now()).toISOString(),...i?{note:i}:{}};return K(t,o),{ok:!0,card:o}}function Oi(t,e=Date.now()){let n=[];for(let s of V(t,"pending")){if(Date.parse(s.expires)>e)continue;let r={...s,status:"expired",outcome:s.if_silent,decided_by:"expiry",decided_at:new Date(e).toISOString()};K(t,r),n.push(r)}return n}function ji(t){return V(t).filter(e=>e.status!=="pending"&&!e.agent_notified_at)}function Ni(t,e,n=Date.now()){let s=M(t,e);!s||s.agent_notified_at||K(t,{...s,agent_notified_at:new Date(n).toISOString()})}function Mi(t){let e=t.status==="decided"?t.verdict==="yes"?"The operator said YES.":"The operator said NO.":`Nobody answered before it expired, so the default applied: ${t.outcome??t.if_silent}.`,n=[`[Approval result] Your decision card "${t.title}" (${t.id}) is closed.`,`Question: ${t.ask}`,e];return t.note&&n.push(`Operator note: ${t.note}`),t.source&&n.push(`Source: ${t.source}`),t.reply&&n.push(`You raised it from ${t.reply.channel} chat ${t.reply.chatId}; reply there if the requester should know.`),n.push("Act on this result now. Do not raise the same card again."),n.join(`
|
|
@@ -128,4 +128,4 @@ Document the arguments, commands, or files the skill expects. Example:
|
|
|
128
128
|
claude-code ${ze(t)} --arg value
|
|
129
129
|
\`\`\`
|
|
130
130
|
`}An();var xn={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function $n(t){return{...xn,...t??{},regions:{...t?.regions??{}},buffer:{...xn.buffer,...t?.buffer??{}}}}function za(t){try{return $n(Ke(t).screen)}catch{return $n(void 0)}}var yi=/^[a-z][\w-]*$/,vn=["window","screen","menubar","notifications"];function B(t,e,n,s){let r=Number(t);if(t===""||t===null||!Number.isFinite(r)||!n(r))throw new Error(`${e} must be ${s}`);return r}var re=(t,e)=>B(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function In(t){let e=typeof t=="string"?t.split(",").map(Number):[t?.x,t?.y,t?.width,t?.height].map(Number);if(e.length!==4||!e.every(Number.isFinite)||e[2]<=0||e[3]<=0)throw new Error("a region is x,y,width,height in screen points, with width and height above 0");return{x:e[0],y:e[1],width:e[2],height:e[3]}}function Ka(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=re(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=re(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=re(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=B(e.stableMs,"stableMs",r=>Number.isInteger(r)&&r>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=B(e.changeThreshold,"changeThreshold",r=>r>=0&&r<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let r={...n.regions??{}};for(let[i,o]of Object.entries(e.regions)){if(!yi.test(i))throw new Error(`region name "${i}" must be lowercase letters, digits, - or _`);o===null?delete r[i]:r[i]=In(o)}n.regions=r}if(e.buffer&&typeof e.buffer=="object"){let r=e.buffer,i={...n.buffer??{}};"enabled"in r&&(i.enabled=!!r.enabled),"seconds"in r&&(i.seconds=B(r.seconds,"buffer.seconds",o=>o>0&&o<=120,"above 0 and at most 120")),"fps"in r&&(i.fps=B(r.fps,"buffer.fps",o=>o>0&&o<=10,"above 0 and at most 10")),"maxPixels"in r&&(i.maxPixels=re(r.maxPixels,"buffer.maxPixels")),"region"in r&&(i.region=String(r.region).trim()),n.buffer=i}let s=n.buffer?.region;if(s!==void 0&&!vn.includes(s)&&!n.regions?.[s])try{In(s)}catch{throw new Error(`buffer.region "${s}" is not a region \u2014 use ${[...vn,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{st as a,wi as b,xe as c,Mr as d,Vr as e,Io as f,Ao as g,_o as h,Lt as i,Co as j,w as k,vi as l,gt as m,Ci as n,ft as o,Ti as p,mt as q,ht as r,M as s,Pi as t,Oi as u,ji as v,Ni as w,Mi as x,G as y,Wi as z,Qi as A,eo as B,Oo as C,Qr as D,jo as E,no as F,ro as G,so as H,io as I,oo as J,ao as K,co as L,uo as M,Re as N,zo as O,Z as P,Te as Q,_s as R,ta as S,na as T,ra as U,Zt as V,sa as W,C as X,nn as Y,rn as Z,ua as _,js as $,cn as aa,Us as ba,je as ca,fn as da,Hs as ea,zs as fa,pa as ga,Ks as ha,Ne as ia,Gs as ja,Xs as ka,dn as la,hn as ma,ha as na,Ys as oa,ya as pa,Ra as qa,Ca as ra,di as sa,Ta as ta,bn as ua,q as va,ho as wa,Tt as xa,fe as ya,we as za,$o as Aa,Pa as Ba,Oa as Ca,ja as Da,Na as Ea,Ma as Fa,Va as Ga,Ua as Ha,Fa as Ia,Ba as Ja,xn as Ka,$n as La,za as Ma,vn as Na,Ka as Oa};
|
|
131
|
-
//# sourceMappingURL=chunk-
|
|
131
|
+
//# sourceMappingURL=chunk-3IY2YWXP.js.map
|
|
@@ -48,7 +48,7 @@ The "modified" field is optional and can contain updated values to pass forward.
|
|
|
48
48
|
... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
|
|
49
49
|
${c}`,is_error:!0}:{tool_use_id:e.id,content:c||"(no output)"}}async editFile(e){let t=String(e.input.path||""),o=e.input.edits,n=ge.resolve(this.cwd,t);if(!o||o.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await W.checkFileWrite(t);if(s==="deny")return{tool_use_id:e.id,content:`File write blocked by permissions: ${t}`,is_error:!0};if(s==="skip")return{tool_use_id:e.id,content:`File write skipped (plan mode): ${t}`};if(f.has("pre:file-write")){let a=await f.execute("pre:file-write",{event:"pre:file-write",file:n,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`File edit blocked by pre:file-write hook: ${t}`,is_error:!0}}let i=await re.readFile(n,"utf8"),c=[];for(let a of o)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),c.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):c.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await re.writeFile(n,i,"utf8"),f.has("post:file-write")&&await f.execute("post:file-write",{event:"post:file-write",file:n,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
|
|
50
50
|
${c.join(`
|
|
51
|
-
`)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-
|
|
51
|
+
`)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-CTZFLXGB.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
|
|
52
52
|
|
|
53
53
|
${p.content}`}:{tool_use_id:e.id,content:`Sub-agent "${t}" failed: ${p.error}`,is_error:!0}}catch(s){return{tool_use_id:e.id,content:`Failed to spawn sub-agent: ${s.message}`,is_error:!0}}}async askUser(e){let t=String(e.input.question||""),o=e.input.options,n=t;return o?.length&&(n+=`
|
|
54
54
|
Options: ${o.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:n}}};async function Ae(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,cwd:s,maxIterations:i=20,enabledTools:c,interactive:a=!0,overwrite:p=!1,dryRun:l=!1,onProgress:d,abortSignal:u}=r,m=u?{...n,abortSignal:u}:n;if(!e.generateRaw)return dt(r);let I=new se(s,{interactive:a,overwrite:p,dryRun:l,acmeContext:r.acmeContext,abortSignal:u}),D=be(c);if(r.acmeContext)for(let g of at)D.push({name:g.name,description:g.description,input_schema:g.input_schema});let E=new Set;if(r.mcpTools?.length)for(let g of r.mcpTools)D.push({name:g.name,description:g.description,input_schema:g.input_schema}),E.add(g.name);let C=o.filter(g=>g.role!=="system").map(g=>({role:g.role,content:g.content})),B=[],G=0,F=0,A=0,O="",j,_=0;for(;_<i;){if(_++,u?.aborted)throw new Error("cancelled");d?.({type:"iteration_start",iteration:_}),b.step(_,`Agentic loop iteration (${D.length} tools available)`);let g,M=!!e.generateRawStream&&!!d;try{if(M){let T=null,U=null,v="";for await(let x of e.generateRawStream(C,t,D,m))x.type==="text_delta"?(v+=x.text,d?.({type:"text_delta",text:x.text})):x.type==="thinking_delta"?d?.({type:"thinking_delta",text:x.text}):x.type==="raw_result"?T=x.result:x.type==="error"&&(U=x.error);if(U&&!T)throw new Error(U);if(!T)throw new Error("generateRawStream returned no raw_result event");g=T,g._streamedText=v}else g=await e.generateRaw(C,t,D,m)}catch(T){if(T.message?.includes("not available"))return dt(r);throw T}G+=g.usage.input_tokens+g.usage.output_tokens,F+=g.usage.input_tokens,A+=g.usage.output_tokens;let P=g._streamedText;for(let T of g.content)T.type==="text"&&(O+=T.text,P===void 0&&d?.({type:"text_delta",text:T.text}));if(P!==void 0&&delete g._streamedText,g.stop_reason==="end_turn"||g.stop_reason==="max_tokens")break;if(g.stop_reason==="tool_use"){let T=g.content.filter(v=>v.type==="tool_use");if(T.length===0)break;C.push({role:"assistant",content:g.content});let U=[];for(let v of T){d?.({type:"tool_call",name:v.name,id:v.id,input:v.input}),b.step(_,`Tool call: ${v.name}`);let x;if(E.has(v.name)&&r.mcpDispatch){let h=await r.mcpDispatch(v.name,v.input);x={tool_use_id:v.id,content:h.content,is_error:h.isError}}else x=await I.execute({name:v.name,id:v.id,input:v.input});d?.({type:"tool_result",name:v.name,id:v.id,content:x.content.slice(0,200),is_error:x.is_error}),x.files?.length&&(B.push(...x.files),d?.({type:"files_created",files:x.files})),x.followUp&&(j=x.followUp),U.push({type:"tool_result",tool_use_id:x.tool_use_id,content:x.content,is_error:x.is_error})}if(C.push({role:"user",content:U}),j)break;continue}break}return d?.({type:"complete",iterations:_,totalTokens:G}),{files:B,content:O,followUp:j,tokensUsed:G,inputTokens:F||void 0,outputTokens:A||void 0,iterations:_}}async function dt(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,maxIterations:s=5}=r,c=[{role:"system",content:t+`
|
|
@@ -123,4 +123,4 @@ ${r.projectInstructions}`),r.memoryContext&&o.push(r.memoryContext),o.push(`# Ou
|
|
|
123
123
|
Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),o.join(`
|
|
124
124
|
|
|
125
125
|
`)}export{qe as a,Vt as b,Yt as c,We as d,ze as e,Ve as f,Ye as g,Pe as h,ee as i,Re as j,le as k,te as l,Tt as m,oe as n,Mt as o,f as p,et as q,tt as r,Me as s,de as t,W as u,ne as v,it as w,Ee as x,$e as y,se as z,mt as A,Zn as B,er as C};
|
|
126
|
-
//# sourceMappingURL=chunk-
|
|
126
|
+
//# sourceMappingURL=chunk-3RC4LO2G.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{c as ee,d as te,e as ne,f as F,g as C,h as j,i as B}from"./chunk-C4CDVE2E.js";import{a as Q,b as Z}from"./chunk-YL223TEU.js";import{a as V}from"./chunk-
|
|
1
|
+
import{c as ee,d as te,e as ne,f as F,g as C,h as j,i as B}from"./chunk-C4CDVE2E.js";import{a as Q,b as Z}from"./chunk-YL223TEU.js";import{a as V}from"./chunk-SN5N2FPG.js";import{t as O,v as G,w as _,z as M}from"./chunk-DTX4I5LQ.js";import{existsSync as W,readFileSync as ce,writeFileSync as pe,appendFileSync as Ae,mkdirSync as Se}from"fs";import{dirname as Ce,resolve as P}from"path";import{fileURLToPath as Ie}from"url";import{hostname as Ee}from"os";import{spawn as Te}from"child_process";M();import{existsSync as re,readFileSync as ae,writeFileSync as L,copyFileSync as ye}from"fs";import{resolve as ie}from"path";function oe(e,t={}){let n=t.configPath||ie(process.cwd(),"agentx.json");if(!re(n))throw new Error(`agentx.json not found at ${n}`);let a=JSON.parse(ae(n,"utf-8")),r=e(a),i=typeof r=="string"?{summary:r}:r,c=JSON.stringify(a,null,2)+`
|
|
2
2
|
`,l=n+".tmp";L(l,c,"utf-8");try{JSON.parse(ae(l,"utf-8"))}catch(d){throw new Error(`config did not round-trip cleanly: ${d.message}`)}let o;return t.skipBackup||(o=`${n}.bak.${Date.now()}`,ye(n,o)),L(n,c,"utf-8"),t.skipReload||ke().catch(()=>{}),{summary:i.summary,payload:i.payload,backupPath:o}}function se(e,t={}){let n=t.configPath||ie(process.cwd(),"agentx.json");if(re(n)&&!t.overwrite)throw new Error(`agentx.json already exists at ${n}. Pass overwrite=true to replace it.`);return L(n,JSON.stringify(e,null,2)+`
|
|
3
3
|
`,"utf-8"),{file:n}}async function ke(){try{let t=_().dashboard.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800";await fetch(`${t}/reload`,{method:"POST"}).catch(()=>null)}catch{}}function le(e,t){let n=e.configExists?e.agentCount===0?"Add your first agent":"Add another agent":"Set up your team",a=`<header class="ax-topbar">
|
|
4
4
|
<div class="ax-topbar__left">
|
|
@@ -737,4 +737,4 @@ tr:hover td { background: var(--bg-hover); }
|
|
|
737
737
|
<h3><a href="${l}/article/${encodeURIComponent(d.path)}">${s(d.meta.title)}</a></h3>
|
|
738
738
|
</div>`;return $(`${t} \xB7 ${n}`,I(r),o)}function U(e,t,n){let a=e.rebuildIndex(),r=J(a.articles.map(c=>({title:c.title,path:c.path,tags:c.tags}))),i='<div class="nav-section">';i+=`<div class="nav-section-title">${s(t)}</div>`,i+=`<a class="nav-item${n?"":" active"}" href="/">Home</a>`,i+='<a class="nav-item" href="/lint">Health check</a>',i+="</div>";for(let[c,l]of r){i+='<div class="nav-section">',i+=`<div class="nav-section-title">${q(c)}</div>`;for(let o of l){let d=o.path===n;i+=`<a class="nav-item${d?" active":""}" href="/article/${encodeURIComponent(o.path)}">${s(o.title)}</a>`}i+="</div>"}return i}function Ye(e){let{wikiDir:t,agentFilter:n,peerUrls:a=[],mode:r="graph",pathPrefix:i=""}=e,c=i.replace(/\/+$/,""),l=new V(t,void 0,r),o=a.length>0?new H(a):null;return async(d,g)=>{let x=new URL(d.url||"/","http://localhost"),p=decodeURIComponent(x.pathname),f=c&&p.startsWith(c)?p.slice(c.length)||"/":p,h=null,T=200;try{if(f.startsWith("/remote/")&&o){let y=f.slice(8).split("/article/");if(y.length===2){let[b,v]=y,m=b.indexOf("/"),k=decodeURIComponent(b.slice(0,m)),u=b.slice(m+1),w=await o.getRemoteArticle(k,u,v);if(w){let z=await o.getRemoteAgents(),N=[...l.summary(),...z.map(S=>({...S,agentId:`${S.agentId} @${S.nodeId}`}))],A=`<div class="breadcrumb"><a href="/">Hub</a> / <span class="tag">remote</span> ${s(u)} @ ${s(k)}</div>`;A+=`<h1>${s(w.meta.title)}</h1>`,A+='<dl class="meta">',A+=`<dt>Tags</dt><dd>${(w.meta.tags||[]).map(S=>`<span class="tag">${S}</span>`).join(" ")}</dd>`,A+=`<dt>Owner</dt><dd>${s(w.meta.owner)}</dd>`,A+=`<dt>Source</dt><dd><span class="tag">remote</span> ${s(k)}</dd>`,A+=`<dt>Updated</dt><dd>${w.meta.lastUpdated}</dd>`,A+="</dl>";let E=new Map;A+=D(w.content,E),h=$(w.meta.title,I(N),A)}}}if(!h&&n){let y=l.getAgentWiki(n);if(f==="/"||f===""){let b=y.rebuildIndex(),v=l.getAgentEntries(n),m=`<h1>${s(n)}</h1>`;if(m+='<div class="stats">',m+=`<div class="stat-card"><div class="number">${b.articles.length}</div><div class="label">Articles</div></div>`,m+=`<div class="stat-card"><div class="number">${v.length}</div><div class="label">Entries</div></div>`,m+="</div>",b.articles.length>0){m+="<h2>Articles</h2><table><tr><th>Title</th><th>Type</th><th>Updated</th></tr>";for(let k of b.articles)m+=`<tr><td><a href="/article/${encodeURIComponent(k.path)}">${s(k.title)}</a></td><td><span class="tag">${(k.tags||[]).slice(0,3).join(", ")}</span></td><td>${k.lastUpdated||""}</td></tr>`;m+="</table>"}h=$(n,U(y,n),m)}else if(f.startsWith("/article/")){let b=f.slice(9),v=y.readArticle(b);if(v){let m=y.rebuildIndex(),k=new Map;for(let w of m.articles)k.set(w.title,w.path);let u=`<h1>${s(v.meta.title)}</h1>`;u+='<dl class="meta">',u+=`<dt>Tags</dt><dd>${(v.meta.tags||[]).map(w=>`<span class="tag">${w}</span>`).join(" ")}</dd>`,u+=`<dt>Updated</dt><dd>${v.meta.lastUpdated}</dd>`,v.meta.sources?.length&&(u+=`<dt>Sources</dt><dd>${v.meta.sources.length} entries</dd>`),u+="</dl>",u+=D(v.content,k),h=$(v.meta.title,U(y,n,b),u)}}else if(f==="/lint"){let b=y.lint(),v="<h1>Health Check</h1>";if(b.length===0)v+='<p style="color:green;">No issues.</p>';else{v+="<table><tr><th>Type</th><th>Article</th><th>Issue</th></tr>";for(let m of b)v+=`<tr><td><span class="tag">${m.type}</span></td><td>${s(m.article)}</td><td>${s(m.message)}</td></tr>`;v+="</table>"}h=$("Health Check",U(y,n),v)}else if(f==="/search"){let b=x.searchParams.get("q")||"",v=await y.findRelevantReranked(b,void 0,20),m=`<h1>Search: "${s(b)}"</h1>`;for(let k of v)m+=`<div class="entry-card"><h3><a href="/article/${encodeURIComponent(k.path)}">${s(k.meta.title)}</a></h3><p>${s(k.content.slice(0,200))}...</p></div>`;v.length===0&&(m+="<p>No results.</p>"),h=$(`Search: ${b}`,U(y,n),m)}else if(f.startsWith("/tag/")){let b=decodeURIComponent(f.slice(5)),v=y.findByTags([b],void 0,100),m=`<h1>Tag: <a class="tag" href="#">${s(b)}</a></h1>`;m+=`<p>${v.length} article${v.length===1?"":"s"} tagged <code>${s(b)}</code></p>`;for(let k of v)m+=`<div class="entry-card"><h3><a href="/article/${encodeURIComponent(k.path)}">${s(k.meta.title)}</a></h3><div class="meta-line">${R((k.meta.tags||[]).slice(0,6))}</div></div>`;v.length===0&&(m+="<p>No articles with this tag.</p>"),h=$(`Tag: ${b}`,U(y,n),m)}}else{let y=o?await o.getRemoteAgents():[],b=l.summary(),v=new Map(b.map(u=>[u.agentId,u])),m=[],k=new Set;for(let u of b){let w=y.find(z=>z.agentId===u.agentId);w&&w.totalArticles>u.totalArticles?m.push({...w,totalEntries:Math.max(u.totalEntries,w.totalEntries),unabsorbed:Math.max(u.unabsorbed,w.unabsorbed)}):m.push(u),k.add(u.agentId)}for(let u of y)k.has(u.agentId)||(m.push(u),k.add(u.agentId));if(f==="/"||f==="")h=Me(l,m,y);else if(f==="/entries")h=Le(l,m);else if(f==="/search")h=Je(l,x.searchParams.get("q")||"",m);else if(f.startsWith("/tag/"))h=qe(l,decodeURIComponent(f.slice(5)),m);else if(f.match(/^\/agent\/[^/]+\/tag\/.+/)){let u=f.match(/^\/agent\/([^/]+)\/tag\/(.+)$/);h=Ke(l,decodeURIComponent(u[1]),decodeURIComponent(u[2]),m)}else if(f.startsWith("/agent/")){let u=f.slice(7),w=u.indexOf("/article/");if(w===-1)h=Fe(l,u,m);else{let z=u.slice(0,w),N=u.slice(w+9);if(h=je(l,z,N,m),!h&&o){let A=y.find(E=>E.agentId===z);if(A){let E=await o.getRemoteArticle(A.peerUrl,z,N);if(E){let S=`<div class="breadcrumb"><a href="/">Hub</a> / <span class="tag">remote @ ${s(A.nodeId)}</span> / ${s(z)}</div>`;S+=`<h1>${s(E.meta.title)}</h1>`,S+='<dl class="meta">',S+=`<dt>Tags</dt><dd>${(E.meta.tags||[]).map(be=>`<span class="tag">${be}</span>`).join(" ")}</dd>`,S+=`<dt>Source</dt><dd><span class="tag">remote</span> ${s(A.nodeId)}</dd>`,S+=`<dt>Updated</dt><dd>${E.meta.lastUpdated}</dd>`,S+="</dl>",S+=D(E.content,new Map),h=$(E.meta.title,I(m),S)}}}}}}if(!h){T=404;let y=n?U(l.getAgentWiki(n),n):I(l.summary());h=$("Not Found",y,"<h1>Page not found</h1>")}}catch(y){T=500,h=$("Error","",`<h1>Error</h1><pre>${s(y.message)}</pre>`)}g.writeHead(T,{"Content-Type":"text/html; charset=utf-8"}),g.end(c?Xe(h,c):h)}}function Xe(e,t){e=e.replace(/(\s(?:href|action)=")\/(?!\/)/g,`$1${t}/`),e=e.replace(new RegExp(`(${t})${t}/`,"g"),`${t}/`);let n=`<a href="/admin" style="position:fixed;top:10px;right:14px;z-index:9999;padding:5px 11px;background:rgba(0,0,0,0.55);color:#fff;font:12px/1.2 'IBM Plex Sans',system-ui,sans-serif;text-decoration:none;border-radius:6px;border:1px solid rgba(255,255,255,0.18);backdrop-filter:blur(6px)">\u2190 Dashboard</a>`;return e=e.replace(/<body([^>]*)>/,`<body$1>${n}`),e}function Kt(e,t=4200,n,a=[],r="graph"){let i=Ye({wikiDir:e,agentFilter:n,peerUrls:a,mode:r});Ne((l,o)=>{i(l,o)}).listen(t)}import{createCipheriv as Ge,createDecipheriv as Ve,createHash as Qe,randomBytes as K,randomInt as Ze,scryptSync as et,timingSafeEqual as tt}from"crypto";import{existsSync as nt,mkdirSync as at,readFileSync as rt,renameSync as it,writeFileSync as ot}from"fs";import{dirname as st,resolve as lt}from"path";var Y="23456789ABCDEFGHJKMNPQRSTUVWXYZ",X=8,dt=10*60*1e3,ct=".agentx/pair-codes.json",pt={N:16384,r:8,p:1};function gt(){let e="";for(let t=0;t<X;t++)e+=Y[Ze(Y.length)];return e}function Qt(e){return`${e.slice(0,4)}-${e.slice(4)}`}function mt(e){if(typeof e!="string"||e.length>64)return null;let t=e.toUpperCase().replace(/[\s\-‐-―]/g,"");if(t.length!==X)return null;for(let n of t)if(!Y.includes(n))return null;return t}var ve=class{constructor(t=process.cwd(),n=ct,a=Date.now){this.now=a;this.file=lt(t,n)}file;create(t){let n=this.load(),a=gt(),{id:r,key:i}=xe(a,n.salt),c=this.now(),l=new Date(c+dt).toISOString();return n.codes=n.codes.filter(o=>Date.parse(o.expiresAt)>c),n.codes.push({id:r,tokenId:t.tokenId,name:t.name,sealed:ut(i,t.token),createdAt:new Date(c).toISOString(),expiresAt:l}),this.save(n),{code:a,expiresAt:l}}redeem(t){let n=this.load(),a=mt(t),{id:r,key:i}=xe(a??"-".repeat(X),n.salt);if(!a)return null;let c=Buffer.from(r),l=n.codes.find(d=>d.id.length===r.length&&tt(Buffer.from(d.id),c));if(!l||Date.parse(l.expiresAt)<=this.now())return null;let o=ft(i,l.sealed);return o?(n.codes=n.codes.filter(d=>d!==l&&Date.parse(d.expiresAt)>this.now()),this.save(n),{token:o,tokenId:l.tokenId,name:l.name}):null}load(){if(nt(this.file))try{let t=JSON.parse(rt(this.file,"utf-8"));if(t&&typeof t.salt=="string"&&Array.isArray(t.codes))return t}catch{}return{salt:K(16).toString("hex"),codes:[]}}save(t){at(st(this.file),{recursive:!0});let n=`${this.file}.${process.pid}.${K(4).toString("hex")}.tmp`;ot(n,JSON.stringify(t,null,2)+`
|
|
739
739
|
`,{encoding:"utf-8",mode:384}),it(n,this.file)}};function xe(e,t){let n=et(e,Buffer.from(t,"hex"),64,pt);return{id:"sha256:"+Qe("sha256").update(n.subarray(0,32)).digest("hex"),key:n.subarray(32)}}function ut(e,t){let n=K(12),a=Ge("aes-256-gcm",e,n),r=Buffer.concat([a.update(t,"utf-8"),a.final()]);return Buffer.concat([n,a.getAuthTag(),r]).toString("base64")}function ft(e,t){try{let n=Buffer.from(t,"base64"),a=Ve("aes-256-gcm",e,n.subarray(0,12));return a.setAuthTag(n.subarray(12,28)),Buffer.concat([a.update(n.subarray(28)),a.final()]).toString("utf-8")}catch{return null}}var ht="https://ntfy.sh";function en(e){return{enabled:!!e?.enabled,server:e?.server||ht,topicSet:!!e?.topic,tokenSet:!!e?.token}}function tn(e,t){let n={...e??{}};if("enabled"in t&&(n.enabled=!!t.enabled),"server"in t){let a=String(t.server).trim().replace(/\/+$/,"");if(!/^https?:\/\/\S+$/.test(a))throw new Error("ntfy server must be an http(s) URL");n.server=a}if("topic"in t){let a=String(t.topic).trim();if(!a)throw new Error("ntfy topic cannot be empty");n.topic=a}if("token"in t){let a=String(t.token??"").trim();a?n.token=a:delete n.token}if(n.enabled&&!n.topic)throw new Error("set a topic before enabling ntfy");return n}export{oe as a,ge as b,Pt as c,Rt as d,Ut as e,dt as f,Qt as g,ve as h,Ht as i,Dt as j,Ot as k,en as l,tn as m,Ye as n,Kt as o};
|
|
740
|
-
//# sourceMappingURL=chunk-
|
|
740
|
+
//# sourceMappingURL=chunk-6QDOUOKD.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var e=["person","project","place","concept","event","decision","pattern"];function i(t){return typeof t=="string"&&e.includes(t)}export{e as a,i as b};
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
2
|
+
//# sourceMappingURL=chunk-CECHWYJ2.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/wiki/types.ts"],"sourcesContent":["// --- Wiki types ---\n//\n// Karpathy/Farzapedia pattern: plain files, LLM-chosen structure, articles\n// organized by `type` with wikilinks (`related`) as the primary navigation\n// surface. `_index.md` is the catalog; tags are a secondary hint, no longer\n// load-bearing. See blog/wiki-karpathy-review for the why.\n\nexport type WikiAccess = \"private\" | \"shared\" | \"public\"\n\n/**\n * Article type — the organizational spine. Matches Farzapedia's\n * `type: person | project | place | concept | event`, extended with\n * `decision` and `pattern` for workflow-heavy corpora.\n * Optional on legacy articles; Phase 2 migration backfills it.\n */\nexport type WikiArticleType =\n | \"person\"\n | \"project\"\n | \"place\"\n | \"concept\"\n | \"event\"\n | \"decision\"\n | \"pattern\"\n\n/** Runtime-iterable source of truth for the `type` enum. Use this for\n * write-side validation and CLI/prompt string interpolation. */\nexport const WIKI_ARTICLE_TYPES: readonly WikiArticleType[] = [\n \"person\",\n \"project\",\n \"place\",\n \"concept\",\n \"event\",\n \"decision\",\n \"pattern\",\n] as const\n\n/** True if `s` is a recognised article type. Use in the write path\n * to drop unknown values coming from upstream LLMs. */\nexport function isWikiArticleType(s: unknown): s is WikiArticleType {\n return typeof s === \"string\" && (WIKI_ARTICLE_TYPES as readonly string[]).includes(s)\n}\n\n/**\n * Article metadata. `type` + `related` are the primary retrieval surface;\n * tags remain as a secondary hint but are no longer central.\n */\nexport interface WikiArticleMeta {\n title: string\n /** Organizational spine — Phase 2 migration backfills any missing values. */\n type?: WikiArticleType\n /** Wikilink targets (by title) — persisted from `[[wikilinks]]` in body. */\n related?: string[]\n /** Secondary hint, no longer the retrieval spine. */\n tags: string[]\n owner: string // Agent ID\n access: WikiAccess\n sharedWith?: string[]\n created: string\n lastUpdated: string\n sources: string[] // Raw entry IDs\n /** Intent graph path (root → leaf node ids) when the article was authored\n * under an active intent graph. Empty for legacy articles — retrieval\n * falls back to pure BM25 for those. */\n graphPath?: string[]\n}\n\nexport interface WikiArticle {\n meta: WikiArticleMeta\n content: string // Markdown body — may contain section tags\n path: string // LLM-chosen path — structure emerges from data\n}\n\nexport interface WikiEntry {\n id: string\n date: string\n agentId: string\n source: string\n sourceContext?: string\n content: string\n meta?: Record<string, unknown>\n}\n\nexport interface WikiIndex {\n articles: Array<{\n path: string\n title: string\n type?: WikiArticleType\n related?: string[]\n tags: string[]\n owner: string\n access: WikiAccess\n sharedWith?: string[]\n aliases: string[]\n backlinks: number\n sources?: string[]\n lastUpdated?: string\n }>\n lastRebuilt: string\n}\n"],"mappings":"AA0BO,IAAMA,EAAiD,CAC5D,SACA,UACA,QACA,UACA,QACA,WACA,SACF,EAIO,SAASC,EAAkBC,EAAkC,CAClE,OAAO,OAAOA,GAAM,UAAaF,EAAyC,SAASE,CAAC,CACtF","names":["WIKI_ARTICLE_TYPES","isWikiArticleType","s"]}
|
|
1
|
+
{"version":3,"sources":["../src/wiki/types.ts"],"sourcesContent":["// --- Wiki types ---\n//\n// Karpathy/Farzapedia pattern: plain files, LLM-chosen structure, articles\n// organized by `type` with wikilinks (`related`) as the primary navigation\n// surface. `_index.md` is the catalog; tags are a secondary hint, no longer\n// load-bearing. See blog/wiki-karpathy-review for the why.\n\nexport type WikiAccess = \"private\" | \"shared\" | \"public\"\n\n/**\n * Article type — the organizational spine. Matches Farzapedia's\n * `type: person | project | place | concept | event`, extended with\n * `decision` and `pattern` for workflow-heavy corpora.\n * Optional on legacy articles; Phase 2 migration backfills it.\n */\nexport type WikiArticleType =\n | \"person\"\n | \"project\"\n | \"place\"\n | \"concept\"\n | \"event\"\n | \"decision\"\n | \"pattern\"\n\n/** Runtime-iterable source of truth for the `type` enum. Use this for\n * write-side validation and CLI/prompt string interpolation. */\nexport const WIKI_ARTICLE_TYPES: readonly WikiArticleType[] = [\n \"person\",\n \"project\",\n \"place\",\n \"concept\",\n \"event\",\n \"decision\",\n \"pattern\",\n] as const\n\n/** True if `s` is a recognised article type. Use in the write path\n * to drop unknown values coming from upstream LLMs. */\nexport function isWikiArticleType(s: unknown): s is WikiArticleType {\n return typeof s === \"string\" && (WIKI_ARTICLE_TYPES as readonly string[]).includes(s)\n}\n\n/**\n * Article metadata. `type` + `related` are the primary retrieval surface;\n * tags remain as a secondary hint but are no longer central.\n */\nexport interface WikiArticleMeta {\n title: string\n /** Organizational spine — Phase 2 migration backfills any missing values. */\n type?: WikiArticleType\n /** Wikilink targets (by title) — persisted from `[[wikilinks]]` in body. */\n related?: string[]\n /** Secondary hint, no longer the retrieval spine. */\n tags: string[]\n owner: string // Agent ID\n access: WikiAccess\n sharedWith?: string[]\n created: string\n lastUpdated: string\n sources: string[] // Raw entry IDs\n /** Intent graph path (root → leaf node ids) when the article was authored\n * under an active intent graph. Empty for legacy articles — retrieval\n * falls back to pure BM25 for those. */\n graphPath?: string[]\n}\n\nexport interface WikiArticle {\n meta: WikiArticleMeta\n content: string // Markdown body — may contain section tags\n path: string // LLM-chosen path — structure emerges from data\n}\n\nexport interface WikiEntry {\n id: string\n date: string\n agentId: string\n source: string\n sourceContext?: string\n content: string\n meta?: Record<string, unknown>\n}\n\nexport interface WikiIndex {\n articles: Array<{\n path: string\n title: string\n type?: WikiArticleType\n related?: string[]\n tags: string[]\n owner: string\n access: WikiAccess\n sharedWith?: string[]\n aliases: string[]\n backlinks: number\n sources?: string[]\n lastUpdated?: string\n /** Intent-graph path the article's sources were classified under. */\n graphPath?: string[]\n }>\n lastRebuilt: string\n}\n"],"mappings":"AA0BO,IAAMA,EAAiD,CAC5D,SACA,UACA,QACA,UACA,QACA,WACA,SACF,EAIO,SAASC,EAAkBC,EAAkC,CAClE,OAAO,OAAOA,GAAM,UAAaF,EAAyC,SAASE,CAAC,CACtF","names":["WIKI_ARTICLE_TYPES","isWikiArticleType","s"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Yn,b as Vn,d as es,f as nt,l as gs,r as ps,x as hs,z as ms}from"./chunk-
|
|
1
|
+
import{a as Yn,b as Vn,d as es,f as nt,l as gs,r as ps,x as hs,z as ms}from"./chunk-W7SEPJFH.js";import{a as Xn}from"./chunk-WP6KLXTP.js";import{a as Mt}from"./chunk-N6EWZGIX.js";import{b as Zn}from"./chunk-DP7RTNDM.js";import{a as ls}from"./chunk-W4YR2RO2.js";import{b as ns,c as _t,d as rs,e as os,h as is}from"./chunk-OPUPVGYP.js";import{a as zn}from"./chunk-SN5N2FPG.js";import{a as Rt,b as ts}from"./chunk-J3SOEFRE.js";import{a as Pt,b as ss}from"./chunk-SIU6STB2.js";import{e as as,i as cs,j as ds,k as us}from"./chunk-X5C5W3E4.js";import{a as Hn}from"./chunk-P2RYUODK.js";import{a as jn,b as Un,c as Bn,d as Wn,f as qn}from"./chunk-DWADWDMU.js";import{a as Kn,b as Gn}from"./chunk-23A5K5UW.js";import{a as tt,c as De}from"./chunk-2GIDVZ4H.js";import{c as Rn,d as Pn}from"./chunk-QOYAX2FT.js";import{b as Jn,c as Qn}from"./chunk-WLMQ5JMX.js";import{q as Nn,t as Ln,v as Te,w as Fn}from"./chunk-BBIWAJRX.js";import{a as Ee,b as et,f as $t}from"./chunk-72SZI2UW.js";import{a as xe,b as Ct}from"./chunk-FCPTN6NF.js";import{e as me}from"./chunk-DSYKYZMT.js";import{d as _n,e as ie,f as En,g as Dn,h as At,s as On,z as So}from"./chunk-DTX4I5LQ.js";Fn();$t();var fs="session-continuity",ys={continues:Ee("The new request continues the task the user was already working on in the previous request, rather than starting a separate one.",{true:`The new request advances, narrows, corrects or follows up on the previous request's task \u2014 including terse replies such as "and the cost?" or "why?" that mean nothing on their own.`,false:"The new request opens a subject that could be answered without having seen the previous request, even if it arrived seconds later or belongs to the same broad field."}),needsHistory:Ee("Does the new request refer to something stated earlier in the conversation?")};function bs(s){let e=(s.recentRequests??[]).filter(Boolean);return{newRequest:Et(s.message,1200),previousRequest:s.previousMessage?Et(s.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>Et(t,400))}:{},minutesSinceLastTurn:s.minutesSinceLastTurn,turnsSoFar:s.turnCount,currentContextTokens:s.lastTurnContextTokens,agent:s.agentId,channel:s.channel}}function ws(s,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,n=s.continues.noul,r=s.needsHistory.noul;return n<=t&&r<=t}function Et(s,e){let t=String(s??"");return t.length>e?t.slice(0,e):t}import{spawn as vo,execFile as Co}from"node:child_process";import{createHash as Ao,randomBytes as $o}from"node:crypto";import{createInterface as Mo}from"node:readline";import{promisify as Ro}from"node:util";var Po=Ro(Co),ae=class extends Error{constructor(t,n=!1){super(t);this.standalone=n}},Dt=class{constructor(e=8,t=3e5){this.capacity=e;this.idleMs=t}entries=new Map;versions=new Map;close(e){if(e.dead)return;e.dead=!0,clearTimeout(e.idle),e.child.kill("SIGTERM"),setTimeout(()=>{e.child.exitCode===null&&e.child.kill("SIGKILL")},3e3).unref()}stop(){for(let e of this.entries.values())this.close(e);this.entries.clear(),this.versions.clear()}async acquire(e){if(e.signal?.aborted)throw new Error("task cancelled by operator");let t=e.env.PATH||"",n=this.versions.get(t);if(n||(n=Po("opencode",["--version"],{env:e.env,timeout:5e3}).then(({stdout:l})=>/^(?:opencode\s+)?v?2\./.test(l.trim())).catch(()=>!1),this.versions.set(t,n),setTimeout(()=>this.versions.delete(t),6e4).unref()),!await n)throw new ae("Warm servers require OpenCode v2; using the CLI path");if(e.signal?.aborted)throw new Error("task cancelled by operator");let r=Ao("sha256").update(JSON.stringify([e.cwd,e.model,e.permission,Object.entries(e.env).sort(([d],[l])=>d.localeCompare(l))])).digest("hex"),o=this.entries.get(e.key);if(o?.busy)throw new ae("Conversation already running",!0);o&&(o.dead||o.fingerprint!==r||e.fresh)&&(this.close(o),this.entries.delete(e.key),o=void 0);let i=!!o;if(!o){if(this.entries.size>=this.capacity){let g=[...this.entries].find(([,f])=>!f.busy);if(!g)throw new ae("Warm server capacity reached",!0);this.close(g[1]),this.entries.delete(g[0])}let d={...e.env,OPENCODE_SERVER_USERNAME:"opencode",OPENCODE_SERVER_PASSWORD:$o(32).toString("hex")},l=vo("opencode",["serve","--hostname","127.0.0.1","--port","0","--stdio"],{cwd:e.cwd,env:d,stdio:["pipe","pipe","pipe"]});o={child:l,env:d,fingerprint:r,url:"",busy:!0,dead:!1},this.entries.set(e.key,o);let u=o;l.stderr.resume(),l.on("exit",()=>this.close(u)),l.on("error",()=>this.close(u));try{await new Promise((g,f)=>{let y=Mo({input:l.stdout}),x=()=>T(new ae("OpenCode server failed before dispatch",!0)),b=()=>T(new Error("task cancelled by operator")),S=setTimeout(x,15e3),T=D=>{clearTimeout(S),l.removeListener("exit",x),l.removeListener("error",x),e.signal?.removeEventListener("abort",b),y.close(),l.stdout.resume(),D?f(D):g()};l.once("exit",x),l.once("error",x),e.signal?.addEventListener("abort",b,{once:!0}),y.on("line",D=>{try{let M=new URL(JSON.parse(D).url);if(M.protocol!=="http:"||M.hostname!=="127.0.0.1"||!M.port||M.username||M.password)return;u.url=M.origin,T()}catch{}}),e.signal?.aborted&&b()})}catch(g){throw this.close(o),this.entries.get(e.key)===o&&this.entries.delete(e.key),g}}let a=o;clearTimeout(a.idle),a.busy=!0;let c=!1;return{url:a.url,env:a.env,reused:i,invalidate:()=>this.close(a),release:(d=!1)=>{c||(c=!0,a.busy=!1,d||a.dead?(this.close(a),this.entries.get(e.key)===a&&this.entries.delete(e.key)):(a.idle=setTimeout(()=>{this.close(a),this.entries.get(e.key)===a&&this.entries.delete(e.key)},this.idleMs),a.idle.unref()))}}}},xs=new Dt;import{execa as ct}from"execa";import{spawn as _o}from"node:child_process";import{createHash as Eo}from"node:crypto";import{createInterface as Do}from"node:readline";var ce=class extends Error{},Oo=s=>_o("codex",["app-server",...s.args],{cwd:s.cwd,env:s.env,stdio:["pipe","pipe","pipe"]}),Ot=class{child;pending=new Map;nextId=0;dead=!1;busy=!1;threadId;idle;notify;failTurn;constructor(e,t){this.child=t(e),this.child.stderr.resume(),Do({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
|
|
2
2
|
`)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let n=++this.nextId;return new Promise((r,o)=>{this.pending.set(n,{resolve:r,reject:o}),this.write({id:n,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let n of this.pending.values())n.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},Nt=class{constructor(e=Oo,t=8,n=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=n}entries=new Map;stop(){for(let{connection:e}of this.entries.values())e.close();this.entries.clear()}async run(e){let t=Date.now();if(e.signal?.aborted)return{content:"",error:"task cancelled by operator",duration:0};let n=Eo("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([b],[S])=>b.localeCompare(S))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new ce("Conversation already running");r&&(r.fingerprint!==n||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let b=[...this.entries].find(([,S])=>!S.connection.busy);if(!b)throw new ce("Codex warm process capacity reached");b[1].connection.close(),this.entries.delete(b[0])}try{r={fingerprint:n,connection:new Ot(e,this.launchProcess)}}catch{throw new ce("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,c="",d,l,u,g=!1,f=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",f,{once:!0});let y=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),x=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let b={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};l=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...b,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=l,clearTimeout(x),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let T=new Promise((D,M)=>{i.failTurn=M,i.notify=(C,_)=>{if(_?.threadId!==l)return;let N=_.item,E={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({..._,type:C.replace("/","."),...N?{item:{...N,type:E[N.type]||N.type}}:{}}),C==="item/completed"&&N?.type==="agentMessage"&&N.phase==="final_answer"&&(d=N.text),C==="item/agentMessage/delta"&&(g||(g=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=_.delta,e.onDelta?.(_.delta,c)),C==="thread/tokenUsage/updated"){let L=_.tokenUsage.last,F=L.cachedInputTokens||0;u={inputTokens:(u?.inputTokens||0)+Math.max(0,(L.inputTokens||0)-F),outputTokens:(u?.outputTokens||0)+(L.outputTokens||0),cacheReadTokens:(u?.cacheReadTokens||0)+F,cacheCreateTokens:(u?.cacheCreateTokens||0)+(L.cacheWriteInputTokens||0)}}C==="turn/completed"&&(_.turn.status==="completed"?D():M(new Error(_.turn.error?.message||`Codex turn ${_.turn.status}`)))}});return T.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:l,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await T,{content:d??c,codexSessionId:l,billedModel:e.model,usage:u,duration:Date.now()-t}}catch(b){if(i.close(),!a&&!e.signal?.aborted)throw new ce(b.message);return{content:c,codexSessionId:l,usage:u,error:b.message,duration:Date.now()-t}}finally{clearTimeout(x),clearTimeout(y),e.signal?.removeEventListener("abort",f),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},Ts=new Nt;import{execFile as Yo}from"child_process";import{StringDecoder as Fe}from"string_decoder";import{mkdtempSync as Os,readFileSync as Ns,rmSync as Ls}from"fs";import{join as it}from"path";import{tmpdir as Fs}from"os";function st(s){let e=(s||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let d=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${d?` Resets ${d[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),n;if(t)try{n=JSON.parse(t[0])}catch{}let r=n?.error||n,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),c=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||c===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||c===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||c===529||c===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||c===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:c&&c>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${c}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function rt(s){return s.fix?`${s.message} \u2014 ${s.fix}`:s.message}var ks=null;function ot(){return ks}function Tc(s){ks=s}function Oe(s){return`${s.agentId}:${s.channel}:${s.chatId}`}function No(s,e){if(s.state()==="busy")return null;let n=s.snapshot(),r=s.opts?.model;return r&&e.model&&r!==e.model?`model changed (${r} -> ${e.model})`:e.resumeSessionId?n.claudeSessionId&&n.claudeSessionId!==e.resumeSessionId?`session changed (${n.claudeSessionId.slice(0,8)} -> ${e.resumeSessionId.slice(0,8)})`:null:n.claudeSessionId?"session rotated":null}var ke=class extends Error{constructor(t,n,r){super(t);this.scope=n;this.cap=r;this.name="RegistryCapExceeded"}},Is=class{handles=new Map;sweeper;handleWorkspace=new Map;cfg;constructor(e){this.cfg={maxProcessesGlobal:e.maxProcessesGlobal??64,maxProcessesPerAgent:e.maxProcessesPerAgent??16,idleTimeoutMs:e.idleTimeoutMs??3e4,staleTimeoutMs:e.staleTimeoutMs??45*60*1e3,sweepIntervalMs:e.sweepIntervalMs??5e3,factory:e.factory,log:e.log??(()=>{}),currentWorkspaceHash:e.currentWorkspaceHash}}start(){this.sweeper||(this.sweeper=setInterval(()=>this.sweepIdle(),this.cfg.sweepIntervalMs),typeof this.sweeper.unref=="function"&&this.sweeper.unref())}async stop(){this.sweeper&&(clearInterval(this.sweeper),this.sweeper=void 0);let e=Array.from(this.handles.values());this.handles.clear(),await Promise.allSettled(e.map(t=>t.kill("registry-stop")))}acquire(e,t){let n=Oe(e),r=this.handles.get(n);if(r&&r.state()!=="dead"){let a=No(r,t);if(!a)return r.claim?.(),r;this.handles.delete(n),this.handleWorkspace.delete(n),this.cfg.log(`[process-registry] respawning ${n}: ${a}`),r.kill(a).catch(()=>{})}if(this.handles.size>=this.cfg.maxProcessesGlobal&&this.evictOldestIdle({scope:"global"}),this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent&&this.evictOldestIdle({scope:"agent",agentId:e.agentId}),this.handles.size>=this.cfg.maxProcessesGlobal)throw new ke(`process registry at global cap (${this.cfg.maxProcessesGlobal}) and no idle handle to evict`,"global",this.cfg.maxProcessesGlobal);if(this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent)throw new ke(`process registry at per-agent cap for ${e.agentId} (${this.cfg.maxProcessesPerAgent}) and no idle handle to evict`,"agent",this.cfg.maxProcessesPerAgent);let i=this.cfg.factory.spawn(e,t);return this.handles.set(n,i),this.handleWorkspace.set(n,t.workspace),this.cfg.log(`[process-registry] spawned ${n}`),i}release(e,t={}){let n=Oe(e),r=this.handles.get(n);r&&(this.handles.delete(n),this.handleWorkspace.delete(n),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=Oe(e),n=this.handles.get(t);return n!=null&&n.state()!=="dead"}async kill(e,t="operator"){let n=Oe(e),r=this.handles.get(n);r&&(this.handles.delete(n),this.handleWorkspace.delete(n),await r.kill(t))}countForAgent(e){let t=0;for(let n of this.handles.values())n.key.agentId===e&&n.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,n=Number.POSITIVE_INFINITY;for(let o of this.handles.values()){if(o.state()!=="idle"||e.scope==="agent"&&o.key.agentId!==e.agentId)continue;let i=o.snapshot().lastTurnAt;i<n&&(n=i,t=o)}if(!t)return!1;let r=Oe(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,n]of this.handles.entries()){let r=n.snapshot();if(n.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(n.state()!=="idle")continue;let o=e-r.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`stale (idle ${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed stale ${t}`);continue}if(o>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`idle (${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let i=this.handleWorkspace.get(t);if(i){let a=null;try{a=this.cfg.currentWorkspaceHash(n.key,i)}catch(c){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${c?.message||c}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let c=r.claudeMdHash??"unmarked",d=a??"unmarked";n.kill(`claude-md drifted (${c} \u2192 ${d})`),this.cfg.log(`[process-registry] killed drifted ${t} (${c} \u2192 ${d})`)}}}}}};import{spawn as Lo}from"child_process";import{existsSync as Fo,readFileSync as Ho}from"fs";import{resolve as jo}from"path";function Uo(s){let e=jo(s,"CLAUDE.md");if(!Fo(e))return null;try{let t=Ho(e,"utf8");return qn(t)}catch{return null}}var Bo=20*60*1e3,Wo=5e3,Ne=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},Le=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function qo(s,e){return s.AGENTX_AGENT_ID=e.agentId,s.AGENTX_CHANNEL=e.channel,s.AGENTX_CHAT_ID=e.chatId,delete s.AGENTX_TASK_ID,s}var Ss=class{constructor(e={}){this.opts=e}spawn(e,t){return new Lt(e,t,this.opts)}},Lt=class{constructor(e,t,n){this.key=e;this.opts=t;this.factoryOpts=n;let r=n.binary??"claude",o=this.buildArgs(t),i=n.log??(()=>{});this.child=Lo(r,o,{cwd:t.workspace,env:De(qo({...process.env},e),t.billing),stdio:["pipe","pipe","pipe"]}),this.snap={key:e,pid:this.child.pid??null,claudeSessionId:t.resumeSessionId??null,state:"warm-cold",spawnedAt:Date.now(),lastTurnAt:Date.now(),turnCount:0,lastInputTokens:0,pendingTaskId:null,claudeMdHash:Uo(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let c=this.waiters.splice(0);for(let d of c)d(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();snap;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,n=new Promise(l=>{t=l}),r=this.turnQueue;if(this.turnQueue=r.then(()=>n),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=JSON.stringify({type:"user",message:{role:"user",content:e.message}});this.child.stdin.write(i+`
|
|
3
3
|
`);let a=e.deadlineMs??Bo,c=o+a,d=()=>(this.kill(`turn deadline (${Math.round(a/6e4)}m)`),new Ne(a));try{for(;;){let l=c-Date.now();if(l<=0)throw d();let u=await this.nextEvent(l);if(u===null&&this.killReason)throw new Le(this.killReason);if(u===null&&!this.exited)throw d();if(u===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(yield{type:u.type,raw:u},u.type==="result"){this.onResultEvent(u);return}}}finally{let l=this.snap.state==="busy";this.snap={...this.snap,...l?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let n=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},Wo);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose"];return e.model&&t.push("--model",e.model),e.permissionMode==="bypassPermissions"&&t.push("--dangerously-skip-permissions"),e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.systemPromptAppend&&e.systemPromptAppend.trim().length>0&&t.push("--append-system-prompt",e.systemPromptAppend),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
|
|
4
4
|
`))!==-1;){let n=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!n.trim())continue;let r;try{r=JSON.parse(n)}catch{continue}this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let n=!1,r=setTimeout(()=>{if(n)return;n=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{n||(n=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},n=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;this.snap={...this.snap,lastTurnAt:Date.now(),turnCount:this.snap.turnCount+1,lastInputTokens:typeof t.input_tokens=="number"?t.input_tokens:this.snap.lastInputTokens,claudeSessionId:n,state:"idle"}}};At();import{resolve as vs,join as Cs}from"path";Ct();var Ko=4e3;function As(s){try{let e=Cs(vs(s.root),".agentx","db.sqlite"),t=Mt({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let n=xe(),r=s.input.command?s.input.command.slice(0,Ko):s.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
|
|
@@ -27,7 +27,7 @@ ${s}`}function Zo(s,e,t,n,r){let o=["run","--format","json","--thinking"],i=t||s
|
|
|
27
27
|
`,u)}};M.stdout?.on("data",I=>{E+=F.write(I);let w=E.split(`
|
|
28
28
|
`);E=w.pop()||"";for(let k of w)U(k)}),M.stderr?.on("data",I=>{L+=H.write(I)});let A=await M;if(i&&i.removeEventListener("abort",N),E+=F.end(),E.trim()&&U(E),L+=H.end(),C)return{content:"",error:_||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:f};if(A.exitCode!==0||y){let I=A,w;return I.timedOut?w=`OpenCode timed out after ${Math.round(T/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:y?w=y:I.code==="ENOENT"||/ENOENT|spawn opencode/i.test((I.shortMessage||"")+" "+L)?w=_s():w=L.trim()||`OpenCode exited with code ${I.exitCode??"unknown"}`,{content:"",...G(w),duration:Date.now()-c,usage:g,opencodeSessionId:f}}return b=!1,{content:u.trim(),duration:Date.now()-c,usage:g,billedModel:e.model||s.model,opencodeSessionId:f}}catch(T){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let D=/ENOENT|spawn opencode/i.test(T?.message||"")?_s():T?.message;return{content:u,...G(D||"OpenCode failed"),duration:Date.now()-c,usage:g,opencodeSessionId:f}}finally{S?.(),x?.release(b)}}async function ui(s,e,t,n){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=ue(s,e,n),c="",d=i({prompt:a,options:{model:e.model||s.model,cwd:s.workspace,permissionMode:"bypassPermissions"}});for await(let l of d)l.type==="result"&&l.subtype==="success"&&(c=l.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...G(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function li(s,e,t,n,r,o,i,a,c){let d=Date.now(),l=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),u=new AbortController,g=!1,f=()=>{let b=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{u.abort(new Error(b))}catch{}};a&&(a.aborted?f():a.addEventListener("abort",f,{once:!0}));let y=setTimeout(()=>{g=!0;try{u.abort(new Error(`orchestrator timed out after ${Math.round(l/6e4)}m`))}catch{}},l);y.unref?.();let x=()=>({content:"",...G(`Orchestrator timed out after ${Math.round(l/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let b=s.provider||"claude-code",S=n?`${n}
|
|
29
29
|
|
|
30
|
-
${e.message}`:e.message,T=e.context?.sender,D=typeof T=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(T),M=e.context?.channel==="web-chat"&&D?{userId:T,agentId:e.agentId||"acme-public"}:void 0,C=Wn(s),_=Object.keys(C).length>0,N={task:S,cwd:s.workspace,provider:b,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:M,providerOpts:o,abortSignal:u.signal,mcpServers:_?C:void 0};if(r){let{generateStream:U}=await import("./agent-
|
|
30
|
+
${e.message}`:e.message,T=e.context?.sender,D=typeof T=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(T),M=e.context?.channel==="web-chat"&&D?{userId:T,agentId:e.agentId||"acme-public"}:void 0,C=Wn(s),_=Object.keys(C).length>0,N={task:S,cwd:s.workspace,provider:b,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:M,providerOpts:o,abortSignal:u.signal,mcpServers:_?C:void 0};if(r){let{generateStream:U}=await import("./agent-V223TG6H.js"),A="",I,w,k,O;for await(let h of U(N)){if(c)try{c(h)}catch{}if(h.type==="text_delta")A+=h.text,r(h.text,A);else if(h.type==="thinking_delta")h.text&&i&&i(h.text);else if(h.type==="generate_result"){if(h.result.content&&h.result.content!==A){let ee=h.result.content.slice(A.length);ee?(A=h.result.content,r(ee,A)):A=h.result.content}I=h.result.tokensUsed,h.result.inputTokens!=null&&(w=h.result.inputTokens),h.result.outputTokens!=null&&(k=h.result.outputTokens)}else if(h.type==="done"){if(h.result.content&&h.result.content!==A){let ee=h.result.content.slice(A.length);ee?(A=h.result.content,r(ee,A)):A=h.result.content}h.result.tokensUsed!=null&&(I=h.result.tokensUsed)}else h.type==="error"&&(O=h.error)}return O&&!A?g?x():O==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...G(`Orchestrator error: ${O}`),duration:Date.now()-d}:((w===void 0||k===void 0)&&I&&(w=Math.round(I*.7),k=I-w),{content:A||"Done.",tokensUsed:I,usage:w!==void 0||k!==void 0?{inputTokens:w||0,outputTokens:k||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:E}=await import("./agent-V223TG6H.js"),L=await E(N),F=L.inputTokens,H=L.outputTokens;if((F===void 0||H===void 0)&&L.tokensUsed){let U=L.tokensUsed;F=Math.round(U*.7),H=U-F}return{content:L.content||"Done.",tokensUsed:L.tokensUsed,usage:F!==void 0||H!==void 0?{inputTokens:F||0,outputTokens:H||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(b){return g?x():b?.message==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...G(`Orchestrator error: ${b.message}`),duration:Date.now()-d}}finally{clearTimeout(y),a&&a.removeEventListener("abort",f)}}var gi=1e3;async function pi(s,e){let t=Promise.resolve(s).then(i=>({kind:"exit",r:i})),n,r=e.then(()=>new Promise(i=>{n=setTimeout(()=>i({kind:"grace"}),gi),n.unref?.()})),o=await Promise.race([t,r]);return n&&clearTimeout(n),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function hi(s,e,t,n,r,o,i){let a=ot();if(!a)return null;let c=Date.now(),d=e.context?.channel||"api",l=e.context?.chatId||e.context?.group||e.context?.sender||"default",u={agentId:e.agentId,channel:d,chatId:l};if(e.freshSession)try{await a.kill(u,"freshSession=true")}catch{}let g,f=!1;try{let A=a.list().length;g=a.acquire(u,{agentId:e.agentId,channel:d,chatId:l,workspace:s.workspace,model:e.model||s.model,permissionMode:s.permissionMode,billing:s.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:n}),f=a.list().length>A}catch(A){return A instanceof ke,null}f&&Wt(e.agentId,s,e.model,n,"persistent");let y=ue(s,e,t),x="",b,S,T,D,M,C,_,N="",E="",L=A=>{if(!i||!A)return;let I;if(E&&A.startsWith(E)?I=A.slice(E.length):I=N&&!N.endsWith(`
|
|
31
31
|
`)?`
|
|
32
32
|
|
|
33
33
|
${A}`:A,E=A,!!I){N+=I;try{i(I,N)}catch{}}},F=!1,H=()=>{F=!0,a.kill(u,"operator-cancel").catch(()=>{})};o&&(o.aborted?H():o.addEventListener("abort",H,{once:!0}));let U=!1;try{let A=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4);for await(let I of g.runTurn({message:y,taskId:e.taskId??"unknown",deadlineMs:A})){if(U=!0,r)try{r(I.raw)}catch{}if(I.type==="assistant"){let w=I.raw.message?.content??[];for(let O of w)O.type==="text"&&typeof O.text=="string"?(x=O.text,L(O.text)):O.type==="tool_use"&&(E="");let k=I.raw.message?.usage;if(k){let O=(k.input_tokens||0)+(k.cache_read_input_tokens||0)+(k.cache_creation_input_tokens||0);O>0&&(D=O)}}if(I.type==="result"){let w=I.raw;if(w.is_error){let k=G(typeof w.result=="string"?w.result:"claude error");b=k.error,S=k.errorKind}else typeof w.result=="string"&&w.result.length>0&&(x=w.result,N||L(w.result));typeof w.session_id=="string"&&(_=w.session_id),w.usage&&(T={inputTokens:w.usage.input_tokens||0,outputTokens:w.usage.output_tokens||0,cacheReadTokens:w.usage.cache_read_input_tokens||0,cacheCreateTokens:w.usage.cache_creation_input_tokens||0}),typeof w.num_turns=="number"&&(M=w.num_turns),typeof w.message?.model=="string"?C=w.message.model:typeof w.model=="string"&&(C=w.model)}}}catch(A){if(F)b="task cancelled by operator",S="cancelled";else if(U)if(A instanceof Le)b=`Claude Code was stopped mid-turn (${A.reason}), before its time limit`,S="interrupted";else if(A instanceof Ne){let I=G(`Claude Code timed out after ${Math.round(A.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||e.agentId}" if tasks need longer.`);b=I.error,S=I.errorKind}else{let I=G(`persistent claude process error: ${A?.message||String(A)}`);b=I.error,S=I.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${A?.message||A}); falling back to spawn-per-task`),a.release(u,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",H),null}finally{o&&o.removeEventListener("abort",H)}return F&&!b&&(b="task cancelled by operator",S="cancelled"),{content:F?"":x,error:b,errorKind:S,duration:Date.now()-c,usage:T,contextTokens:D,numTurns:M,billedModel:C,claudeSessionId:_}}function Js(s){return ie(s.autonomy)?s.taskId?Ms(s.autonomy,s.agentId,s.taskId):{error:`autonomy "${s.autonomy}" requires a task id to enforce`}:{args:[]}}async function mi(s,e,t,n,r,o,i){let a=e.autonomy,c=Rs(a,s.tier);if(c)return{content:"",error:c,autonomy:a};let d=e.taskId||`autonomy-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,l={...e,taskId:d,message:`${Dn(a)}
|
|
@@ -131,7 +131,7 @@ Agent: ${t.slice(0,1e3)}`}],{model:ji,maxTokens:512})).content.trim().match(/\[[
|
|
|
131
131
|
`)[0]?.slice(0,80)});return n}getChannelHandle(e,t){let n=this.agents.get(e)?.def;if(n)return t==="telegram"?n.mentions.find(r=>r.startsWith("@")):n.mentions[0]}async execute(e,t,n,r){let o=Date.now(),i;try{i=await this.executeInternal(e,t,n,r)}catch(c){i={content:"",error:c?.message??String(c)}}let a=e.runningTaskId?this.interruptedRuns.get(e.runningTaskId):void 0;if(a&&(this.interruptedRuns.delete(e.runningTaskId),i={...i,content:"",error:a,errorKind:"interrupted"}),e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i),e.intentRef)try{let c=i.error?nt(i.error)?"queued":/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";ns().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:c,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(c){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${c?.message??c}`)}return i}async executeInternal(e,t,n,r){let o=ie(e.autonomy),i=o?null:br().offer({agentId:e.agentId,text:e.message,channel:e.context?.channel||"api",chatId:String(e.context?.chatId||e.context?.group||"default"),sender:String(e.context?.sender||"unknown")});if(i){let p=await i;if(p.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${p.sessionId}`),{content:p.text,viaAttachedSession:p.sessionId};this.log(`[${e.agentId}] attached session did not take it (${p.reason}) \u2014 spawning`)}let a=this.agents.get(e.agentId);if(!a){if(o)return{content:"",error:`autonomy "${e.autonomy}" cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`,autonomy:e.autonomy};if(this.meshFallback){let p=this.meshFallback.directory().find(m=>m.healthy&&m.skills.some(v=>v.id===e.agentId));if(p){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${p.peer}"`);try{let m=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(p.peer,e.message,e.agentId,{timeoutMs:m}),viaMesh:p.peer}}catch(m){return this.log(`[${e.agentId}] mesh fallback to "${p.peer}" failed: ${m?.message??m}`),{content:"",error:`mesh fallback failed: ${m?.message??m}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let c=e.context?.channel||"api",d=e.context?.chatId||e.context?.group||e.context?.sender||"default",l;if(a.activeTasks>=a.def.maxConcurrent)if(c==="api"||c==="app"||c==="a2a"||c==="mcp"||c==="reminder"||c==="events"||o){let p=Date.now(),m=25*6e4,v=500;for(;a.activeTasks>=a.def.maxConcurrent;){if(Date.now()-p>m)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(m/6e4)}m`};await new Promise(P=>setTimeout(P,v))}}else if(c==="voice"){let p=Date.now(),m=25*6e4,v=`${e.agentId}\0${d}`;for(;this.messageQueue.isBusy(e.agentId,c,d)||this.voiceClaims.has(v);){if(Date.now()-p>m)return{content:"",error:`Agent "${e.agentId}" busy \u2014 voice wait timed out after ${Math.round(m/6e4)}m`};await new Promise(P=>setTimeout(P,500))}l=v,this.voiceClaims.add(v)}else{let p=a.def.queueMode||"collect",m=this.messageQueue.enqueue(e.agentId,c,d,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:c,chatId:d,originalContext:e.context,queuedAt:e.queuedAt});if(m==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(m){let v=this.messageQueue.pendingCount(e.agentId,c,d);return this.log(`[${e.agentId}] busy, message queued (mode: ${m}, pending: ${v}) behind=${a.runningTasks.map(P=>P.id).join(",")||"-"} chat=${c}:${d} at=${new Date().toISOString()}`),{content:"",error:es(m,v)}}}let u=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(p,m)=>{this.log(`[${e.agentId}] ${p} \u2014 queued, resumes in ~${Math.max(1,Math.round(m/1e3))}s`)}});if(l&&this.voiceClaims.delete(l),!u.ok)return this.log(`[${e.agentId}] ${u.reason}`),{content:"",error:u.reason};if(e.queuedAt!==void 0){let p=dr(e.queuedAt);p&&(e.message=`${p}
|
|
132
132
|
${e.message}`),e.queuedAt=void 0}a.activeTasks++,a.totalTasks++,a.lastActive=new Date;let g={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),message:e.message||"",channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date};if(a.runningTasks.push(g),e.runningTaskId=g.id,this.runningContexts.set(g.id,e.context??{}),e.onStart)try{e.onStart(g.id)}catch{}let f=new AbortController;this.taskAborts.set(g.id,{agentId:e.agentId,channel:g.channel,chatId:typeof g.chatId=="string"?g.chatId:"",originalMessage:e.message||"",controller:f});let y={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(g.id,y);let x=p=>{if(p){y.buffer+=p,y.buffer.length>Xr&&(y.buffer=y.buffer.slice(y.buffer.length-Xr));for(let m of y.subscribers)try{m(p)}catch{}}},b=xe();e.taskId=b;let S=new Map,T=(p,m,v)=>{try{V().emit("task:step",{taskId:b,agentId:e.agentId,name:"pipeline",action:p,status:v,ms:Date.now()-m,at:new Date().toISOString()})}catch{}},D=0,M=!1,C=()=>{M||(M=!0,D&&T("first-event",D,"ok"))},_;if(t){let p=ac();_=m=>{C();let v=p(m);if(v&&x(v),Zr(b,e.agentId,m),Vr(S,m),r)try{r(m)}catch{}}}else _=p=>{if(C(),Zr(b,e.agentId,p),Vr(S,p),r)try{r(p)}catch{}};let N=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,E=N?setTimeout(()=>f.abort(new Error(`timed out after ${Math.round(N/1e3)}s`)),N):void 0;E?.unref?.();let L=(a.def.preSpawnTimeoutSec??ec)*1e3,F=setTimeout(()=>{f.abort(new Error(`timed out before spawn after ${Math.round(L/1e3)}s in step "${g.step??"start"}"`))},L);F.unref?.();let H=()=>{F&&clearTimeout(F),F=void 0},U=()=>`task=${g.id} chat=${c}:${d} at=${new Date().toISOString()}`,A;f.signal.addEventListener("abort",()=>{let p=yt(f.signal).message;/^timed out/.test(p)&&(A=g.step??"start"),this.log(`[${e.agentId}] task ${g.id} aborted in step "${g.step??"start"}" \u2014 ${p} ${U()}`)},{once:!0});let I=p=>{g.step=p,this.log(`[${e.agentId}] step ${p} ${U()}`)},w=(p,m,v=0)=>{if(f.signal.aborted)return Promise.reject(yt(f.signal));I(p),(p==="agent"||p==="workflow-auto-run")&&(H(),D=Date.now());let P=Date.now();return Qr(m(),f.signal,v).then(W=>(T(p,P,"ok"),W),W=>{throw T(p,P,"error"),W})},k=!1,O=p=>{if(k)return;k=!0,this.runReleases.delete(g.id),E&&clearTimeout(E),H(),a.activeTasks--;let m=a.runningTasks.findIndex(v=>v.id===g.id);m!==-1&&a.runningTasks.splice(m,1),this.runningContexts.delete(g.id),this.taskAborts.delete(g.id),y.done=!0,y.endedAt=new Date;for(let v of y.subscribers)try{v(`
|
|
133
133
|
[task finished]
|
|
134
|
-
`)}catch{}y.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(g.id),Va).unref?.();try{let v=y.endedAt,P={id:g.id,agentId:e.agentId,channel:g.channel,chatId:g.chatId,sender:g.sender,message:e.message||"",startedAt:g.startedAt.toISOString(),endedAt:v.toISOString(),durationMs:v.getTime()-g.startedAt.getTime(),ok:!p?.error,error:p?.error,...A?{status:"timeout",step:A}:{},responseText:p?.content||"",transcript:y.buffer};this.persistTaskRecord(P);let W=(P.responseText||P.error||"").trim();if(W){let Q=W.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:Q,at:v,ok:P.ok})}}catch(v){this.log(`[${e.agentId}] task history persist failed: ${v?.message}`)}this.messageQueue.markDone(e.agentId,c,d).then(v=>{if(v.length!==0){this.log(`[${e.agentId}] flushing ${v.length} queued message(s) after task=${g.id} chat=${c}:${d} at=${new Date().toISOString()}`);for(let P of v){let W=P.originalContext||{channel:P.channel,sender:P.sender,chatId:P.chatId};this.execute({message:P.text,agentId:e.agentId,context:W,queuedAt:P.queuedAt??P.timestamp}).then(Q=>this.postQueuedResponseToChannel(e.agentId,W,Q)).catch(Q=>{this.log(`[${e.agentId}] queued message failed: ${Q.message}`)})}}}).catch(v=>{this.log(`[${e.agentId}] queue flush failed: ${v.message}`)})};this.runReleases.set(g.id,O),this.messageQueue.markRunning(e.agentId,c,d),this.log(`[${e.agentId}] executing task (${a.activeTasks}/${a.def.maxConcurrent}) ${U()}`);let h=e.context?.channel||"api",{evaluateRequest:ee,selectRequestContext:no}=await import("./request-planner-NMOAOZIM.js"),ge=await w("request-gate",()=>ee(e.message,e.agentId,h));ge.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`);let $=e.context?.chatId||e.context?.group||e.context?.sender||"default",bt=e.context?.sender||"User",te=a.def.tier==="codex-cli";e.freshSession&&(this.sessions.clearSession(e.agentId,h,$),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${h}:${$}`),V().emit("session:rotated",{agentId:e.agentId,channel:h,chatId:$,reason:"stale",at:new Date().toISOString()})),e.freshSession||await w("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,h,$,e.seedHistory));let so=[...this.sessions.getSession(e.agentId,h,$).messages].reverse().find(p=>p.role==="agent")?.content;Jr({agent:e.agentId,channel:h,chatId:$,message:e.message,previousReply:so,taskId:b}),this.sessions.addUserMessage(e.agentId,h,$,bt,e.message);let dn=Date.now();V().emit("task:started",{agentId:e.agentId,channel:h,chatId:$,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",at:new Date(dn).toISOString(),taskId:b,resumeOrigin:ar(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom});let Y,wt,un=this.classifier;if(un&&h!=="a2a"&&!te){I("classify");let p=Date.now();wt=un.classify({text:e.message,channel:h,sender:e.context?.sender,agentId:e.agentId}).then(m=>{Y=m||void 0,T("classify",p,"ok")},m=>{this.log(`[classifier] classify failed for ${e.agentId}: ${m?.message||m}`),T("classify",p,"error")})}let ln=async p=>{if(!wt)return;let m;await Promise.race([wt,new Promise(v=>{m=setTimeout(v,p),m.unref?.()})]),m&&clearTimeout(m)};await ln(Ja);let Re=this.config.workflows?.matching,we;if(this.config.workflows?.enabled&&Re?.enabled&&!o)try{let p=new gs({baseDir:q(process.cwd(),this.config.workflows.dir)}),m=ps({agentId:e.agentId,channel:h,message:e.message,intentPath:Y?.path},p.list());m&&m.confidence>=Re.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${m.workflow.id} confidence=${m.confidence.toFixed(2)} mode=${Re.mode} reasons=${m.reasons.join(",")||"n/a"}`),Re.mode==="auto"&&m.confidence>=Re.autoRunThreshold&&(this.workflowAutoRunner?we={workflowId:m.workflow.id,confidence:m.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(p){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${p?.message||p}`)}let ro=this.wikiHub.getAgentWiki(e.agentId),gn=this.memoryStore.findRelevant(e.message,e.agentId,te?3:8),pn=this.memoryStore.buildContext(gn),hn=this.memoryStore.contextFacts(gn),oo=this.patternStore.findRelevant(e.message,e.agentId,5),io=this.patternStore.buildContext(oo),mn="";if(!te)try{let{loadLocalSkills:p,getAutoInjectSkills:m}=await import("./loader-YFVSSYSL.js"),v=await w("skills",()=>p(a.def.workspace));mn=m(v,e.message)}catch{}let j=a.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,h,$):a.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,h,$):a.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,h,$):void 0;if(j&&this.sessions.isSessionStale(e.agentId,h,$)&&(this.log(`[${e.agentId}] session stale for ${h}:${$}, starting fresh`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,h,$,"stale"),this.sessions.clearClaudeSessionId(e.agentId,h,$),V().emit("session:rotated",{agentId:e.agentId,channel:h,chatId:$,reason:"stale",at:new Date().toISOString()}),j=void 0),j&&this.sessions.shouldRotateByTierTwo(e.agentId,h,$)){let p=this.sessions.getLastTurnContextTokens(e.agentId,h,$);this.log(`[${e.agentId}] tier-2 rotation for ${h}:${$} (last turn context: ${p} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,h,$,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,h,$),V().emit("session:rotated",{agentId:e.agentId,channel:h,chatId:$,reason:"tier-2",lastTurnInputTokens:p,at:new Date().toISOString()}),j=void 0}if(j&&this.sessions.shouldRotateByTurns(e.agentId,h,$)){let p=this.sessions.getTurnCount(e.agentId,h,$);this.log(`[${e.agentId}] max-turns rotation for ${h}:${$} (${p} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,h,$,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,h,$),V().emit("session:rotated",{agentId:e.agentId,channel:h,chatId:$,reason:"max-turns",at:new Date().toISOString()}),j=void 0}if(j&&a.def.tier==="claude-code"){let p=j;await w("rotate",()=>this.maybeRotateForContinuity(e,a,h,$,p))&&(j=void 0)}try{let p=await w("compact",()=>this.sessions.compactIfNeeded(e.agentId,h,$,this.memoryStore));if(p.compacted){let m=p.qualityScore??"?",v=p.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${h}:${$} (quality: ${m}%, ${v} entities lost)`),p.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${p.lostEntities.slice(0,5).join(", ")}`),p.drift){let P=p.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${P.overallScore} (lexicon=${P.lexiconDecay}, tools=${P.toolShift}, semantic=${P.semanticDrift})`),P.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${P.lostWords.slice(0,5).join(", ")}`)}}}catch(p){this.log(`[${e.agentId}] compaction failed (non-fatal): ${p.message}`)}let ao=process.env.AGENTX_CONTEXT_SURGERY==="1",co=te?{maxMessages:8,maxChars:2400}:ao&&zr(h,a.def.tier)?{maxMessages:6,maxChars:1800}:void 0,uo=!j&&!te?rc(ro,e.agentId):void 0,Ge=j?void 0:this.sessions.buildHistoryContext(e.agentId,h,$,co),lo=j?void 0:this.sessions.getRotationMemo(e.agentId,h,$)??void 0,fn,yn=[];if(this.config.procedures?.injection?.enabled&&!j&&!te)try{let p=new We({baseDir:q(process.cwd(),this.config.procedures.dir)}),m=tn(e.message,p.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(m.length>0){fn=nn(m),yn=m.map(v=>({id:v.procedure.meta.id,title:v.procedure.meta.title}));for(let v of m)this.log(`[${e.agentId}] procedure match ${v.procedure.meta.id} score=${v.score.toFixed(2)} (${v.reasons.join(",")})`)}}catch(p){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${p?.message||p}`)}if(me&&me.cat)try{let m=this.sessions.getSession(e.agentId,h,$).messages,v=m[0],P=m[m.length-1],W=Ge===void 0?`resume=${j?j.slice(0,8):"?"} (no rebuild)`:`fresh history=${Ge.length}c/${Ge.split(`
|
|
134
|
+
`)}catch{}y.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(g.id),Va).unref?.();try{let v=y.endedAt,P={id:g.id,agentId:e.agentId,channel:g.channel,chatId:g.chatId,sender:g.sender,message:e.message||"",startedAt:g.startedAt.toISOString(),endedAt:v.toISOString(),durationMs:v.getTime()-g.startedAt.getTime(),ok:!p?.error,error:p?.error,...A?{status:"timeout",step:A}:{},responseText:p?.content||"",transcript:y.buffer};this.persistTaskRecord(P);let W=(P.responseText||P.error||"").trim();if(W){let Q=W.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:Q,at:v,ok:P.ok})}}catch(v){this.log(`[${e.agentId}] task history persist failed: ${v?.message}`)}this.messageQueue.markDone(e.agentId,c,d).then(v=>{if(v.length!==0){this.log(`[${e.agentId}] flushing ${v.length} queued message(s) after task=${g.id} chat=${c}:${d} at=${new Date().toISOString()}`);for(let P of v){let W=P.originalContext||{channel:P.channel,sender:P.sender,chatId:P.chatId};this.execute({message:P.text,agentId:e.agentId,context:W,queuedAt:P.queuedAt??P.timestamp}).then(Q=>this.postQueuedResponseToChannel(e.agentId,W,Q)).catch(Q=>{this.log(`[${e.agentId}] queued message failed: ${Q.message}`)})}}}).catch(v=>{this.log(`[${e.agentId}] queue flush failed: ${v.message}`)})};this.runReleases.set(g.id,O),this.messageQueue.markRunning(e.agentId,c,d),this.log(`[${e.agentId}] executing task (${a.activeTasks}/${a.def.maxConcurrent}) ${U()}`);let h=e.context?.channel||"api",{evaluateRequest:ee,selectRequestContext:no}=await import("./request-planner-NMOAOZIM.js"),ge=await w("request-gate",()=>ee(e.message,e.agentId,h));ge.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`);let $=e.context?.chatId||e.context?.group||e.context?.sender||"default",bt=e.context?.sender||"User",te=a.def.tier==="codex-cli";e.freshSession&&(this.sessions.clearSession(e.agentId,h,$),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${h}:${$}`),V().emit("session:rotated",{agentId:e.agentId,channel:h,chatId:$,reason:"stale",at:new Date().toISOString()})),e.freshSession||await w("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,h,$,e.seedHistory));let so=[...this.sessions.getSession(e.agentId,h,$).messages].reverse().find(p=>p.role==="agent")?.content;Jr({agent:e.agentId,channel:h,chatId:$,message:e.message,previousReply:so,taskId:b}),this.sessions.addUserMessage(e.agentId,h,$,bt,e.message);let dn=Date.now();V().emit("task:started",{agentId:e.agentId,channel:h,chatId:$,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",at:new Date(dn).toISOString(),taskId:b,resumeOrigin:ar(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom});let Y,wt,un=this.classifier;if(un&&h!=="a2a"&&!te){I("classify");let p=Date.now();wt=un.classify({text:e.message,channel:h,sender:e.context?.sender,chatId:$,agentId:e.agentId}).then(m=>{Y=m||void 0,T("classify",p,"ok")},m=>{this.log(`[classifier] classify failed for ${e.agentId}: ${m?.message||m}`),T("classify",p,"error")})}let ln=async p=>{if(!wt)return;let m;await Promise.race([wt,new Promise(v=>{m=setTimeout(v,p),m.unref?.()})]),m&&clearTimeout(m)};await ln(Ja);let Re=this.config.workflows?.matching,we;if(this.config.workflows?.enabled&&Re?.enabled&&!o)try{let p=new gs({baseDir:q(process.cwd(),this.config.workflows.dir)}),m=ps({agentId:e.agentId,channel:h,message:e.message,intentPath:Y?.path},p.list());m&&m.confidence>=Re.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${m.workflow.id} confidence=${m.confidence.toFixed(2)} mode=${Re.mode} reasons=${m.reasons.join(",")||"n/a"}`),Re.mode==="auto"&&m.confidence>=Re.autoRunThreshold&&(this.workflowAutoRunner?we={workflowId:m.workflow.id,confidence:m.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(p){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${p?.message||p}`)}let ro=this.wikiHub.getAgentWiki(e.agentId),gn=this.memoryStore.findRelevant(e.message,e.agentId,te?3:8),pn=this.memoryStore.buildContext(gn),hn=this.memoryStore.contextFacts(gn),oo=this.patternStore.findRelevant(e.message,e.agentId,5),io=this.patternStore.buildContext(oo),mn="";if(!te)try{let{loadLocalSkills:p,getAutoInjectSkills:m}=await import("./loader-YFVSSYSL.js"),v=await w("skills",()=>p(a.def.workspace));mn=m(v,e.message)}catch{}let j=a.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,h,$):a.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,h,$):a.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,h,$):void 0;if(j&&this.sessions.isSessionStale(e.agentId,h,$)&&(this.log(`[${e.agentId}] session stale for ${h}:${$}, starting fresh`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,h,$,"stale"),this.sessions.clearClaudeSessionId(e.agentId,h,$),V().emit("session:rotated",{agentId:e.agentId,channel:h,chatId:$,reason:"stale",at:new Date().toISOString()}),j=void 0),j&&this.sessions.shouldRotateByTierTwo(e.agentId,h,$)){let p=this.sessions.getLastTurnContextTokens(e.agentId,h,$);this.log(`[${e.agentId}] tier-2 rotation for ${h}:${$} (last turn context: ${p} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,h,$,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,h,$),V().emit("session:rotated",{agentId:e.agentId,channel:h,chatId:$,reason:"tier-2",lastTurnInputTokens:p,at:new Date().toISOString()}),j=void 0}if(j&&this.sessions.shouldRotateByTurns(e.agentId,h,$)){let p=this.sessions.getTurnCount(e.agentId,h,$);this.log(`[${e.agentId}] max-turns rotation for ${h}:${$} (${p} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),a.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,a.def,j,h,$,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,h,$),V().emit("session:rotated",{agentId:e.agentId,channel:h,chatId:$,reason:"max-turns",at:new Date().toISOString()}),j=void 0}if(j&&a.def.tier==="claude-code"){let p=j;await w("rotate",()=>this.maybeRotateForContinuity(e,a,h,$,p))&&(j=void 0)}try{let p=await w("compact",()=>this.sessions.compactIfNeeded(e.agentId,h,$,this.memoryStore));if(p.compacted){let m=p.qualityScore??"?",v=p.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${h}:${$} (quality: ${m}%, ${v} entities lost)`),p.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${p.lostEntities.slice(0,5).join(", ")}`),p.drift){let P=p.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${P.overallScore} (lexicon=${P.lexiconDecay}, tools=${P.toolShift}, semantic=${P.semanticDrift})`),P.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${P.lostWords.slice(0,5).join(", ")}`)}}}catch(p){this.log(`[${e.agentId}] compaction failed (non-fatal): ${p.message}`)}let ao=process.env.AGENTX_CONTEXT_SURGERY==="1",co=te?{maxMessages:8,maxChars:2400}:ao&&zr(h,a.def.tier)?{maxMessages:6,maxChars:1800}:void 0,uo=!j&&!te?rc(ro,e.agentId):void 0,Ge=j?void 0:this.sessions.buildHistoryContext(e.agentId,h,$,co),lo=j?void 0:this.sessions.getRotationMemo(e.agentId,h,$)??void 0,fn,yn=[];if(this.config.procedures?.injection?.enabled&&!j&&!te)try{let p=new We({baseDir:q(process.cwd(),this.config.procedures.dir)}),m=tn(e.message,p.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(m.length>0){fn=nn(m),yn=m.map(v=>({id:v.procedure.meta.id,title:v.procedure.meta.title}));for(let v of m)this.log(`[${e.agentId}] procedure match ${v.procedure.meta.id} score=${v.score.toFixed(2)} (${v.reasons.join(",")})`)}}catch(p){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${p?.message||p}`)}if(me&&me.cat)try{let m=this.sessions.getSession(e.agentId,h,$).messages,v=m[0],P=m[m.length-1],W=Ge===void 0?`resume=${j?j.slice(0,8):"?"} (no rebuild)`:`fresh history=${Ge.length}c/${Ge.split(`
|
|
135
135
|
`).length}L`,Q=`[${e.agentId}] ${h}:${$} ${W} | session.messages=${m.length}`+(m.length>0?` first=${v.timestamp.slice(11,19)}(${v.role}:${(v.content||"").slice(0,40).replace(/\n/g," ")}) last=${P.timestamp.slice(11,19)}(${P.role}:${(P.content||"").slice(0,40).replace(/\n/g," ")})`:"");me.cat("context",Q)}catch(p){me.cat("context",`[${e.agentId}] context-diag error: ${p?.message??p}`)}let bn;if(a.def.contextReferences&&!j)try{let p=a.def.workspace,m=this.referencesCache.get(p);if(!m){let[P,W]=await w("references",()=>Promise.all([Rt(a.def.workspace),Pt(a.def.workspace)]));if(P.byId.size===0&&W.recipes.length===0){let[Q,he]=await w("references",()=>Promise.all([Rt(process.cwd()),Pt(process.cwd())]));m={refs:Q,recipes:he}}else m={refs:P,recipes:W};this.referencesCache.set(p,m)}let v=ss({agentId:e.agentId,intentTags:Y?.path,message:e.message},m.recipes,m.refs);v.cards.length>0&&(bn=ts(v.cards,500*4)),v.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${v.unresolvedIds.join(", ")}`)}catch(p){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${p?.message||p}`)}let wn=this.sessions.getCrossSessionSummary(e.agentId,h,$,e.message),xn,Je=Ys(e.message);if(Je)try{let p=this.sessions.recallTurns({agentId:e.agentId,channel:h,chatId:$,lookbackDays:Je.lookbackDays,limit:12});if(p.turns.length>0){let m=[`[Long-memory recall \u2014 last ${Je.lookbackDays}d on this chat (cue-triggered)]`],v=[...p.turns].sort((P,W)=>P.ts.localeCompare(W.ts));for(let P of v){let W=P.ts.slice(11,16)+" "+P.day,Q=P.role==="user"?P.senderName||"User":P.senderName||"Agent";m.push(`${W} ${Q}: ${P.content}`)}p.hasMore&&m.push(`[\u2026${p.totalScanned-p.turns.length}+ older turns available \u2014 call /recall with before=${p.oldestTs} to walk further back]`),m.push("[End of long-memory recall \u2014 respond to the latest message above]"),xn=m.join(`
|
|
136
136
|
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${Je.lookbackDays}d, turns=${p.turns.length}, scanned=${p.totalScanned}`)}}catch(p){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${p.message}`)}let go=te?"layered":e.contextStrategy??a.def.contextStrategy??this.config.session.contextStrategy??"layered",Tn,kn,In=!1;if(go==="planner"&&!ge.active&&h!=="voice"&&h!=="desktop"){try{let{planContext:p}=await import("./context-planner-JU7CNXCB.js"),m=await w("plan-context",()=>p({agentId:e.agentId,channel:h,chatId:$,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));m?(In=!0,Tn=m.sessionHistory,pn=m.memoryContext,hn=m.memoryFacts,wn=m.crossChatContext,kn=m.debug,this.log(`[${e.agentId}] planner: turns=${m.debug.recentTurns}, mem=${m.debug.memoryIncluded?"yes":"no"}, xchat=${m.debug.crossChatIncluded?"yes":"no"} (${m.debug.planLatencyMs}ms) \u2014 ${m.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(p){this.log(`[${e.agentId}] planner failed (non-fatal): ${p.message} \u2014 falling back to layered (keeping --resume for continuity)`)}In&&j&&(this.sessions.clearClaudeSessionId(e.agentId,h,$),j=void 0)}let xt=`${e.agentId}:${h}:${$}`,Qe=Bn(e.message);Qe&&(Qe==="default"?(this.activeSouls.delete(xt),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(xt,Qe),this.log(`[${e.agentId}] Soul switched to: ${Qe}`)));let po=this.activeSouls.get(xt),ho=jn(a.def.workspace,po),mo=Un(ho),fo=this.agentMemory.indexMarkdown(e.agentId),yo=a.def.tier==="claude-code"||a.def.tier==="codex-cli"?`[Operating principle]
|
|
137
137
|
Always investigate the codebase before relying on issue history or comments. The code is the source of truth \u2014 start by reading relevant files (CLAUDE.md, then code), and consult conversation context only to clarify intent. Issue threads may contain wrong hypotheses; verify against the source.`:"",bo=cc(a.def.richMessages,h),Sn="";if(a.def.workspace){let p=q(a.def.workspace,"CLAUDE.md");if(Z(p))try{let m=qe(p,"utf-8");Sn=`[Project CLAUDE.md]
|
|
@@ -149,4 +149,4 @@ ${R}`),m+=R.length}catch{}}}let wo=Tt.length>0?Tt.join(`
|
|
|
149
149
|
|
|
150
150
|
Agent: ${R.content}`,meta:nc(Y,e.context)})}catch{}Gn(e.agentId,e.message,R.content,{channel:h,chatId:$,sender:bt},this.memoryStore).catch(()=>{}),pr(e.agentId,e.message,R.content,{channel:h,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let J=R.billedModel||e.model||a.def.model,oe=e.context?.channel,Ze=oe&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${oe}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,R.duration||0,R.usage,e.message.length,R.content.length,!1,J,oe,Ze),this.log(`[${e.agentId}] completed in ${R.duration}ms`+(R.tokensUsed?` (${R.tokensUsed} tokens)`:"")+` ${U()}`)}return R}catch(p){a.errors++,this.log(`[${e.agentId}] unexpected error: ${p.message}`);let m=st(p.message);return pe={content:"",error:rt(m),errorKind:m.kind},pe}finally{Mn.stop(),O(pe)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}runningAgentDrainSeconds(){let e=[];for(let t of this.agents.values())t.activeTasks>0&&e.push(t.def.drainTimeoutSeconds);return e}list(){return Array.from(this.agents.values()).map(e=>{let t=this.lastSummaries.get(e.id);return{id:e.id,name:e.def.name,tier:e.def.tier,model:e.def.model,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive,runningTasks:e.runningTasks,lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),n=q(process.cwd(),Me,this.safe(e.agentId),t);Z(n)||za(n,{recursive:!0});let r=q(n,`${this.safe(e.id)}.json`);Ya(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let n=Date.now(),r=this.sparklineCache.get(e);if(r&&n-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=n-t*36e5,a=q(process.cwd(),Me,this.safe(e));if(!Z(a))return this.sparklineCache.set(e,{hourly:o,at:n}),o;let c=new Date(n).toISOString().slice(0,10),d=new Date(n-864e5).toISOString().slice(0,10);new Date(n).setUTCHours(0,0,0,0);for(let u of[d,c]){let g=q(a,u);if(Z(g))try{for(let f of se(g)){if(!f.endsWith(".json"))continue;let y=f.split("-")[0],x=parseInt(y,10);if(!Number.isFinite(x)||x<i||x>n)continue;let b=Math.floor((n-x)/36e5),S=t-1-b;S>=0&&S<t&&o[S]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:n}),o}hydrateLastSummariesFromDisk(){let e=q(process.cwd(),Me);if(!Z(e))return 0;let t=0;for(let n of se(e)){let r=q(e,n),o;try{o=se(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=q(r,i),c;try{c=se(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let l=JSON.parse(qe(q(a,d),"utf-8")),u=(l.responseText||l.error||"").trim();if(!u)continue;let g=u.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(l.agentId,{text:g,at:new Date(l.endedAt),ok:l.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=tc){let t=q(process.cwd(),Me);if(!Z(t))return 0;let n=Date.now()-e*24*60*60*1e3,r=0;for(let o of se(t)){let i=q(t,o),a;try{a=se(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=n))try{Xa(q(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let n=q(process.cwd(),Me,this.safe(e));if(!Z(n))return[];let r=se(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of r){if(o.length>=t)break;let a=q(n,i),c;try{c=se(a).filter(d=>d.endsWith(".json"))}catch{continue}c.sort().reverse();for(let d of c){if(o.length>=t)break;try{let l=JSON.parse(qe(q(a,d),"utf-8")),{transcript:u,responseText:g,...f}=l;o.push(f)}catch{}}}return o}getTaskRecord(e,t){let n=q(process.cwd(),Me,this.safe(e));if(!Z(n))return null;let r=this.safe(t),o=se(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=q(n,i,`${r}.json`);if(Z(a))try{return JSON.parse(qe(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,n){let r=ls();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||n.errorKind==="cancelled"||n.errorKind==="interrupted"||nt(n.error))return;let a=n.error?`Error: ${n.error}`:(n.content||"").trim();a&&r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}runningTaskOwner(e){for(let t of this.agents.values()){let n=t.runningTasks.find(r=>r.id===e);if(n)return{agentId:t.id,channel:n.channel,chatId:n.chatId}}return null}findRunningTurn(e,t={}){let n=this.agents.get(e);if(!n)return null;let r;if(t.taskId)r=n.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=n.runningTasks.filter(a=>a.channel===t.channel&&a.chatId===t.chatId);r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(n=>n.id)}:null}isChatBusy(e,t,n){return this.messageQueue.isBusy(e,t,n)}cancelRunningTask(e,t="operator"){let n=this.taskAborts.get(e);if(!n)return null;try{n.controller.abort(new Error(t))}catch{}return this.log(`[${n.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:n.agentId,channel:n.channel,chatId:n.chatId}}interruptRunning(e){let t=0;for(let[n,r]of this.taskAborts){this.interruptedRuns.set(n,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${n} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,n,r="operator"){let o=0;for(let[i,a]of this.taskAborts)a.agentId===e&&a.channel===t&&a.chatId===n&&this.cancelRunningTask(i,r)&&o++;return o}queueFollowUp(e,t,n,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:d}=o,l=o.controller.signal.aborted,u=!1;l&&d&&(u=this.sessions.removeLastUserMessageIfMatches(i,a,c,d)),this.messageQueue.enqueue(i,a,c,{text:t,sender:n,timestamp:Date.now(),channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:n}});let g=this.messageQueue.pendingCount(i,a,c),f=!1;if(r.replace){let y=r.reason||`replaced by follow-up from ${n}`;try{o.controller.abort(new Error(y))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${y}`),f=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${g}${u?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:f,edited:u,pending:g}}async continueFinishedTask(e,t,n,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,c=i.chatId;return new Promise(d=>{let l=!1,u=g=>{l||(l=!0,d(g))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:n,agentId:e,model:o.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:g=>u({ok:!0,agentId:e,channel:a,chatId:c,taskId:g,queued:!1})}).then(g=>{nt(g.error)?u({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):g.error?u({ok:!1,status:500,error:g.error||"run did not start"}):u({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:g.viaAttachedSession?"attached":"other"})}).catch(g=>u({ok:!1,status:500,error:g?.message??String(g)}))})}subscribeToTaskOutput(e,t){let n=this.taskOutputs.get(e);return n?n.done?{initial:n.buffer,done:!0,unsubscribe:()=>{}}:(n.subscribers.add(t),{initial:n.buffer,done:!1,unsubscribe:()=>{n.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function cc(s,e){return s===!1||e!=="telegram"&&e!=="whatsapp"&&e!=="app"?"":["[Rich replies]","On this chat channel you may add buttons, a poll, or media to a reply by appending ONE fenced block at the very end:","```agentx:ui",'{ "buttons": [{"label": "Open docs", "url": "https://..."}], "poll": {"question": "Ship it?", "options": ["Yes", "No"]}, "media": {"type": "image", "url": "https://..."} }',"```","All fields are optional; include only what helps. Buttons must be https URLs (tappable callback actions aren't supported yet). Use this sparingly \u2014 only when a link, choice, or image genuinely improves the reply. The block is stripped from the visible text.",...e==="app"?[`In this phone app you may also offer up to 4 short answers the user can tap instead of typing: "quickReplies": ["Yes", "Not now"] (at most 40 characters each), or a button with a reply instead of a url: {"label": "Run the tests", "reply": "Please run the tests"}. A tap sends that text as the user's next message, nothing more. Offer them only when the user is likely to answer with one of them.`]:[]].join(`
|
|
151
151
|
`)}export{xs as a,Ts as b,Tc as c,Is as d,Uo as e,Ss as f,As as g,Ec as h,Lc as i,Fc as j,ri as k,Ks as l,di as m,ui as n,li as o,Qs as p,ut as q,lt as r,pd as s,zt as t,V as u,hr as v,Ki as w,zi as x,yr as y,Rd as z,br as A,We as B,Ea as C,Da as D,Oa as E,Na as F,La as G,tn as H,ul as I,ll as J,nc as K,sc as L,rc as M,cn as N,Yr as O,Vr as P,ic as Q,Zr as R,eo as S,cc as T};
|
|
152
|
-
//# sourceMappingURL=chunk-
|
|
152
|
+
//# sourceMappingURL=chunk-FBDIJEKL.js.map
|