agentix-cli 0.69.0 → 0.69.2
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-VQIC7O5T.js → agent-P2UO35ZW.js} +2 -2
- package/dist/{board-dashboard-ZPJHXX3U.js → board-dashboard-3WVKEGRZ.js} +6 -5
- package/dist/{board-dashboard-ZPJHXX3U.js.map → board-dashboard-3WVKEGRZ.js.map} +1 -1
- package/dist/{chunk-ART666G6.js → chunk-2V7IQUEA.js} +2 -2
- package/dist/{chunk-PNWNVOEZ.js → chunk-4DRNEOOW.js} +2 -2
- package/dist/{chunk-NVJHA63C.js → chunk-4UMYRIEI.js} +10 -10
- package/dist/chunk-4UMYRIEI.js.map +1 -0
- package/dist/{chunk-HEJOWP7O.js → chunk-56AQBWEJ.js} +2 -2
- package/dist/{chunk-JHWBCDD2.js → chunk-A5ZCMRB3.js} +12 -9
- package/dist/chunk-A5ZCMRB3.js.map +1 -0
- package/dist/{chunk-BYKF3UTL.js → chunk-AIV547JW.js} +2 -2
- package/dist/chunk-ILEC3IAV.js +3 -0
- package/dist/chunk-ILEC3IAV.js.map +1 -0
- package/dist/{chunk-B65FS265.js → chunk-JSF2THM4.js} +2 -2
- package/dist/chunk-KA2UIZXG.js +3 -0
- package/dist/chunk-KA2UIZXG.js.map +1 -0
- package/dist/chunk-KXR6GVL7.js +5 -0
- package/dist/chunk-KXR6GVL7.js.map +1 -0
- package/dist/{chunk-QDRAKJSY.js → chunk-L2K4N3DA.js} +4 -4
- package/dist/chunk-M6HJDSLS.js +109 -0
- package/dist/chunk-M6HJDSLS.js.map +1 -0
- package/dist/{chunk-4NXIJEYU.js → chunk-U3XQ7USK.js} +9 -9
- package/dist/{chunk-4NXIJEYU.js.map → chunk-U3XQ7USK.js.map} +1 -1
- package/dist/{chunk-S4ASFOJU.js → chunk-VXDM7JAT.js} +2 -2
- package/dist/{chunk-5AMQFDLE.js → chunk-X4FD5OBK.js} +63 -63
- package/dist/{chunk-5AMQFDLE.js.map → chunk-X4FD5OBK.js.map} +1 -1
- package/dist/{chunk-NEC4RXFT.js → chunk-XMW422NO.js} +2 -2
- package/dist/{chunk-LPWPFEIE.js → chunk-YBLITM6C.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/fact-proposals-LZWS5KFO.js +2 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +1 -1
- package/dist/ledger-CH7R756S.js +2 -0
- package/dist/{migrate-v2-5VGHWPBW.js → migrate-v2-KOMPDC6U.js} +2 -2
- package/dist/{program-6PFRDQFT.js → program-GUBHJFZS.js} +2 -2
- package/dist/{promote-XRKH73IB.js → promote-7FMPZKXN.js} +2 -2
- package/dist/questions-ZATLU5AW.js +2 -0
- package/dist/{registry-KP3C4EZ4.js → registry-MUMQPZDM.js} +2 -2
- package/dist/{rotation-memo-store-X63HYIMV.js → rotation-memo-store-A4YW6FSK.js} +2 -2
- package/dist/{schedule-tool-ZVKBZOVG.js → schedule-tool-BY72YNNU.js} +2 -2
- package/dist/{scheduler-5NBO3J2G.js → scheduler-XWYFGG2S.js} +2 -2
- package/dist/{tool-ZENVUVBO.js → tool-ZUGNQZGI.js} +2 -2
- package/dist/{wiki-W6WI6HL3.js → wiki-LLL7VWRJ.js} +2 -2
- package/package.json +1 -1
- package/dist/chunk-AU6FFC4I.js +0 -5
- package/dist/chunk-AU6FFC4I.js.map +0 -1
- package/dist/chunk-CUZWGTXT.js +0 -109
- package/dist/chunk-CUZWGTXT.js.map +0 -1
- package/dist/chunk-JHWBCDD2.js.map +0 -1
- package/dist/chunk-NVJHA63C.js.map +0 -1
- package/dist/chunk-ST6KPQOY.js +0 -3
- package/dist/chunk-ST6KPQOY.js.map +0 -1
- package/dist/chunk-ZXR6GNEK.js +0 -3
- package/dist/chunk-ZXR6GNEK.js.map +0 -1
- package/dist/fact-proposals-ERRQXV2J.js +0 -2
- package/dist/ledger-DHYRP4TN.js +0 -2
- package/dist/questions-QGITDLJY.js +0 -2
- /package/dist/{agent-VQIC7O5T.js.map → agent-P2UO35ZW.js.map} +0 -0
- /package/dist/{chunk-ART666G6.js.map → chunk-2V7IQUEA.js.map} +0 -0
- /package/dist/{chunk-PNWNVOEZ.js.map → chunk-4DRNEOOW.js.map} +0 -0
- /package/dist/{chunk-HEJOWP7O.js.map → chunk-56AQBWEJ.js.map} +0 -0
- /package/dist/{chunk-BYKF3UTL.js.map → chunk-AIV547JW.js.map} +0 -0
- /package/dist/{chunk-B65FS265.js.map → chunk-JSF2THM4.js.map} +0 -0
- /package/dist/{chunk-QDRAKJSY.js.map → chunk-L2K4N3DA.js.map} +0 -0
- /package/dist/{chunk-S4ASFOJU.js.map → chunk-VXDM7JAT.js.map} +0 -0
- /package/dist/{chunk-NEC4RXFT.js.map → chunk-XMW422NO.js.map} +0 -0
- /package/dist/{chunk-LPWPFEIE.js.map → chunk-YBLITM6C.js.map} +0 -0
- /package/dist/{fact-proposals-ERRQXV2J.js.map → fact-proposals-LZWS5KFO.js.map} +0 -0
- /package/dist/{ledger-DHYRP4TN.js.map → ledger-CH7R756S.js.map} +0 -0
- /package/dist/{migrate-v2-5VGHWPBW.js.map → migrate-v2-KOMPDC6U.js.map} +0 -0
- /package/dist/{program-6PFRDQFT.js.map → program-GUBHJFZS.js.map} +0 -0
- /package/dist/{promote-XRKH73IB.js.map → promote-7FMPZKXN.js.map} +0 -0
- /package/dist/{questions-QGITDLJY.js.map → questions-ZATLU5AW.js.map} +0 -0
- /package/dist/{registry-KP3C4EZ4.js.map → registry-MUMQPZDM.js.map} +0 -0
- /package/dist/{rotation-memo-store-X63HYIMV.js.map → rotation-memo-store-A4YW6FSK.js.map} +0 -0
- /package/dist/{schedule-tool-ZVKBZOVG.js.map → schedule-tool-BY72YNNU.js.map} +0 -0
- /package/dist/{scheduler-5NBO3J2G.js.map → scheduler-XWYFGG2S.js.map} +0 -0
- /package/dist/{tool-ZENVUVBO.js.map → tool-ZUGNQZGI.js.map} +0 -0
- /package/dist/{wiki-W6WI6HL3.js.map → wiki-LLL7VWRJ.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-2V7IQUEA.js";import{b as ie,t as Xe,v as H,w as oe,y as ae}from"./chunk-4UMYRIEI.js";import{g as qe,h as Je,i as Ye,k as Ze,l as Qe}from"./chunk-XMW422NO.js";import{d as et,e as tt}from"./chunk-AQASR6KR.js";import{q as Ge}from"./chunk-A5ZCMRB3.js";import{w as Ke,z as An}from"./chunk-N5NPJ6DJ.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-JSF2THM4.js.map
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{b as F,c as S,d as $,f as x}from"./chunk-GQ76J72O.js";import{a as B,b as j,c as v}from"./chunk-ILEC3IAV.js";import{createHash as X}from"crypto";import{existsSync as z,statSync as G}from"fs";import{resolve as K}from"path";import{closeSync as D,existsSync as q,mkdirSync as C,openSync as M,readFileSync as N,renameSync as _,statSync as J,unlinkSync as g,writeFileSync as H}from"fs";import{dirname as E}from"path";var l=class extends Error{constructor(e,i){super(`fact ledger ${e} is unreadable (${i}). Nothing was written to it. Repair the JSON, or move the file aside to start an empty ledger.`);this.file=e;this.name="LedgerCorruptError"}},I=["id","subject","attribute","value","source","verifiedAt","verifiedBy","volatility"],W=["id","status","claim","source","verifiedAt","agentId"],L=(r,t)=>!!r&&typeof r=="object"&&!Array.isArray(r)&&t.every(e=>typeof r[e]=="string");function O(r){if(!q(r))return null;let t;try{t=JSON.parse(N(r,"utf-8"))}catch(s){throw new l(r,String(s?.message??s))}if(!t||typeof t!="object"||!Array.isArray(t.facts)||t.proposals!==void 0&&!Array.isArray(t.proposals))throw new l(r,"not a ledger: expected { facts: [], proposals: [] }");let e=t.facts.findIndex(s=>!L(s,I));if(e>=0)throw new l(r,`fact #${e+1} is missing ${I.join("/")}`);let i=(t.proposals??[]).findIndex(s=>!L(s,W));if(i>=0)throw new l(r,`proposal #${i+1} is missing ${W.join("/")}`);return{facts:t.facts,proposals:t.proposals??[]}}function P(r,t){C(E(r),{recursive:!0});let e=`${r}.${process.pid}.tmp`;H(e,JSON.stringify(t,null,2)+`
|
|
2
|
+
`),_(e,r)}var Q=r=>Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,r),p=new Set,w=(r,t)=>{try{return Date.now()-J(r).mtimeMs>t}catch{return!1}};function U(r,t){let e=`${r}.takeover`;if(w(e,t))try{g(e)}catch{}let i;try{i=M(e,"wx")}catch{return}try{w(r,t)&&g(r)}catch{}finally{D(i);try{g(e)}catch{}}}function R(r,t,e={}){let i=`${r}.lock`;if(p.has(i))return t();let s=e.timeoutMs??3e3,o=e.staleMs??15e3;C(E(i),{recursive:!0});let a=Date.now()+s,c;for(;c===void 0;)try{c=M(i,"wx")}catch(u){if(u?.code!=="EEXIST")throw u;if(w(i,o)&&U(i,o),Date.now()>a)throw new Error(`fact ledger is busy (${i}). If no agentx command is running, delete that lock and try again.`);Q(25)}p.add(i);try{return t()}finally{p.delete(i),D(c);try{g(i)}catch{}}}var d=r=>r.toLowerCase().replace(/\s+/g," ").trim();function V(r,t){return"f-"+X("sha1").update(`${d(r)}\0${d(t)}`).digest("hex").slice(0,10)}var T=class{constructor(t){this.wikiDir=t;this.file=K(t,"_facts.json")}file;cache;reported;load(){if(!z(this.file))return{version:1,facts:[],proposals:[]};let t=G(this.file).mtimeMs;if(this.cache?.mtimeMs===t)return structuredClone(this.cache.data);let e;try{e=O(this.file)}catch(s){throw this.reported!==t&&(this.reported=t,console.error(`[wiki-facts] ${s.message}`)),s}let i={version:1,facts:e?.facts??[],proposals:e?.proposals??[]};return this.cache={mtimeMs:t,data:i},structuredClone(i)}update(t){return R(this.file,()=>{this.cache=void 0;let e=this.load(),{save:i,result:s}=t(e);return i&&(P(this.file,e),this.cache=void 0),s})}list(){return this.load().facts}get(t){return this.list().find(e=>e.id===t||t.length>=6&&e.id.startsWith(t))??null}write(t,e={}){e.confirmedBy&&B("confirm a fact");let i=e.now??Date.now(),s=new Date(i).toISOString();if(!t.source?.trim())throw new Error('a fact needs a source: a system, URL, command or "owner said"');if(!t.subject?.trim()||!t.attribute?.trim()||!t.value?.trim())throw new Error("a fact needs a subject, an attribute and a value");let o=t.verifiedAt==="now"?i:Date.parse(t.verifiedAt??""),a=Number.isFinite(o),c=a?new Date(Math.min(o,i)).toISOString():s,u=F(t.volatility)?t.volatility:$(t.attribute,`${t.subject} ${t.attribute} is ${t.value}`),h={source:t.source.trim(),verifiedAt:c,verifiedBy:t.verifiedBy||"unknown",volatility:u,...typeof t.ttlDays=="number"?{ttlDays:t.ttlDays}:{}},b=V(t.subject,t.attribute),m=this.update(f=>{let n=f.facts.find(y=>y.id===b);if(!n){let y={id:b,subject:t.subject.trim(),attribute:t.attribute.trim(),value:t.value.trim(),...h,createdAt:s,updatedAt:s,...!a&&!e.confirmedBy?{undated:!0}:{},...e.confirmedBy?{confirmedBy:e.confirmedBy}:{}};return f.facts.push(y),{save:!0,result:{status:"created",fact:y}}}let A=Date.parse(n.verifiedAt),k=a&&(n.undated||!Number.isFinite(A)||Date.parse(c)>A);return d(n.value)===d(t.value)?!k&&!e.confirmedBy?{save:!1,result:{status:"unchanged",fact:n}}:(Object.assign(n,h,{updatedAt:s},e.confirmedBy?{confirmedBy:e.confirmedBy}:{}),delete n.undated,{save:!0,result:{status:"verified",fact:n}}):!e.confirmedBy&&(!k||n.confirmedBy)?{save:!1,result:{contradiction:n}}:(n.history=[...n.history??[],{value:n.value,source:n.source,verifiedAt:n.verifiedAt,verifiedBy:n.verifiedBy,replacedAt:s}].slice(-10),n.value=t.value.trim(),Object.assign(n,h,{updatedAt:s}),delete n.undated,e.confirmedBy?n.confirmedBy=e.confirmedBy:delete n.confirmedBy,{save:!0,result:{status:"updated",fact:n}})});if("contradiction"in m){let f=Y(this.wikiDir,m.contradiction,{...t,verifiedAt:a?c:"undated"});return{status:"contradiction",fact:m.contradiction,questionId:f.id,questionClosed:f.closed}}return m}};function Y(r,t,e){let i=new v(r),s={kind:"contradiction",agentId:e.verifiedBy||"unknown",path:"_facts.json",subject:t.subject,field:`${t.attribute}=${d(e.value)}`,tier:"pillar",factId:t.id,proposed:{value:e.value.trim(),source:e.source.trim(),verifiedAt:e.verifiedAt,verifiedBy:e.verifiedBy},question:`${t.subject} \xB7 ${t.attribute}: the wiki says "${t.value}" (${t.source}, checked ${t.verifiedAt.slice(0,10)}), but ${e.verifiedBy} reports "${e.value.trim()}" (${e.source.trim()}, checked ${e.verifiedAt.slice(0,10)}). Which is true?`},o=j(s.kind,s.agentId,s.subject,s.field);i.add([s]);let a=i.list().find(c=>c.id===o);return a?a.status==="answered"||a.status==="dismissed"?{closed:a.status}:{id:o}:{}}function dt(r){return new v(r).list("open").filter(t=>t.kind==="contradiction").map(t=>({type:"contradiction",articles:[`_facts.json#${t.factId??"?"}`],message:`[${t.id}] ${t.question}`,confidence:"high"}))}function ut(r,t=Date.now()){return r.undated===!0||x(r,t)}function lt(r,t){let e=d(r),i=null;for(let s of t){let o=d(s.subject);if(o.length<3||!e.includes(o))continue;let a=d(s.attribute).split(" ").filter(u=>u.length>2);(e.includes(d(s.value))||s.volatility!=="stable"&&S(r)===s.volatility||a.length>0&&a.every(u=>e.includes(u)))&&(!i||s.subject.length>i.subject.length)&&(i=s)}return i}export{R as a,V as b,T as c,dt as d,ut as e,lt as f};
|
|
3
|
+
//# sourceMappingURL=chunk-KA2UIZXG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/wiki/facts/ledger.ts","../src/wiki/facts/ledger-file.ts"],"sourcesContent":["import { createHash } from \"crypto\"\nimport { existsSync, statSync } from \"fs\"\nimport { resolve } from \"path\"\nimport { readLedger, withLock, writeLedger } from \"./ledger-file\"\nimport { classifyAttribute, classifyFact, isFactClass, isPastTtl, type FactClass, type Provenance } from \"@/agents/fact-freshness\"\nimport type { ContradictionIssue } from \"../lint-contradictions\"\nimport { QuestionStore, questionId } from \"../questions\"\n\n// --- The wiki fact ledger: durable facts with provenance (#273) ---\n//\n// Articles are prose. A fact an agent states to a person (\"the vendor\n// account is past due\") needs more than prose: where it came from, when\n// it was last checked, by whom, and how long it stays true. This is that\n// record — one small JSON sidecar beside `_questions.json`, skipped by the\n// article index like every `_` file.\n//\n// Every other store references it: memory lines that restate a ledger\n// fact are replaced by a reference at injection (agents/memory-context),\n// and memo claims wait here as proposals (fact-proposals.ts) instead of\n// becoming memory.\n//\n// Overwrite safety: a write that disagrees with the current value needs a\n// check newer than the current one, or a person's confirmation. Otherwise\n// the old value stays and a contradiction question joins the wiki's\n// question queue (`agentx wiki questions`), where the answer is written\n// back through here.\n\nexport interface WikiFact extends Provenance {\n id: string\n subject: string\n attribute: string\n value: string\n createdAt: string\n updatedAt: string\n /** Set when a person confirmed the value over a newer-dated one. */\n confirmedBy?: string\n /** Recorded with no check time: never counts as checked, so it is\n * always shown UNVERIFIED until a dated check or a person confirms it. */\n undated?: true\n /** Earlier values, newest last. Nothing is replaced silently. */\n history?: Array<{ value: string; source: string; verifiedAt: string; verifiedBy: string; replacedAt: string }>\n}\n\nexport interface FactInput {\n subject: string\n attribute: string\n value: string\n source: string\n verifiedBy: string\n /** When the source was checked (ISO date, or \"now\"). Without it the\n * write is undated and never counts as newer than an existing fact. */\n verifiedAt?: string\n volatility?: FactClass\n ttlDays?: number\n}\n\nexport type WriteStatus = \"created\" | \"verified\" | \"unchanged\" | \"updated\" | \"contradiction\"\n\nexport interface WriteResult {\n status: WriteStatus\n fact: WikiFact\n /** The queued question, for a contradiction. */\n questionId?: string\n /** Set instead of questionId when a person already answered or\n * dismissed this same claim, so it is not asked again. */\n questionClosed?: \"answered\" | \"dismissed\"\n}\n\nexport interface LedgerFile {\n version: 1\n facts: WikiFact[]\n proposals: import(\"./fact-proposals\").FactProposal[]\n}\n\nconst norm = (s: string) => s.toLowerCase().replace(/\\s+/g, \" \").trim()\n\n/**\n * Confirming a fact is a person's act. A process an agent runs carries\n * AGENTX_AGENT_ID (the runtime sets it for every agent), so a confirmation\n * from inside one is refused: an agent can't outrank a person, or itself.\n */\nimport { assertPerson } from \"./person\"\nexport { assertPerson }\n\n/** Stable per subject and attribute, so a re-check lands on the same fact. */\nexport function factId(subject: string, attribute: string): string {\n return \"f-\" + createHash(\"sha1\").update(`${norm(subject)}\\u0000${norm(attribute)}`).digest(\"hex\").slice(0, 10)\n}\n\nexport class FactLedger {\n readonly file: string\n private cache?: { mtimeMs: number; data: LedgerFile }\n private reported?: number\n\n constructor(readonly wikiDir: string) {\n this.file = resolve(wikiDir, \"_facts.json\")\n }\n\n /** The ledger as stored. Throws LedgerCorruptError on a file that does\n * not parse: it is never read as empty, so it is never overwritten. */\n load(): LedgerFile {\n if (!existsSync(this.file)) return { version: 1, facts: [], proposals: [] }\n const mtimeMs = statSync(this.file).mtimeMs\n if (this.cache?.mtimeMs === mtimeMs) return structuredClone(this.cache.data)\n let raw\n try {\n raw = readLedger(this.file)\n } catch (e) {\n // Once per version of the bad file, not once per prompt.\n if (this.reported !== mtimeMs) {\n this.reported = mtimeMs\n console.error(`[wiki-facts] ${(e as Error).message}`)\n }\n throw e\n }\n const data: LedgerFile = { version: 1, facts: (raw?.facts ?? []) as WikiFact[], proposals: (raw?.proposals ?? []) as LedgerFile[\"proposals\"] }\n this.cache = { mtimeMs, data }\n return structuredClone(data)\n }\n\n /**\n * Load, change and save under the ledger's lock, so concurrent writers\n * (a daemon proposing memo claims, a CLI `set`) can't drop each other's\n * change. `fn` returns whether to save, and a result.\n */\n update<T>(fn: (data: LedgerFile) => { save: boolean; result: T }): T {\n return withLock(this.file, () => {\n this.cache = undefined\n const data = this.load()\n const { save, result } = fn(data)\n if (save) {\n writeLedger(this.file, data)\n this.cache = undefined\n }\n return result\n })\n }\n\n list(): WikiFact[] { return this.load().facts }\n\n get(id: string): WikiFact | null {\n return this.list().find((f) => f.id === id || (id.length >= 6 && f.id.startsWith(id))) ?? null\n }\n\n /**\n * Record a checked fact. Refuses a fact with no source. A different value\n * replaces the current one only with a dated check newer than the current\n * one, or `confirmedBy`. A value a person confirmed is replaced only by\n * another confirmation. Otherwise the current value stays and a\n * contradiction question is raised.\n *\n * A write with no `verifiedAt` is undated: it can create a fact, but it\n * never counts as newer than a fact already there.\n */\n write(input: FactInput, opts: { confirmedBy?: string; now?: number } = {}): WriteResult {\n if (opts.confirmedBy) assertPerson(\"confirm a fact\")\n const now = opts.now ?? Date.now()\n const nowIso = new Date(now).toISOString()\n if (!input.source?.trim()) throw new Error(\"a fact needs a source: a system, URL, command or \\\"owner said\\\"\")\n if (!input.subject?.trim() || !input.attribute?.trim() || !input.value?.trim()) {\n throw new Error(\"a fact needs a subject, an attribute and a value\")\n }\n const checked = input.verifiedAt === \"now\" ? now : Date.parse(input.verifiedAt ?? \"\")\n const dated = Number.isFinite(checked)\n // A check can't be dated after it happened.\n const verifiedAt = dated ? new Date(Math.min(checked, now)).toISOString() : nowIso\n const volatility = isFactClass(input.volatility)\n ? input.volatility\n : classifyAttribute(input.attribute, `${input.subject} ${input.attribute} is ${input.value}`)\n const provenance: Provenance = {\n source: input.source.trim(), verifiedAt, verifiedBy: input.verifiedBy || \"unknown\", volatility,\n ...(typeof input.ttlDays === \"number\" ? { ttlDays: input.ttlDays } : {}),\n }\n const id = factId(input.subject, input.attribute)\n\n const out = this.update<WriteResult | { contradiction: WikiFact }>((data) => {\n const existing = data.facts.find((f) => f.id === id)\n if (!existing) {\n const fact: WikiFact = {\n id, subject: input.subject.trim(), attribute: input.attribute.trim(), value: input.value.trim(),\n ...provenance, createdAt: nowIso, updatedAt: nowIso,\n ...(!dated && !opts.confirmedBy ? { undated: true as const } : {}),\n ...(opts.confirmedBy ? { confirmedBy: opts.confirmedBy } : {}),\n }\n data.facts.push(fact)\n return { save: true, result: { status: \"created\", fact } }\n }\n\n const prior = Date.parse(existing.verifiedAt)\n // Any dated check beats a fact that was never dated.\n const newer = dated && (existing.undated || !Number.isFinite(prior) || Date.parse(verifiedAt) > prior)\n if (norm(existing.value) === norm(input.value)) {\n if (!newer && !opts.confirmedBy) return { save: false, result: { status: \"unchanged\", fact: existing } }\n Object.assign(existing, provenance, { updatedAt: nowIso }, opts.confirmedBy ? { confirmedBy: opts.confirmedBy } : {})\n delete existing.undated\n return { save: true, result: { status: \"verified\", fact: existing } }\n }\n\n // A person's confirmation outranks any agent's date.\n if (!opts.confirmedBy && (!newer || existing.confirmedBy)) {\n return { save: false, result: { contradiction: existing } }\n }\n\n existing.history = [...(existing.history ?? []), {\n value: existing.value, source: existing.source, verifiedAt: existing.verifiedAt,\n verifiedBy: existing.verifiedBy, replacedAt: nowIso,\n }].slice(-10)\n existing.value = input.value.trim()\n Object.assign(existing, provenance, { updatedAt: nowIso })\n delete existing.undated\n if (opts.confirmedBy) existing.confirmedBy = opts.confirmedBy\n else delete existing.confirmedBy\n return { save: true, result: { status: \"updated\", fact: existing } }\n })\n\n if (\"contradiction\" in out) {\n const q = raiseContradiction(this.wikiDir, out.contradiction, { ...input, verifiedAt: dated ? verifiedAt : \"undated\" })\n return { status: \"contradiction\", fact: out.contradiction, questionId: q.id, questionClosed: q.closed }\n }\n return out\n }\n}\n\nfunction raiseContradiction(wikiDir: string, current: WikiFact, input: FactInput & { verifiedAt: string }): { id?: string; closed?: \"answered\" | \"dismissed\" } {\n const store = new QuestionStore(wikiDir)\n const item = {\n kind: \"contradiction\" as const,\n agentId: input.verifiedBy || \"unknown\",\n path: \"_facts.json\",\n subject: current.subject,\n // One question per refused value: a second, different claim is a new\n // question, while repeating the same claim does not ask twice.\n field: `${current.attribute}=${norm(input.value)}`,\n tier: \"pillar\",\n factId: current.id,\n proposed: { value: input.value.trim(), source: input.source.trim(), verifiedAt: input.verifiedAt, verifiedBy: input.verifiedBy },\n question:\n `${current.subject} · ${current.attribute}: the wiki says \"${current.value}\" ` +\n `(${current.source}, checked ${current.verifiedAt.slice(0, 10)}), but ${input.verifiedBy} reports ` +\n `\"${input.value.trim()}\" (${input.source.trim()}, checked ${input.verifiedAt.slice(0, 10)}). Which is true?`,\n }\n const id = questionId(item.kind, item.agentId, item.subject, item.field)\n store.add([item])\n // Undefined when the queue could not take it (an unreadable file): the\n // old value still stands, and the caller says the question is missing.\n // Only an open question is one the owner will see. A person who already\n // answered or dismissed this same claim is not asked again; a question\n // that is missing altogether means the queue could not take it (an\n // unreadable file), and the old value still stands.\n const q = store.list().find((x) => x.id === id)\n if (!q) return {}\n if (q.status === \"answered\" || q.status === \"dismissed\") return { closed: q.status }\n return { id }\n}\n\n/** Open fact contradictions, in the shape `wiki lint` reports. */\nexport function factContradictions(wikiDir: string): ContradictionIssue[] {\n return new QuestionStore(wikiDir).list(\"open\")\n .filter((q) => q.kind === \"contradiction\")\n .map((q) => ({\n type: \"contradiction\" as const,\n articles: [`_facts.json#${q.factId ?? \"?\"}`],\n message: `[${q.id}] ${q.question}`,\n confidence: \"high\" as const,\n }))\n}\n\n/** A fact is stale when it is past its class TTL. */\nexport function isStaleFact(f: WikiFact, now = Date.now()): boolean {\n return f.undated === true || isPastTtl(f, now)\n}\n\n/**\n * The ledger fact a memory line restates, if any. The line must name the\n * fact's subject, and either repeat its value, share its volatility class,\n * or name its attribute.\n */\nexport function matchFact(content: string, facts: WikiFact[]): WikiFact | null {\n const text = norm(content)\n let best: WikiFact | null = null\n for (const f of facts) {\n const subject = norm(f.subject)\n if (subject.length < 3 || !text.includes(subject)) continue\n const attrWords = norm(f.attribute).split(\" \").filter((w) => w.length > 2)\n const hit = text.includes(norm(f.value))\n || (f.volatility !== \"stable\" && classifyFact(content) === f.volatility)\n || (attrWords.length > 0 && attrWords.every((w) => text.includes(w)))\n if (hit && (!best || f.subject.length > best.subject.length)) best = f\n }\n return best\n}\n","import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from \"fs\"\nimport { dirname } from \"path\"\n\n// --- The fact ledger's file: strict reads, locked writes (#273) ---\n//\n// Two rules keep the ledger from losing facts with nobody watching:\n// 1. A file that does not parse is never treated as empty. Reading it\n// throws LedgerCorruptError, so no write can replace it; the file is\n// left exactly as it is for a person to repair.\n// 2. load → modify → save runs under a lockfile, so a daemon proposing\n// memo claims and a CLI `set` or `approve` can't drop each other's\n// write.\n\nexport class LedgerCorruptError extends Error {\n constructor(readonly file: string, cause: string) {\n super(\n `fact ledger ${file} is unreadable (${cause}). Nothing was written to it. ` +\n `Repair the JSON, or move the file aside to start an empty ledger.`,\n )\n this.name = \"LedgerCorruptError\"\n }\n}\n\nexport interface RawLedger {\n facts: unknown[]\n proposals: unknown[]\n}\n\nconst FACT_FIELDS = [\"id\", \"subject\", \"attribute\", \"value\", \"source\", \"verifiedAt\", \"verifiedBy\", \"volatility\"]\nconst PROPOSAL_FIELDS = [\"id\", \"status\", \"claim\", \"source\", \"verifiedAt\", \"agentId\"]\n\nconst hasStrings = (o: unknown, keys: string[]) =>\n !!o && typeof o === \"object\" && !Array.isArray(o) && keys.every((k) => typeof (o as Record<string, unknown>)[k] === \"string\")\n\n/** Null when the file does not exist; throws when it exists but is not a ledger. */\nexport function readLedger(file: string): RawLedger | null {\n if (!existsSync(file)) return null\n let raw: any\n try {\n raw = JSON.parse(readFileSync(file, \"utf-8\"))\n } catch (e) {\n throw new LedgerCorruptError(file, String((e as Error)?.message ?? e))\n }\n if (!raw || typeof raw !== \"object\" || !Array.isArray(raw.facts) || (raw.proposals !== undefined && !Array.isArray(raw.proposals))) {\n throw new LedgerCorruptError(file, \"not a ledger: expected { facts: [], proposals: [] }\")\n }\n // Every entry is read by prompt rendering; one malformed entry must stop\n // the ledger being used, not crash a prompt or be dropped on the next save.\n const bad = raw.facts.findIndex((f: any) => !hasStrings(f, FACT_FIELDS))\n if (bad >= 0) throw new LedgerCorruptError(file, `fact #${bad + 1} is missing ${FACT_FIELDS.join(\"/\")}`)\n const badP = (raw.proposals ?? []).findIndex((p: any) => !hasStrings(p, PROPOSAL_FIELDS))\n if (badP >= 0) throw new LedgerCorruptError(file, `proposal #${badP + 1} is missing ${PROPOSAL_FIELDS.join(\"/\")}`)\n return { facts: raw.facts, proposals: raw.proposals ?? [] }\n}\n\nexport function writeLedger(file: string, data: unknown): void {\n mkdirSync(dirname(file), { recursive: true })\n const tmp = `${file}.${process.pid}.tmp`\n writeFileSync(tmp, JSON.stringify(data, null, 2) + \"\\n\")\n renameSync(tmp, file)\n}\n\nconst sleep = (ms: number) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)\n\n/** Locks this process holds, so a caller already inside one (approve →\n * write) re-enters instead of waiting on itself. */\nconst held = new Set<string>()\n\nconst isStale = (path: string, staleMs: number) => {\n try { return Date.now() - statSync(path).mtimeMs > staleMs } catch { return false }\n}\n\n/**\n * Take over a crashed holder's lock. Only one waiter may do it at a time\n * (a second `.takeover` lock), and it re-checks under that lock, so two\n * waiters that both saw the old lock can't both delete it — the second\n * would otherwise delete the first one's fresh lock.\n */\nexport function takeOver(lock: string, staleMs: number): void {\n const guard = `${lock}.takeover`\n if (isStale(guard, staleMs)) { try { unlinkSync(guard) } catch { /* another waiter did */ } }\n let fd: number\n try { fd = openSync(guard, \"wx\") } catch { return }\n try {\n if (isStale(lock, staleMs)) unlinkSync(lock)\n } catch {\n // Not removable (a directory, a permission): the wait times out with\n // an error naming the lock, rather than spinning.\n } finally {\n closeSync(fd)\n try { unlinkSync(guard) } catch { /* gone */ }\n }\n}\n\n/**\n * Run `fn` holding `<file>.lock`. Waits up to `timeoutMs` for another\n * holder; a lock older than `staleMs` is a crashed holder and is taken\n * over. Re-entrant within one process.\n */\nexport function withLock<T>(file: string, fn: () => T, opts: { timeoutMs?: number; staleMs?: number } = {}): T {\n const lock = `${file}.lock`\n if (held.has(lock)) return fn()\n const timeoutMs = opts.timeoutMs ?? 3000\n const staleMs = opts.staleMs ?? 15_000\n mkdirSync(dirname(lock), { recursive: true })\n const deadline = Date.now() + timeoutMs\n let fd: number | undefined\n while (fd === undefined) {\n try {\n fd = openSync(lock, \"wx\")\n } catch (e: any) {\n if (e?.code !== \"EEXIST\") throw e\n if (isStale(lock, staleMs)) takeOver(lock, staleMs)\n if (Date.now() > deadline) {\n throw new Error(`fact ledger is busy (${lock}). If no agentx command is running, delete that lock and try again.`)\n }\n sleep(25)\n }\n }\n held.add(lock)\n try {\n return fn()\n } finally {\n held.delete(lock)\n closeSync(fd)\n try { unlinkSync(lock) } catch { /* already gone */ }\n }\n}\n"],"mappings":"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","names":["createHash","existsSync","statSync","resolve","closeSync","existsSync","mkdirSync","openSync","readFileSync","renameSync","statSync","unlinkSync","writeFileSync","dirname","LedgerCorruptError","file","cause","FACT_FIELDS","PROPOSAL_FIELDS","hasStrings","o","keys","k","readLedger","raw","e","bad","f","badP","p","writeLedger","data","tmp","sleep","ms","held","isStale","path","staleMs","takeOver","lock","guard","fd","withLock","fn","opts","timeoutMs","deadline","norm","s","factId","subject","attribute","createHash","norm","FactLedger","wikiDir","resolve","existsSync","mtimeMs","statSync","raw","readLedger","e","data","fn","withLock","save","result","writeLedger","id","f","input","opts","assertPerson","now","nowIso","checked","dated","verifiedAt","volatility","isFactClass","classifyAttribute","provenance","out","existing","fact","prior","newer","q","raiseContradiction","current","store","QuestionStore","item","questionId","x","factContradictions","isStaleFact","isPastTtl","matchFact","content","facts","text","best","attrWords","w","classifyFact"]}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{a as d,c as F}from"./chunk-KA2UIZXG.js";import{c as u,j as g,k as f}from"./chunk-GQ76J72O.js";import{a as l}from"./chunk-ILEC3IAV.js";import{createHash as w}from"crypto";var m=(t,r)=>"fp-"+w("sha1").update(`${t}\0${r.toLowerCase().replace(/\s+/g," ").trim()}`).digest("hex").slice(0,10);function b(t){let r=t.replace(/^[-*•]\s*/,"").replace(/\s*\((?:[^)]*)\)\s*$/,"").trim(),s=r.match(/^(.{2,60}?)\s+(?:is|are|was|were|has been|went|got)\s+(.{1,80})$/i);if(!s)return{};let a=u(r);return{subject:s[1].trim(),attribute:a==="stable"?"state":`${a} status`,value:s[2].trim()}}function y(t,r,s){let a=t.at??new Date().toISOString(),e=f(s),o=u(s);return{id:r,status:"pending",claim:s,...b(s),volatility:o==="stable"?"work-state":o,source:e?.source??`${t.origin} (unchecked summary)`,verifiedAt:e?.verifiedAt??a,verifiedBy:t.agentId,origin:t.origin,agentId:t.agentId,...t.chat?{chat:t.chat}:{},createdAt:a}}function I(t,r){return r.length===0?[]:t.update(s=>{let a=[],e=!1;for(let o of r){let i=o.claim.replace(/^[-*•]\s*/,"").trim();if(!i)continue;let c=m(o.agentId,i),n=s.proposals.find(v=>v.id===c);if(n){a.push(n);continue}let p=y(o,c,i);s.proposals.push(p),a.push(p),e=!0}return{save:e,result:a}})}function A(t,r){return t.load().proposals.filter(s=>!r||s.status===r)}var P=(t,r)=>t.id===r||r.length>=6&&t.id.startsWith(r);function j(t,r){return t.load().proposals.find(s=>P(s,r))}function h(t,r,s){return t.update(a=>{let e=a.proposals.find(o=>P(o,r));if(!e)throw new Error(`no fact proposal "${r}"`);if(e.status!=="pending")throw new Error(`proposal ${e.id} is already ${e.status}`);return Object.assign(e,s),{save:!0,result:e}})}function B(t,r,s,a={}){return l("approve a fact proposal"),d(t.file,()=>$(t,r,s,a))}function $(t,r,s,a){let e=j(t,r);if(!e)throw new Error(`no fact proposal "${r}"`);if(e.status!=="pending")throw new Error(`proposal ${e.id} is already ${e.status}`);let o=a.subject??e.subject,i=a.attribute??e.attribute,c=a.value??e.value;if(!o||!i||!c)throw new Error("could not read a subject, attribute and value from the claim; pass --subject, --attribute and --value");let n=t.write({subject:o,attribute:i,value:c,source:a.source??e.source,verifiedBy:e.verifiedBy,verifiedAt:e.verifiedAt,volatility:e.volatility},{confirmedBy:s});return{proposal:h(t,e.id,{status:"approved",decidedAt:new Date().toISOString(),decidedBy:s}),write:n}}function E(t,r,s,a){return l("reject a fact proposal"),h(t,r,{status:"rejected",decidedAt:new Date().toISOString(),decidedBy:s,...a?{reason:a}:{}})}function C(t,r,s){let{workState:a,claims:e}=g(r);if(e.length===0)return{workState:a.join(`
|
|
2
|
+
`),pinned:r,proposals:[]};let o=[],i;try{o=I(new F(t),e.map(n=>({claim:n,...s})))}catch(n){i=String(n?.message??n)}let c=e.map((n,p)=>`- UNVERIFIED claim (${o[p]?`wiki proposal ${o[p].id}`:"not checked"}): ${n.replace(/^[-*•]\s*/,"")}`);return{workState:a.join(`
|
|
3
|
+
`),pinned:[...a,...c].join(`
|
|
4
|
+
`),proposals:o,...i?{error:i}:{}}}export{b as a,I as b,A as c,B as d,E as e,C as f};
|
|
5
|
+
//# sourceMappingURL=chunk-KXR6GVL7.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/wiki/facts/fact-proposals.ts"],"sourcesContent":["import { createHash } from \"crypto\"\nimport { citedCheck, classifyFact, splitMemo, type FactClass } from \"@/agents/fact-freshness\"\nimport { assertPerson, FactLedger, type FactInput, type WriteResult } from \"./ledger\"\nimport { withLock } from \"./ledger-file\"\n\n// --- Fact proposals: what a session summary claims, waiting for a check ---\n//\n// A rotation or continuity memo is a model's summary of a session. When it\n// says \"the vendor account is past due\", that is a claim nobody checked in\n// this form, and storing it as memory is how a stale note became a stated\n// fact (#273). So memo claims about outside systems come here instead,\n// with where they came from. They reach the ledger only when a person\n// approves one (a confirmation), never on their own.\n\nexport type FactProposalStatus = \"pending\" | \"approved\" | \"rejected\"\n\nexport interface FactProposal {\n id: string\n status: FactProposalStatus\n /** The line as the memo stated it. */\n claim: string\n /** Best guess at the structured fact, editable on approval. */\n subject?: string\n attribute?: string\n value?: string\n volatility: FactClass\n /** The check the memo cited, or where the claim came from. */\n source: string\n /** When that check happened, or when the memo was written. */\n verifiedAt: string\n verifiedBy: string\n /** e.g. \"rotation-memo:tier-2\" or \"continuity-memo\". */\n origin: string\n agentId: string\n chat?: string\n createdAt: string\n decidedAt?: string\n decidedBy?: string\n reason?: string\n}\n\nexport interface ProposalInput {\n claim: string\n agentId: string\n origin: string\n chat?: string\n at?: string\n}\n\nconst proposalId = (agentId: string, claim: string) =>\n \"fp-\" + createHash(\"sha1\").update(`${agentId}\\u0000${claim.toLowerCase().replace(/\\s+/g, \" \").trim()}`).digest(\"hex\").slice(0, 10)\n\n/** \"X is Y\" → subject X, value Y, attribute named after the class. */\nexport function parseClaim(claim: string): { subject?: string; attribute?: string; value?: string } {\n const text = claim.replace(/^[-*•]\\s*/, \"\").replace(/\\s*\\((?:[^)]*)\\)\\s*$/, \"\").trim()\n const m = text.match(/^(.{2,60}?)\\s+(?:is|are|was|were|has been|went|got)\\s+(.{1,80})$/i)\n if (!m) return {}\n const cls = classifyFact(text)\n return { subject: m[1].trim(), attribute: cls === \"stable\" ? \"state\" : `${cls} status`, value: m[2].trim() }\n}\n\nfunction newProposal(it: ProposalInput, id: string, claim: string): FactProposal {\n const at = it.at ?? new Date().toISOString()\n const cited = citedCheck(claim)\n const cls = classifyFact(claim)\n return {\n id, status: \"pending\", claim, ...parseClaim(claim),\n // A summary's claim is never stable: at best it was true that day.\n volatility: cls === \"stable\" ? \"work-state\" : cls,\n source: cited?.source ?? `${it.origin} (unchecked summary)`,\n verifiedAt: cited?.verifiedAt ?? at,\n verifiedBy: it.agentId,\n origin: it.origin, agentId: it.agentId,\n ...(it.chat ? { chat: it.chat } : {}),\n createdAt: at,\n }\n}\n\n/** Queue claims, under the ledger's lock. The same claim from the same\n * agent is kept once. Throws on an unreadable ledger rather than\n * writing over it. */\nexport function proposeFacts(ledger: FactLedger, items: ProposalInput[]): FactProposal[] {\n if (items.length === 0) return []\n return ledger.update((data) => {\n const out: FactProposal[] = []\n let added = false\n for (const it of items) {\n const claim = it.claim.replace(/^[-*•]\\s*/, \"\").trim()\n if (!claim) continue\n const id = proposalId(it.agentId, claim)\n const seen = data.proposals.find((p) => p.id === id)\n if (seen) { out.push(seen); continue }\n const p = newProposal(it, id, claim)\n data.proposals.push(p)\n out.push(p)\n added = true\n }\n return { save: added, result: out }\n })\n}\n\nexport function listFactProposals(ledger: FactLedger, status?: FactProposalStatus): FactProposal[] {\n return ledger.load().proposals.filter((p) => !status || p.status === status)\n}\n\nconst matches = (x: FactProposal, id: string) => x.id === id || (id.length >= 6 && x.id.startsWith(id))\n\nfunction findProposal(ledger: FactLedger, id: string): FactProposal | undefined {\n return ledger.load().proposals.find((x) => matches(x, id))\n}\n\n/** Decide a pending proposal under the ledger's lock. */\nfunction decide(ledger: FactLedger, id: string, fields: Partial<FactProposal>): FactProposal {\n return ledger.update((data) => {\n const p = data.proposals.find((x) => matches(x, id))\n if (!p) throw new Error(`no fact proposal \"${id}\"`)\n if (p.status !== \"pending\") throw new Error(`proposal ${p.id} is already ${p.status}`)\n Object.assign(p, fields)\n return { save: true, result: p }\n })\n}\n\n/**\n * Approve a claim: a person confirms it, so it is written to the ledger\n * with their name, even over a newer-dated value.\n */\nexport function approveFactProposal(\n ledger: FactLedger, id: string, by: string,\n edit: Partial<Pick<FactInput, \"subject\" | \"attribute\" | \"value\" | \"source\">> = {},\n): { proposal: FactProposal; write: WriteResult } {\n assertPerson(\"approve a fact proposal\")\n // One lock for the whole approval: the fact write and the decision\n // land together, or neither does (both re-enter this lock).\n return withLock(ledger.file, () => approveLocked(ledger, id, by, edit))\n}\n\nfunction approveLocked(\n ledger: FactLedger, id: string, by: string,\n edit: Partial<Pick<FactInput, \"subject\" | \"attribute\" | \"value\" | \"source\">>,\n): { proposal: FactProposal; write: WriteResult } {\n const p = findProposal(ledger, id)\n if (!p) throw new Error(`no fact proposal \"${id}\"`)\n if (p.status !== \"pending\") throw new Error(`proposal ${p.id} is already ${p.status}`)\n const subject = edit.subject ?? p.subject\n const attribute = edit.attribute ?? p.attribute\n const value = edit.value ?? p.value\n if (!subject || !attribute || !value) {\n throw new Error(\"could not read a subject, attribute and value from the claim; pass --subject, --attribute and --value\")\n }\n const write = ledger.write(\n { subject, attribute, value, source: edit.source ?? p.source, verifiedBy: p.verifiedBy, verifiedAt: p.verifiedAt, volatility: p.volatility },\n { confirmedBy: by },\n )\n const proposal = decide(ledger, p.id, { status: \"approved\", decidedAt: new Date().toISOString(), decidedBy: by })\n return { proposal, write }\n}\n\nexport function rejectFactProposal(ledger: FactLedger, id: string, by: string, reason?: string): FactProposal {\n assertPerson(\"reject a fact proposal\")\n return decide(ledger, id, { status: \"rejected\", decidedAt: new Date().toISOString(), decidedBy: by, ...(reason ? { reason } : {}) })\n}\n\n/**\n * Route a session memo: claims about outside systems become proposals;\n * the rest is work state. `pinned` is what the next fresh session reads,\n * with each claim marked unverified and pointing at its proposal.\n */\nexport function routeMemo(\n wikiDir: string, memo: string, ctx: { agentId: string; origin: string; chat?: string },\n): { workState: string; pinned: string; proposals: FactProposal[]; error?: string } {\n const { workState, claims } = splitMemo(memo)\n if (claims.length === 0) return { workState: workState.join(\"\\n\"), pinned: memo, proposals: [] }\n let proposals: FactProposal[] = []\n let error: string | undefined\n try {\n proposals = proposeFacts(new FactLedger(wikiDir), claims.map((claim) => ({ claim, ...ctx })))\n } catch (e) {\n // An unwritable wiki must not lose the memo: claims stay out of\n // memory and are pinned for this chat only, still marked.\n error = String((e as Error)?.message ?? e)\n }\n const flagged = claims.map((c, i) =>\n `- UNVERIFIED claim (${proposals[i] ? `wiki proposal ${proposals[i].id}` : \"not checked\"}): ${c.replace(/^[-*•]\\s*/, \"\")}`)\n return { workState: workState.join(\"\\n\"), pinned: [...workState, ...flagged].join(\"\\n\"), proposals, ...(error ? { error } : {}) }\n}\n"],"mappings":"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","names":["createHash","proposalId","agentId","claim","createHash","parseClaim","text","m","cls","classifyFact","newProposal","it","id","at","cited","citedCheck","proposeFacts","ledger","items","data","out","added","seen","p","listFactProposals","status","matches","x","findProposal","decide","fields","approveFactProposal","by","edit","assertPerson","withLock","approveLocked","subject","attribute","value","write","rejectFactProposal","reason","routeMemo","wikiDir","memo","ctx","workState","claims","splitMemo","proposals","error","FactLedger","e","flagged","c","i"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as qn,b as Kn,d as Jn,f as Ze,l as os,r as is,x as as,z as cs}from"./chunk-
|
|
1
|
+
import{a as qn,b as Kn,d as Jn,f as Ze,l as os,r as is,x as as,z as cs}from"./chunk-4UMYRIEI.js";import{a as It}from"./chunk-N6EWZGIX.js";import{a as Wn}from"./chunk-WP6KLXTP.js";import{b as Gn}from"./chunk-DP7RTNDM.js";import{a as rs}from"./chunk-W4YR2RO2.js";import{b as zn,c as Ct,d as Yn,e as Vn,h as Zn}from"./chunk-A5ZCMRB3.js";import{a as St,b as Qn}from"./chunk-J3SOEFRE.js";import{a as vt,b as Xn}from"./chunk-SIU6STB2.js";import{e as es,i as ts,j as ns,k as ss}from"./chunk-X5C5W3E4.js";import{a as _n}from"./chunk-Q2WW2HF4.js";import{a as En,b as Dn,c as On,d as Nn,f as Ln}from"./chunk-DWADWDMU.js";import{a as Fn,b as Hn}from"./chunk-NO2HOK4B.js";import{a as Bn}from"./chunk-VXDM7JAT.js";import{b as jn,c as Un}from"./chunk-M6HJDSLS.js";import{a as Ve,c as _e}from"./chunk-2GIDVZ4H.js";import{q as Mn,t as Rn,v as we,w as Pn}from"./chunk-VOS2IW4V.js";import{a as Pe,b as Ye,f as kt}from"./chunk-72SZI2UW.js";import{a as be,b as xt}from"./chunk-FCPTN6NF.js";import{c as In,d as Sn}from"./chunk-QOYAX2FT.js";import{e as pe}from"./chunk-DSYKYZMT.js";import{d as vn,e as oe,f as Cn,g as An,h as Tt,s as $n,z as fo}from"./chunk-N5NPJ6DJ.js";Pn();kt();var ds="session-continuity",us={continues:Pe("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:Pe("Does the new request refer to something stated earlier in the conversation?")};function ls(s){let e=(s.recentRequests??[]).filter(Boolean);return{newRequest:At(s.message,1200),previousRequest:s.previousMessage?At(s.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>At(t,400))}:{},minutesSinceLastTurn:s.minutesSinceLastTurn,turnsSoFar:s.turnCount,currentContextTokens:s.lastTurnContextTokens,agent:s.agentId,channel:s.channel}}function gs(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 At(s,e){let t=String(s??"");return t.length>e?t.slice(0,e):t}import{spawn as yo,execFile as bo}from"node:child_process";import{createHash as wo,randomBytes as xo}from"node:crypto";import{createInterface as To}from"node:readline";import{promisify as ko}from"node:util";var Io=ko(bo),ie=class extends Error{constructor(t,n=!1){super(t);this.standalone=n}},$t=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=Io("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 ie("Warm servers require OpenCode v2; using the CLI path");if(e.signal?.aborted)throw new Error("task cancelled by operator");let r=wo("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 ie("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 p=[...this.entries].find(([,y])=>!y.busy);if(!p)throw new ie("Warm server capacity reached",!0);this.close(p[1]),this.entries.delete(p[0])}let d={...e.env,OPENCODE_SERVER_USERNAME:"opencode",OPENCODE_SERVER_PASSWORD:xo(32).toString("hex")},l=yo("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((p,y)=>{let b=To({input:l.stdout}),x=()=>k(new ie("OpenCode server failed before dispatch",!0)),w=()=>k(new Error("task cancelled by operator")),I=setTimeout(x,15e3),k=_=>{clearTimeout(I),l.removeListener("exit",x),l.removeListener("error",x),e.signal?.removeEventListener("abort",w),b.close(),l.stdout.resume(),_?y(_):p()};l.once("exit",x),l.once("error",x),e.signal?.addEventListener("abort",w,{once:!0}),b.on("line",_=>{try{let A=new URL(JSON.parse(_).url);if(A.protocol!=="http:"||A.hostname!=="127.0.0.1"||!A.port||A.username||A.password)return;u.url=A.origin,k()}catch{}}),e.signal?.aborted&&w()})}catch(p){throw this.close(o),this.entries.get(e.key)===o&&this.entries.delete(e.key),p}}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()))}}}},ps=new $t;import{execa as ot}from"execa";import{spawn as So}from"node:child_process";import{createHash as vo}from"node:crypto";import{createInterface as Co}from"node:readline";var ae=class extends Error{},Ao=s=>So("codex",["app-server",...s.args],{cwd:s.cwd,env:s.env,stdio:["pipe","pipe","pipe"]}),Mt=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(),Co({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()}},Rt=class{constructor(e=Ao,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=vo("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([w],[I])=>w.localeCompare(I))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new ae("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 w=[...this.entries].find(([,I])=>!I.connection.busy);if(!w)throw new ae("Codex warm process capacity reached");w[1].connection.close(),this.entries.delete(w[0])}try{r={fingerprint:n,connection:new Mt(e,this.launchProcess)}}catch{throw new ae("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,p=!1,y=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",y,{once:!0});let b=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 w={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",{...w,...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 k=new Promise((_,A)=>{i.failTurn=A,i.notify=(v,R)=>{if(R?.threadId!==l)return;let N=R.item,M={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...R,type:v.replace("/","."),...N?{item:{...N,type:M[N.type]||N.type}}:{}}),v==="item/completed"&&N?.type==="agentMessage"&&N.phase==="final_answer"&&(d=N.text),v==="item/agentMessage/delta"&&(p||(p=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=R.delta,e.onDelta?.(R.delta,c)),v==="thread/tokenUsage/updated"){let O=R.tokenUsage.last,F=O.cachedInputTokens||0;u={inputTokens:(u?.inputTokens||0)+Math.max(0,(O.inputTokens||0)-F),outputTokens:(u?.outputTokens||0)+(O.outputTokens||0),cacheReadTokens:(u?.cacheReadTokens||0)+F,cacheCreateTokens:(u?.cacheCreateTokens||0)+(O.cacheWriteInputTokens||0)}}v==="turn/completed"&&(R.turn.status==="completed"?_():A(new Error(R.turn.error?.message||`Codex turn ${R.turn.status}`)))}});return k.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:l,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await k,{content:d??c,codexSessionId:l,billedModel:e.model,usage:u,duration:Date.now()-t}}catch(w){if(i.close(),!a&&!e.signal?.aborted)throw new ae(w.message);return{content:c,codexSessionId:l,usage:u,error:w.message,duration:Date.now()-t}}finally{clearTimeout(x),clearTimeout(b),e.signal?.removeEventListener("abort",y),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())}}},hs=new Rt;import{execFile as Bo}from"child_process";import{StringDecoder as Oe}from"string_decoder";import{mkdtempSync as $s,readFileSync as Ms,rmSync as Rs}from"fs";import{join as st}from"path";import{tmpdir as Ps}from"os";function et(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 tt(s){return s.fix?`${s.message} \u2014 ${s.fix}`:s.message}var ms=null;function nt(){return ms}function ic(s){ms=s}function Ee(s){return`${s.agentId}:${s.channel}:${s.chatId}`}var xe=class extends Error{constructor(t,n,r){super(t);this.scope=n;this.cap=r;this.name="RegistryCapExceeded"}},fs=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=Ee(e),r=this.handles.get(n);if(r&&r.state()!=="dead")return r.claim?.(),r;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 xe(`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 xe(`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=Ee(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=Ee(e),n=this.handles.get(t);return n!=null&&n.state()!=="dead"}async kill(e,t="operator"){let n=Ee(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=Ee(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 $o}from"child_process";import{existsSync as Mo,readFileSync as Ro}from"fs";import{resolve as Po}from"path";function _o(s){let e=Po(s,"CLAUDE.md");if(!Mo(e))return null;try{let t=Ro(e,"utf8");return Ln(t)}catch{return null}}var Eo=20*60*1e3,Do=5e3,De=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}};function Oo(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 ys=class{constructor(e={}){this.opts=e}spawn(e,t){return new Pt(e,t,this.opts)}},Pt=class{constructor(e,t,n){this.key=e;this.spawnOpts=t;this.factoryOpts=n;let r=n.binary??"claude",o=this.buildArgs(t),i=n.log??(()=>{});this.child=$o(r,o,{cwd:t.workspace,env:_e(Oo({...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:_o(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??Eo,c=o+a,d=()=>(this.kill(`turn deadline (${Math.round(a/6e4)}m)`),new De(a));try{for(;;){let l=c-Date.now();if(l<=0)throw d();let u=await this.nextEvent(l);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)},Do);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"}}};Tt();import{resolve as bs,join as ws}from"path";xt();var No=4e3;function xs(s){try{let e=ws(bs(s.root),".agentx","db.sqlite"),t=It({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let n=be(),r=s.input.command?s.input.command.slice(0,No):s.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
|
|
@@ -27,7 +27,7 @@ ${s}`}function Wo(s,e,t,n,r){let o=["run","--format","json","--thinking"],i=t||s
|
|
|
27
27
|
`,u)}};A.stdout?.on("data",g=>{M+=F.write(g);let T=M.split(`
|
|
28
28
|
`);M=T.pop()||"";for(let E of T)H(E)}),A.stderr?.on("data",g=>{O+=D.write(g)});let C=await A;if(i&&i.removeEventListener("abort",N),M+=F.end(),M.trim()&&H(M),O+=D.end(),v)return{content:"",error:R||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:y};if(C.exitCode!==0||b){let g=C,T;return g.timedOut?T=`OpenCode timed out after ${Math.round(k/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:b?T=b:g.code==="ENOENT"||/ENOENT|spawn opencode/i.test((g.shortMessage||"")+" "+O)?T=vs():T=O.trim()||`OpenCode exited with code ${g.exitCode??"unknown"}`,{content:"",...K(T),duration:Date.now()-c,usage:p,opencodeSessionId:y}}return w=!1,{content:u.trim(),duration:Date.now()-c,usage:p,billedModel:e.model||s.model,opencodeSessionId:y}}catch(k){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let _=/ENOENT|spawn opencode/i.test(k?.message||"")?vs():k?.message;return{content:u,...K(_||"OpenCode failed"),duration:Date.now()-c,usage:p,opencodeSessionId:y}}finally{I?.(),x?.release(w)}}async function ei(s,e,t,n){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=de(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:"",...K(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function ti(s,e,t,n,r,o,i,a,c){let d=Date.now(),l=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),u=new AbortController,p=!1,y=()=>{let w=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{u.abort(new Error(w))}catch{}};a&&(a.aborted?y():a.addEventListener("abort",y,{once:!0}));let b=setTimeout(()=>{p=!0;try{u.abort(new Error(`orchestrator timed out after ${Math.round(l/6e4)}m`))}catch{}},l);b.unref?.();let x=()=>({content:"",...K(`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 w=s.provider||"claude-code",I=n?`${n}
|
|
29
29
|
|
|
30
|
-
${e.message}`:e.message,k=e.context?.sender,_=typeof k=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(k),A=e.context?.channel==="web-chat"&&_?{userId:k,agentId:e.agentId||"acme-public"}:void 0,v=Nn(s),R=Object.keys(v).length>0,N={task:I,cwd:s.workspace,provider:w,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:A,providerOpts:o,abortSignal:u.signal,mcpServers:R?v:void 0};if(r){let{generateStream:H}=await import("./agent-
|
|
30
|
+
${e.message}`:e.message,k=e.context?.sender,_=typeof k=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(k),A=e.context?.channel==="web-chat"&&_?{userId:k,agentId:e.agentId||"acme-public"}:void 0,v=Nn(s),R=Object.keys(v).length>0,N={task:I,cwd:s.workspace,provider:w,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:A,providerOpts:o,abortSignal:u.signal,mcpServers:R?v:void 0};if(r){let{generateStream:H}=await import("./agent-P2UO35ZW.js"),C="",g,T,E,L;for await(let m of H(N)){if(c)try{c(m)}catch{}if(m.type==="text_delta")C+=m.text,r(m.text,C);else if(m.type==="thinking_delta")m.text&&i&&i(m.text);else if(m.type==="generate_result"){if(m.result.content&&m.result.content!==C){let X=m.result.content.slice(C.length);X?(C=m.result.content,r(X,C)):C=m.result.content}g=m.result.tokensUsed,m.result.inputTokens!=null&&(T=m.result.inputTokens),m.result.outputTokens!=null&&(E=m.result.outputTokens)}else if(m.type==="done"){if(m.result.content&&m.result.content!==C){let X=m.result.content.slice(C.length);X?(C=m.result.content,r(X,C)):C=m.result.content}m.result.tokensUsed!=null&&(g=m.result.tokensUsed)}else m.type==="error"&&(L=m.error)}return L&&!C?p?x():L==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...K(`Orchestrator error: ${L}`),duration:Date.now()-d}:((T===void 0||E===void 0)&&g&&(T=Math.round(g*.7),E=g-T),{content:C||"Done.",tokensUsed:g,usage:T!==void 0||E!==void 0?{inputTokens:T||0,outputTokens:E||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:M}=await import("./agent-P2UO35ZW.js"),O=await M(N),F=O.inputTokens,D=O.outputTokens;if((F===void 0||D===void 0)&&O.tokensUsed){let H=O.tokensUsed;F=Math.round(H*.7),D=H-F}return{content:O.content||"Done.",tokensUsed:O.tokensUsed,usage:F!==void 0||D!==void 0?{inputTokens:F||0,outputTokens:D||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(w){return p?x():w?.message==="cancelled"||a?.aborted||u.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...K(`Orchestrator error: ${w.message}`),duration:Date.now()-d}}finally{clearTimeout(b),a&&a.removeEventListener("abort",y)}}async function ni(s,e,t,n,r,o,i){let a=nt();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 p,y=!1;try{let C=a.list().length;p=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}),y=a.list().length>C}catch(C){return C instanceof xe,null}y&&Lt(e.agentId,s,e.model,n,"persistent");let b=de(s,e,t),x="",w,I,k,_,A,v,R,N="",M="",O=C=>{if(!i||!C)return;let g;if(M&&C.startsWith(M)?g=C.slice(M.length):g=N&&!N.endsWith(`
|
|
31
31
|
`)?`
|
|
32
32
|
|
|
33
33
|
${C}`:C,M=C,!!g){N+=g;try{i(g,N)}catch{}}},F=!1,D=()=>{F=!0,a.kill(u,"operator-cancel").catch(()=>{})};o&&(o.aborted?D():o.addEventListener("abort",D,{once:!0}));let H=!1;try{let C=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4);for await(let g of p.runTurn({message:b,taskId:e.taskId??"unknown",deadlineMs:C})){if(H=!0,r)try{r(g.raw)}catch{}if(g.type==="assistant"){let T=g.raw.message?.content??[];for(let L of T)L.type==="text"&&typeof L.text=="string"?(x=L.text,O(L.text)):L.type==="tool_use"&&(M="");let E=g.raw.message?.usage;if(E){let L=(E.input_tokens||0)+(E.cache_read_input_tokens||0)+(E.cache_creation_input_tokens||0);L>0&&(_=L)}}if(g.type==="result"){let T=g.raw;if(T.is_error){let E=K(typeof T.result=="string"?T.result:"claude error");w=E.error,I=E.errorKind}else typeof T.result=="string"&&T.result.length>0&&(x=T.result,N||O(T.result));typeof T.session_id=="string"&&(R=T.session_id),T.usage&&(k={inputTokens:T.usage.input_tokens||0,outputTokens:T.usage.output_tokens||0,cacheReadTokens:T.usage.cache_read_input_tokens||0,cacheCreateTokens:T.usage.cache_creation_input_tokens||0}),typeof T.num_turns=="number"&&(A=T.num_turns),typeof T.message?.model=="string"?v=T.message.model:typeof T.model=="string"&&(v=T.model)}}}catch(C){if(F)w="task cancelled by operator",I="cancelled";else if(H)if(C instanceof De){let g=K(`Claude Code timed out after ${Math.round(C.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||e.agentId}" if tasks need longer.`);w=g.error,I=g.errorKind}else{let g=K(`persistent claude process error: ${C?.message||String(C)}`);w=g.error,I=g.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${C?.message||C}); falling back to spawn-per-task`),a.release(u,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",D),null}finally{o&&o.removeEventListener("abort",D)}return F&&!w&&(w="task cancelled by operator",I="cancelled"),{content:F?"":x,error:w,errorKind:I,duration:Date.now()-c,usage:k,contextTokens:_,numTurns:A,billedModel:v,claudeSessionId:R}}function js(s){return oe(s.autonomy)?s.taskId?ks(s.autonomy,s.agentId,s.taskId):{error:`autonomy "${s.autonomy}" requires a task id to enforce`}:{args:[]}}async function si(s,e,t,n,r,o,i){let a=e.autonomy,c=Is(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:`${An(a)}
|
|
@@ -127,7 +127,7 @@ Agent: ${t.slice(0,1e3)}`}],{model:$i,maxTokens:512})).content.trim().match(/\[[
|
|
|
127
127
|
\u2192 ${i}(${a})
|
|
128
128
|
`}return r}if(n==="user"&&t.message?.content){let r="";for(let o of t.message.content)if(o.type==="tool_result"){let i=Array.isArray(o.content)?o.content.map(c=>typeof c?.text=="string"?c.text:"").join(""):typeof o.content=="string"?o.content:"",a=o.is_error?"\u2190 [error] ":"\u2190 ";r+=`${a}${Be(i,800)}
|
|
129
129
|
`}return r}return n==="result"?`\xB7 done${t.duration_ms?` (${Math.round(t.duration_ms/1e3)}s)`:""}
|
|
130
|
-
`:""}}var Jr=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new Gn;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;workflowAutoRunner;messageQueue;voiceClaims=new Set;classifier;graphStore;handoverStore=new qn;activeSouls=new Map;taskOutputs=new Map;taskAborts=new Map;runningContexts=new Map;runReleases=new Map;lastSummaries=new Map;sparklineCache=new Map;referencesCache=new Map;log;constructor(e,t=console.error.bind(console,"[agents]")){if(this.log=t,this.config=e,this.providers=e.providers,this.sessions=new at(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens}),this.wikiHub=new Bn(void 0,void 0,"unified"),this.memoryStore=new Kn,this.patternStore=new ut,this.rateLimiter=new ct,this.tokenTracker=new Ce,this.messageQueue=new dt,hr({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),e.graph?.enabled){this.graphStore=new jn({baseDir:B(process.cwd(),e.graph.baseDir),log:(...r)=>t("[graph]",...r)});let n=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new Un({store:this.graphStore,daemonUrl:e.dashboard.daemonUrl,token:e.dashboard.token,draftAgent:n,autoApproveStructure:e.graph.autoApproveStructure,autoApproveConfidence:e.graph.autoApproveConfidence,classifierModel:e.graph.classifierModel,log:(...r)=>t("[classifier]",...r)})}for(let[n,r]of Object.entries(e.agents))this.agents.set(n,{id:n,def:r,activeTasks:0,totalTasks:0,errors:0,runningTasks:[]})}setLandscape(e){this.landscape=e}setMeshFallback(e){this.meshFallback=e}setWorkflowAutoRunner(e){this.workflowAutoRunner=e}setProviders(e){this.providers=e}setConfig(e){this.config=e}buildHandoverNote(e,t,n){let r=this.handoverStore.get(t,n);if(!r||r.toAgent!==e)return;let o=this.handoverStore.consumeSummary(t,n);if(!(!o&&r.summaryConsumedAt))return{fromAgent:r.fromAgent,summary:o||r.summary,at:r.createdAt}}getAgent(e){return this.agents.get(e)?.def}findByMention(e,t={}){let n=e.toLowerCase(),r,o=0;for(let[i,a]of this.agents)for(let c of a.def.mentions){if(t.atMentionsOnly&&!c.startsWith("@"))continue;let d=c.toLowerCase();n.includes(d)&&d.length>o&&(r=i,o=d.length)}return r}findAllMentioned(e){let t=e.toLowerCase(),n=[];for(let[r,o]of this.agents)for(let i of o.def.mentions)if(t.includes(i.toLowerCase())){n.push(r);break}return n}getWikiHub(){return this.wikiHub}getGraphStore(){return this.graphStore}getSessionStore(){return this.sessions}async maybeRotateForContinuity(e,t,n,r,o){let i=null,a=null,c=[];try{let p=this.sessions.getSession(e.agentId,n,r);i=Ks(p.messages,e.message??""),c=Gs(p.messages,e.message??"",this.config.session.continuityStateTurns),p.updatedAt&&(a=Math.round((Date.now()-Date.parse(p.updatedAt))/6e4))}catch{}let d={message:e.message??"",previousMessage:i,recentRequests:c,minutesSinceLastTurn:a,turnCount:this.sessions.getTurnCount(e.agentId,n,r),lastTurnContextTokens:this.sessions.getLastTurnContextTokens(e.agentId,n,r)||null,agentId:e.agentId,channel:n},l=await we(ds,ls(d),us,{incumbent:{continues:"yes",needsHistory:"yes"},links:[{kind:"session",id:`${e.agentId}:${n}:${r}`}],features:{agent:e.agentId,channel:n}});return!l||l.mode!=="active"||!gs(l.answers,{mechanicalRotation:!1})?!1:(this.log(`[${e.agentId}] continuity rotation for ${n}:${r} (new subject)`),this.captureRotationMemoAsync(e.agentId,t.def,o,n,r,"continuity"),this.sessions.clearClaudeSessionId(e.agentId,n,r),ee().emit("session:rotated",{agentId:e.agentId,channel:n,chatId:r,reason:"continuity",at:new Date().toISOString()}),!0)}async captureRotationMemoAsync(e,t,n,r,o,i){try{let{extractRotationMemo:a}=await import("./rotation-memo-5MTSJ4FH.js"),c=await a(t,n);if(!c.memo){this.log(`[${e}] rotation memo skipped (${i}, ${c.reason}, ${c.durationMs}ms)`);return}let{storeRotationMemo:d}=await import("./rotation-memo-store-
|
|
130
|
+
`:""}}var Jr=class{agents=new Map;config;providers={};sessions;wikiHub;memoryStore;agentMemory=new Gn;patternStore;rateLimiter;tokenTracker;landscape;meshFallback;workflowAutoRunner;messageQueue;voiceClaims=new Set;classifier;graphStore;handoverStore=new qn;activeSouls=new Map;taskOutputs=new Map;taskAborts=new Map;runningContexts=new Map;runReleases=new Map;lastSummaries=new Map;sparklineCache=new Map;referencesCache=new Map;log;constructor(e,t=console.error.bind(console,"[agents]")){if(this.log=t,this.config=e,this.providers=e.providers,this.sessions=new at(process.cwd(),{staleMinutes:e.session.staleMinutes,maxTurnsPerSession:e.session.maxTurnsPerSession,tierTwoThresholdTokens:e.session.tierTwoThresholdTokens}),this.wikiHub=new Bn(void 0,void 0,"unified"),this.memoryStore=new Kn,this.patternStore=new ut,this.rateLimiter=new ct,this.tokenTracker=new Ce,this.messageQueue=new dt,hr({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),e.graph?.enabled){this.graphStore=new jn({baseDir:B(process.cwd(),e.graph.baseDir),log:(...r)=>t("[graph]",...r)});let n=e.graph.draftAgent||e.dashboard?.draftAgent;this.classifier=new Un({store:this.graphStore,daemonUrl:e.dashboard.daemonUrl,token:e.dashboard.token,draftAgent:n,autoApproveStructure:e.graph.autoApproveStructure,autoApproveConfidence:e.graph.autoApproveConfidence,classifierModel:e.graph.classifierModel,log:(...r)=>t("[classifier]",...r)})}for(let[n,r]of Object.entries(e.agents))this.agents.set(n,{id:n,def:r,activeTasks:0,totalTasks:0,errors:0,runningTasks:[]})}setLandscape(e){this.landscape=e}setMeshFallback(e){this.meshFallback=e}setWorkflowAutoRunner(e){this.workflowAutoRunner=e}setProviders(e){this.providers=e}setConfig(e){this.config=e}buildHandoverNote(e,t,n){let r=this.handoverStore.get(t,n);if(!r||r.toAgent!==e)return;let o=this.handoverStore.consumeSummary(t,n);if(!(!o&&r.summaryConsumedAt))return{fromAgent:r.fromAgent,summary:o||r.summary,at:r.createdAt}}getAgent(e){return this.agents.get(e)?.def}findByMention(e,t={}){let n=e.toLowerCase(),r,o=0;for(let[i,a]of this.agents)for(let c of a.def.mentions){if(t.atMentionsOnly&&!c.startsWith("@"))continue;let d=c.toLowerCase();n.includes(d)&&d.length>o&&(r=i,o=d.length)}return r}findAllMentioned(e){let t=e.toLowerCase(),n=[];for(let[r,o]of this.agents)for(let i of o.def.mentions)if(t.includes(i.toLowerCase())){n.push(r);break}return n}getWikiHub(){return this.wikiHub}getGraphStore(){return this.graphStore}getSessionStore(){return this.sessions}async maybeRotateForContinuity(e,t,n,r,o){let i=null,a=null,c=[];try{let p=this.sessions.getSession(e.agentId,n,r);i=Ks(p.messages,e.message??""),c=Gs(p.messages,e.message??"",this.config.session.continuityStateTurns),p.updatedAt&&(a=Math.round((Date.now()-Date.parse(p.updatedAt))/6e4))}catch{}let d={message:e.message??"",previousMessage:i,recentRequests:c,minutesSinceLastTurn:a,turnCount:this.sessions.getTurnCount(e.agentId,n,r),lastTurnContextTokens:this.sessions.getLastTurnContextTokens(e.agentId,n,r)||null,agentId:e.agentId,channel:n},l=await we(ds,ls(d),us,{incumbent:{continues:"yes",needsHistory:"yes"},links:[{kind:"session",id:`${e.agentId}:${n}:${r}`}],features:{agent:e.agentId,channel:n}});return!l||l.mode!=="active"||!gs(l.answers,{mechanicalRotation:!1})?!1:(this.log(`[${e.agentId}] continuity rotation for ${n}:${r} (new subject)`),this.captureRotationMemoAsync(e.agentId,t.def,o,n,r,"continuity"),this.sessions.clearClaudeSessionId(e.agentId,n,r),ee().emit("session:rotated",{agentId:e.agentId,channel:n,chatId:r,reason:"continuity",at:new Date().toISOString()}),!0)}async captureRotationMemoAsync(e,t,n,r,o,i){try{let{extractRotationMemo:a}=await import("./rotation-memo-5MTSJ4FH.js"),c=await a(t,n);if(!c.memo){this.log(`[${e}] rotation memo skipped (${i}, ${c.reason}, ${c.durationMs}ms)`);return}let{storeRotationMemo:d}=await import("./rotation-memo-store-A4YW6FSK.js"),l=d(this.memoryStore,this.sessions,{wikiDir:this.wikiHub.getBaseDir(),agentId:e,channel:r,chatId:o,reason:i,memo:c.memo});l.error&&this.log(`[${e}] memo claims not proposed: ${l.error}`),this.log(`[${e}] rotation memo captured (${i}, ${c.durationMs}ms, ${c.memo.length} chars, ${l.proposals} claim(s) proposed to the wiki)`)}catch(a){this.log(`rotation memo error: ${a?.message||a}`)}}buildPeerList(e,t){let n=[];for(let[r,o]of this.agents)r!==e&&n.push({name:o.def.name,handle:this.getChannelHandle(r,t),role:o.def.systemPrompt?.split(`
|
|
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(a){i={content:"",error:a?.message??String(a)}}if(e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i),e.intentRef)try{let a=i.error?Ze(i.error)?"queued":/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";zn().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:a,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(a){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${a?.message??a}`)}return i}async executeInternal(e,t,n,r){let o=oe(e.autonomy),i=o?null:lr().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 h=await i;if(h.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${h.sessionId}`),{content:h.text,viaAttachedSession:h.sessionId};this.log(`[${e.agentId}] attached session did not take it (${h.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 h=this.meshFallback.directory().find(f=>f.healthy&&f.skills.some(S=>S.id===e.agentId));if(h){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${h.peer}"`);try{let f=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(h.peer,e.message,e.agentId,{timeoutMs:f}),viaMesh:h.peer}}catch(f){return this.log(`[${e.agentId}] mesh fallback to "${h.peer}" failed: ${f?.message??f}`),{content:"",error:`mesh fallback failed: ${f?.message??f}`}}}}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 h=Date.now(),f=25*6e4,S=500;for(;a.activeTasks>=a.def.maxConcurrent;){if(Date.now()-h>f)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(f/6e4)}m`};await new Promise(P=>setTimeout(P,S))}}else if(c==="voice"){let h=Date.now(),f=25*6e4,S=`${e.agentId}\0${d}`;for(;this.messageQueue.isBusy(e.agentId,c,d)||this.voiceClaims.has(S);){if(Date.now()-h>f)return{content:"",error:`Agent "${e.agentId}" busy \u2014 voice wait timed out after ${Math.round(f/6e4)}m`};await new Promise(P=>setTimeout(P,500))}l=S,this.voiceClaims.add(S)}else{let h=a.def.queueMode||"collect",f=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(f==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(f){let S=this.messageQueue.pendingCount(e.agentId,c,d);return this.log(`[${e.agentId}] busy, message queued (mode: ${f}, pending: ${S}) behind=${a.runningTasks.map(P=>P.id).join(",")||"-"} chat=${c}:${d} at=${new Date().toISOString()}`),{content:"",error:Jn(f,S)}}}let u=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(h,f)=>{this.log(`[${e.agentId}] ${h} \u2014 queued, resumes in ~${Math.max(1,Math.round(f/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 h=nr(e.queuedAt);h&&(e.message=`${h}
|
|
132
132
|
${e.message}`),e.queuedAt=void 0}a.activeTasks++,a.totalTasks++,a.lastActive=new Date;let p={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(p),e.runningTaskId=p.id,this.runningContexts.set(p.id,e.context??{}),e.onStart)try{e.onStart(p.id)}catch{}let y=new AbortController;this.taskAborts.set(p.id,{agentId:e.agentId,channel:p.channel,chatId:typeof p.chatId=="string"?p.chatId:"",originalMessage:e.message||"",controller:y});let b={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(p.id,b);let x=h=>{if(h){b.buffer+=h,b.buffer.length>Wr&&(b.buffer=b.buffer.slice(b.buffer.length-Wr));for(let f of b.subscribers)try{f(h)}catch{}}},w=be();e.taskId=w;let I=new Map,k;if(t){let h=Ga();k=f=>{let S=h(f);if(S&&x(S),Gr(w,e.agentId,f),Kr(I,f),r)try{r(f)}catch{}}}else k=h=>{if(Gr(w,e.agentId,h),Kr(I,h),r)try{r(h)}catch{}};let _=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,A=_?setTimeout(()=>y.abort(new Error(`timed out after ${Math.round(_/1e3)}s`)),_):void 0;A?.unref?.();let v=(a.def.preSpawnTimeoutSec??Ha)*1e3,R=setTimeout(()=>{y.abort(new Error(`timed out before spawn after ${Math.round(v/1e3)}s in step "${p.step??"start"}"`))},v);R.unref?.();let N=()=>{R&&clearTimeout(R),R=void 0},M=()=>`task=${p.id} chat=${c}:${d} at=${new Date().toISOString()}`,O;y.signal.addEventListener("abort",()=>{let h=ht(y.signal).message;/^timed out/.test(h)&&(O=p.step??"start"),this.log(`[${e.agentId}] task ${p.id} aborted in step "${p.step??"start"}" \u2014 ${h} ${M()}`)},{once:!0});let F=h=>{p.step=h,this.log(`[${e.agentId}] step ${h} ${M()}`)},D=(h,f,S=0)=>y.signal.aborted?Promise.reject(ht(y.signal)):(F(h),(h==="agent"||h==="workflow-auto-run")&&N(),Ur(f(),y.signal,S)),H=!1,C=h=>{if(H)return;H=!0,this.runReleases.delete(p.id),A&&clearTimeout(A),N(),a.activeTasks--;let f=a.runningTasks.findIndex(S=>S.id===p.id);f!==-1&&a.runningTasks.splice(f,1),this.runningContexts.delete(p.id),this.taskAborts.delete(p.id),b.done=!0,b.endedAt=new Date;for(let S of b.subscribers)try{S(`
|
|
133
133
|
[task finished]
|
|
@@ -149,4 +149,4 @@ ${$}`),f+=$.length}catch{}}}let lo=ft.length>0?ft.join(`
|
|
|
149
149
|
|
|
150
150
|
Agent: ${$.content}`,meta:Ua(Y,e.context)})}catch{}Hn(e.agentId,e.message,$.content,{channel:g,chatId:m,sender:X},this.memoryStore).catch(()=>{}),ir(e.agentId,e.message,$.content,{channel:g,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let G=$.billedModel||e.model||a.def.model,re=e.context?.channel,Xe=re&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${re}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,$.duration||0,$.usage,e.message.length,$.content.length,!1,G,re,Xe),this.log(`[${e.agentId}] completed in ${$.duration}ms`+($.tokensUsed?` (${$.tokensUsed} tokens)`:"")+` ${M()}`)}return $}catch(h){a.errors++,this.log(`[${e.agentId}] unexpected error: ${h.message}`);let f=et(h.message);return le={content:"",error:tt(f),errorKind:f.kind},le}finally{kn.stop(),C(le)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;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=B(process.cwd(),Ae,this.safe(e.agentId),t);V(n)||Da(n,{recursive:!0});let r=B(n,`${this.safe(e.id)}.json`);Na(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=B(process.cwd(),Ae,this.safe(e));if(!V(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 p=B(a,u);if(V(p))try{for(let y of ne(p)){if(!y.endsWith(".json"))continue;let b=y.split("-")[0],x=parseInt(b,10);if(!Number.isFinite(x)||x<i||x>n)continue;let w=Math.floor((n-x)/36e5),I=t-1-w;I>=0&&I<t&&o[I]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:n}),o}hydrateLastSummariesFromDisk(){let e=B(process.cwd(),Ae);if(!V(e))return 0;let t=0;for(let n of ne(e)){let r=B(e,n),o;try{o=ne(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=B(r,i),c;try{c=ne(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let l=JSON.parse(Ue(B(a,d),"utf-8")),u=(l.responseText||l.error||"").trim();if(!u)continue;let p=u.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(l.agentId,{text:p,at:new Date(l.endedAt),ok:l.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=ja){let t=B(process.cwd(),Ae);if(!V(t))return 0;let n=Date.now()-e*24*60*60*1e3,r=0;for(let o of ne(t)){let i=B(t,o),a;try{a=ne(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=n))try{Oa(B(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let n=B(process.cwd(),Ae,this.safe(e));if(!V(n))return[];let r=ne(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=B(n,i),c;try{c=ne(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(Ue(B(a,d),"utf-8")),{transcript:u,responseText:p,...y}=l;o.push(y)}catch{}}}return o}getTaskRecord(e,t){let n=B(process.cwd(),Ae,this.safe(e));if(!V(n))return null;let r=this.safe(t),o=ne(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=B(n,i,`${r}.json`);if(V(a))try{return JSON.parse(Ue(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,n){let r=rs();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||n.errorKind==="cancelled"||Ze(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}}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 p=this.messageQueue.pendingCount(i,a,c),y=!1;if(r.replace){let b=r.reason||`replaced by follow-up from ${n}`;try{o.controller.abort(new Error(b))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${b}`),y=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${p}${u?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:y,edited:u,pending:p}}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=p=>{l||(l=!0,d(p))};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:p=>u({ok:!0,agentId:e,channel:a,chatId:c,taskId:p,queued:!1})}).then(p=>{Ze(p.error)?u({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):p.error?u({ok:!1,status:500,error:p.error||"run did not start"}):u({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:p.viaAttachedSession?"attached":"other"})}).catch(p=>u({ok:!1,status:500,error:p?.message??String(p)}))})}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 Ja(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{ps as a,hs as b,ic as c,fs as d,_o as e,ys as f,xs as g,bc as h,kc as i,Ic as j,Qo as k,Fs as l,Zo as m,ei as n,ti as o,Us as p,at as q,ct as r,Vc as s,Wt as t,ee as u,ar as v,Ei as w,Li as x,ur as y,md as z,lr as A,je as B,Ta as C,ka as D,Ia as E,Sa as F,va as G,zt as H,Qu as I,zu as J,Ua as K,Ba as L,Wa as M,tn as N,qr as O,Kr as P,Ka as Q,Gr as R,Jr as S,Ja as T};
|
|
152
|
-
//# sourceMappingURL=chunk-
|
|
152
|
+
//# sourceMappingURL=chunk-L2K4N3DA.js.map
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import{a as M,b as R,c as re,d as L,e as _}from"./chunk-4DRNEOOW.js";import{b as X}from"./chunk-64P4QHSZ.js";import{a as Q,b as Z,c as ee,d as te,e as se}from"./chunk-TFVUOC2C.js";import{v as Y,w as he}from"./chunk-VOS2IW4V.js";import{a as V,b as pe}from"./chunk-FX3D7YON.js";import{c as O,d as T}from"./chunk-QOYAX2FT.js";import{o as K,p as de}from"./chunk-SZJMS7K4.js";var A={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},G=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as D,writeFileSync as F,appendFileSync as ue,existsSync as I,mkdirSync as B,renameSync as ge,statSync as ie}from"fs";import{resolve as P,dirname as oe}from"path";import{createHash as fe}from"crypto";var J=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??P(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),B(this.baseDir,{recursive:!0})}schemaPath(){return P(this.baseDir,"schema.json")}nodesPath(){return P(this.baseDir,"nodes.json")}indexPath(){return P(this.baseDir,"index.json")}classificationsPath(){return P(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!I(e))return this.saveSchema(A),this.log("seeded starter schema at",e),A;let t=D(e,"utf-8"),s=M.safeParse(JSON.parse(t));if(!s.success)throw new Error(`Invalid ${e}: ${s.error.issues.map(r=>r.message).join("; ")}`);if((s.data.version??1)<(A.version??2)){let r=e.replace(/\.json$/,`.v${s.data.version??1}.bak.json`);try{F(r,t),this.log(`migrated graph schema v${s.data.version??1} -> v${A.version}; old saved at ${r}`)}catch(a){this.log(`could not back up old schema: ${a?.message??a}`)}this.saveSchema(A);let n=this.nodesPath();if(I(n)){let a=n.replace(/\.json$/,".v1.bak.json");try{F(a,D(n,"utf-8")),this.log(`archived v1 nodes.json -> ${a}`)}catch(i){this.log(`could not back up old nodes: ${i?.message??i}`)}try{let i=ae();this.saveNodes(i)}catch(i){this.log(`could not seed v2 nodes: ${i?.message??i}`)}}return A}return s.data}saveSchema(e){let t=M.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(s=>s.message).join("; ")}`);ne(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!I(e)){let t=ae();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let s=L.safeParse(JSON.parse(t));if(!s.success)throw new Error(`Invalid ${e}: ${s.error.issues.map(r=>r.message).join("; ")}`);return s.data}))}saveNodes(e){let t=L.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(s=>s.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:s,size:r}=ie(e),n=this.parsed.get(e);if(n&&n.mtimeMs===s&&n.size===r)return n.data;let a=t(D(e,"utf-8"));return this.parsed.set(e,{mtimeMs:s,size:r,data:a}),a}writeParsed(e,t){this.parsed.delete(e),ne(e,t);let{mtimeMs:s,size:r}=ie(e);this.parsed.set(e,{mtimeMs:s,size:r,data:t})}validateNode(e,t,s){let r=t.levels.find(i=>i.id===e.level);if(!r)throw new Error(`Unknown level: "${e.level}"`);let n=r.axes.filter(i=>!i.optional).filter(i=>!(i.name in e.axes));if(n.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${n.map(i=>i.name).join(", ")}`);for(let i of r.axes){let o=e.axes[i.name];if(o!=null){if(i.type==="enum"&&i.values&&!i.values.includes(o))throw new Error(`Node ${e.id}: axis ${i.name}="${o}" not in enum ${JSON.stringify(i.values)}`);if(i.type==="ref"){if(!s.some(c=>c.id===o))throw new Error(`Node ${e.id}: axis ${i.name}="${o}" refers to unknown node`);if(i.refLevel){let c=s.find(l=>l.id===o);if(c.level!==i.refLevel)throw new Error(`Node ${e.id}: axis ${i.name} expected level "${i.refLevel}" but got "${c.level}"`)}}}}let a=t.levels.findIndex(i=>i.id===e.level);if(a===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let i=s.find(c=>c.id===e.parentId);if(!i)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let o=t.levels.findIndex(c=>c.id===i.level);if(o<0||o>=a)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${i.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,s,r){let n=[],a=[],i=new Date().toISOString();for(let o=0;o<e.length;o++){let c=e[o],l=this.loadNodes().nodes;if(l.find(m=>m.id===c)){a.push(c);continue}let p=0;for(let m=o-1;m>=0;m--){let b=e[m],W=l.find(k=>k.id===b)||n.find(k=>k.id===b);if(W){p=s.levels.findIndex(k=>k.id===W.level)+1;break}}let u=t[c]??{},d=null;for(let m=p;m<s.levels.length;m++){let b=s.levels[m];if(b.axes.filter(k=>!k.optional).filter(k=>!(k.name in u)).length===0){d=b.id,p=m+1;break}}if(!d&&p<s.levels.length&&(d=s.levels[p].id,p++),!d)throw new Error(`Can't place node ${c} \u2014 no schema level left (cursor=${p}, levels=${s.levels.length})`);let h=null,f=s.levels.findIndex(m=>m.id===d);for(let m=o-1;m>=0;m--){let b=e[m],W=l.find(C=>C.id===b)||n.find(C=>C.id===b);if(!W)continue;let k=s.levels.findIndex(C=>C.id===W.level);if(k>=0&&k<f){h=b;break}}let g={id:c,level:d,parentId:h,axes:u,createdAt:i,createdBy:r};this.addNode(g),n.push(g)}return{added:n,skipped:a}}addNode(e){let t=this.loadSchema(),s=this.loadNodes();if(s.nodes.some(r=>r.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...s.nodes,e]),s.nodes.push(e),this.saveNodes(s),e}appendClassification(e){let t=R.safeParse(e);if(!t.success){let n=t.error.issues.map(a=>`${a.path.join(".")}: ${a.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${n} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let s=JSON.stringify(t.data)+`
|
|
2
|
+
`,r=this.classificationsPath();return I(r)||B(oe(r),{recursive:!0}),ue(r,s),!0}listPendingClassifications(e=200){return this.listByStatus("pending",e)}listAllClassifications(){return this.readAllCollapsed()}listByStatus(e,t=200){return this.readAllCollapsed().filter(r=>r.status===e).slice(0,t)}readAllCollapsed(){let e=this.classificationsPath();if(!I(e))return[];let s=D(e,"utf-8").split(`
|
|
3
|
+
`).filter(Boolean),r=new Map;for(let n of s)try{let a=R.safeParse(JSON.parse(n));if(!a.success)continue;r.set(a.data.msgHash,a.data)}catch{}return Array.from(r.values()).sort((n,a)=>n.ts<a.ts?1:-1)}updateClassificationStatus(e,t){let r=this.readAllCollapsed().find(a=>a.msgHash===e);if(!r)return null;let n={...r,status:t.status,ts:new Date().toISOString()};if(t.reviewer||t.reviewReason){let a=` \xB7 ${t.reviewer?`reviewer=${t.reviewer}`:""}${t.reviewReason?` \xB7 ${t.reviewReason}`:""}`;n.preview=((r.preview||"")+a).slice(0,500)}return this.appendClassification(n),n}readRecentClassifications(e=50){let t=this.classificationsPath();if(!I(t))return[];let r=D(t,"utf-8").split(`
|
|
4
|
+
`).filter(Boolean),n=[];for(let a=r.length-1;a>=0&&n.length<e;a--)try{let i=R.safeParse(JSON.parse(r[a]));i.success&&n.push(i.data)}catch{}return n}fingerprint(e){let s=[e.text.toLowerCase().replace(/\s+/g," ").trim(),e.channel??"",e.sender??""].join("");return fe("sha256").update(s).digest("hex").slice(0,32)}loadIndex(){return structuredClone(this.index())}saveIndex(e){let t=_.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid index: ${t.error.issues.map(s=>s.message).join("; ")}`);this.writeParsed(this.indexPath(),t.data)}index(){let e=this.indexPath();return I(e)?this.readParsed(e,t=>{let s=_.safeParse(JSON.parse(t));if(!s.success)throw new Error(`Invalid ${e}: ${s.error.issues.map(r=>r.message).join("; ")}`);return s.data}):{version:1,entries:{}}}getFingerprint(e){let t=this.index().entries[e];return t&&structuredClone(t)}setFingerprint(e,t){let s=re.safeParse({...t,fingerprint:e,updatedAt:new Date().toISOString()});if(!s.success)throw new Error(`Refusing to save invalid index entry: ${s.error.issues.map(n=>n.message).join("; ")}`);let r=this.index();this.writeParsed(this.indexPath(),{...r,entries:{...r.entries,[e]:s.data}})}updateNodeAxes(e,t){let s=this.loadSchema(),r=this.loadNodes(),n=r.nodes.find(i=>i.id===e);if(!n)throw new Error(`Node not found: ${e}`);let a={...n,axes:t};return this.validateNode(a,s,r.nodes.map(i=>i.id===e?a:i)),r.nodes=r.nodes.map(i=>i.id===e?a:i),this.saveNodes(r),a}deleteNode(e){let t=this.loadNodes(),s=t.nodes.find(n=>n.parentId===e);if(s)throw new Error(`Cannot delete "${e}" \u2014 child node "${s.id}" still points to it`);let r=t.nodes.find(n=>Object.values(n.axes).some(a=>a===e));if(r)throw new Error(`Cannot delete "${e}" \u2014 node "${r.id}" references it via an axis`);t.nodes=t.nodes.filter(n=>n.id!==e),this.saveNodes(t)}approveClassification(e){if(this.getFingerprint(e.msgHash))return;let t=this.loadSchema(),s=new Set(this.loadNodes().nodes.map(r=>r.id));for(let r=0;r<e.path.length;r++){let n=e.path[r];if(s.has(n))continue;let a=t.levels[r]?.id;if(!a)break;let i=e.proposedAxes?.[n]??{},o=r===0?null:e.path[r-1];this.addNode({id:n,level:a,parentId:o,axes:i,createdAt:new Date().toISOString(),createdBy:e.agentId}),s.add(n)}this.setFingerprint(e.msgHash,{path:e.path,leaf:e.leaf}),this.appendClassification({...e,status:"approved",ts:new Date().toISOString()})}rejectClassification(e){this.appendClassification({...e,status:"rejected",ts:new Date().toISOString()})}};function ne(w,e){B(oe(w),{recursive:!0});let t=`${w}.tmp-${process.pid}`;F(t,JSON.stringify(e,null,2)),ge(t,w)}function ae(){let w=new Date().toISOString(),e=[],t=new Set;for(let s of G)t.has(s.category)||(e.push({id:s.category,level:"category",parentId:null,axes:{kind:s.category},createdAt:w,createdBy:"starter"}),t.add(s.category));for(let s of G)e.push({id:s.verb,level:"verb",parentId:s.category,axes:{name:s.verb,...s.description?{description:s.description}:{}},createdAt:w,createdBy:"starter"});return{version:1,nodes:e}}pe();de();import{createHash as me}from"crypto";var H=class{store;daemonUrl;token;draftAgent;autoApprove;autoApproveStructure;classifierModel;classifierProviderName;providerInstance;log;constructor(e){this.store=e.store,this.daemonUrl=e.daemonUrl.replace(/\/+$/,""),this.token=e.token,this.draftAgent=e.draftAgent,this.autoApprove=e.autoApproveConfidence??1,this.autoApproveStructure=e.autoApproveStructure??"extend-leaves",this.classifierModel=e.classifierModel??"claude-haiku-4-5-20251001",this.classifierProviderName=e.classifierProvider??"claude-code",this.log=e.log??console.error.bind(console,"[classifier]")}getProvider(){return this.providerInstance||(this.providerInstance=K(this.classifierProviderName)),this.providerInstance}async classify(e){let t=this.store.fingerprint({text:e.text,channel:e.channel,sender:e.sender}),s=this.store.getFingerprint(t);if(s)return this.store.appendClassification({ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,path:s.path,proposedAxes:{},leaf:s.leaf,source:"cache",status:"approved",preview:e.text.slice(0,200)}),{path:s.path,pathId:U(s.path),pathLabel:q(s.path,this.store.loadNodes().nodes),axes:{},leaf:s.leaf,source:"cache",status:"approved"};let r=this.store.loadSchema(),n=this.store.loadNodes().nodes,a=await this.proposePath(e,r,n).catch(g=>(this.log("LLM proposal failed:",g?.message||g),null));if(!a)return null;let{path:i,proposedAxes:o,confidence:c,leaf:l}=a;if(i.length===0)return null;let v={ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,path:i,proposedAxes:o,leaf:l,source:"llm",status:"pending",confidence:c,preview:e.text.slice(0,200)},p=new Set(n.map(g=>g.id)),u=i.map((g,m)=>p.has(g)?-1:m).filter(g=>g>=0),d=!1;if(this.autoApproveStructure==="any")d=!0;else if(this.autoApproveStructure==="extend-leaves"){let g=u.length===0,m=u.length===1&&u[0]===i.length-1;d=g||m}let h=c!==void 0&&c>=this.autoApprove,f="pending";if(d||h)try{this.commitNewNodes(i,o,r,n,e.sender),this.store.setFingerprint(t,{path:i,leaf:l}),f="approved"}catch(g){this.log("auto-approve failed \u2014 staying pending \xB7",`path=${JSON.stringify(i)}`,`reason=${(g?.message||g).toString().slice(0,200)}`)}return v.status=f,this.store.appendClassification(v),{path:i,pathId:U(i),pathLabel:q(i,this.store.loadNodes().nodes),axes:o,leaf:l,source:"llm",status:f,confidence:c}}async proposePath(e,t,s){let r=s.map(d=>({id:d.id,level:d.level,parentId:d.parentId,axes:d.axes})),n=["You are the intent classifier for AgentX. You answer ONE question:",'"what kind of work does this message describe?" \u2014 verb-level only.',"","IMPORTANT \u2014 what NOT to encode in the path:","- Client / company / project / team names. Those are already on the event"," metadata (project, channel, agentId). Embedding them in the path causes"," duplicate nodes (one per client) for the same verb.","- The specific subject (issue number, file name, person name). Same reason.","- The agent's name or role. Pick the verb the *requester* intended.","","SCHEMA (fixed levels \u2014 pick one node per level):","```json",JSON.stringify(t,null,2),"```","","EXISTING NODES (prefer reusing these; only invent a new node when no","existing one fits):","```json",JSON.stringify(r,null,2),"```","","MESSAGE:","```",e.text.slice(0,2e3),"```",`channel: ${e.channel??"?"}`,`sender: ${e.sender??"?"}`,"","TASK:","1. Classify into 'category' (closed enum): code, ops, support, admin,"," knowledge, social, system. Pick the closest fit.","2. Pick or propose a 'verb' node. Verb ids are dot-namespaced lower-kebab,",' e.g. "review.merge-request", "deploy.staging", "investigate.error",',' "chat.greeting", "fix.bug". Reuse an existing verb when the message is'," the same kind of work as something already classified, even when the"," client / project / subject differs.","","Examples (right vs wrong):",'- "Please review MR #957 on globex/system" \u2192 ["code", "review.merge-request"]',' NOT ["business", "acme", "globex-v2", "review-mr-957-system"]','- "Deploy initech-v2 to staging please" \u2192 ["ops", "deploy.staging"]',' NOT ["business", "acme", "initech-v2", "deploy-initech-v2-to-staging"]','- "Hello Atlas" \u2192 ["support", "chat.greeting"]',"","NODE ID RULES (strict \u2014 invalid ids get dropped):","- lowercase-kebab + dots only: [a-z0-9][a-z0-9._-]*","- no spaces, no uppercase, no Arabic/other non-Latin",'- verb ids should use a "category.specific" or "verb.modifier" shape',"","Return ONE JSON object on one line, no prose, no fences:",' { "path": string[], "proposedAxes": { [nodeId]: { [axisName]: string } }, "leaf": { "input"?: string, "output"?: string }, "confidence": number }',"confidence in [0,1]. Prefer low confidence over guessing."].join(`
|
|
5
|
+
`),a=await this.callProvider(n),i=V(a);if(!i||!Array.isArray(i.path))return null;let o=/^[a-z0-9][a-z0-9._-]*$/,c=new Map,l=i.path.filter(d=>typeof d=="string"&&d.length>0).map(d=>{let h=d.trim(),f=ce(h);return h!==f&&c.set(h,f),f}).filter(d=>o.test(d));if(l.length===0)return null;let v={};if(i.proposedAxes&&typeof i.proposedAxes=="object")for(let[d,h]of Object.entries(i.proposedAxes)){if(!h||typeof h!="object")continue;let f=c.get(d)??ce(d);if(!f)continue;let g={};for(let[m,b]of Object.entries(h))typeof b=="string"&&(g[m]=b);!g.name&&d!==f&&(g.name=d.trim()),v[f]=g}let p={};i.leaf&&typeof i.leaf=="object"&&(typeof i.leaf.input=="string"&&(p.input=i.leaf.input),typeof i.leaf.output=="string"&&(p.output=i.leaf.output));let u=typeof i.confidence=="number"?Math.max(0,Math.min(1,i.confidence)):void 0;return{path:l,proposedAxes:v,confidence:u,leaf:p}}commitNewNodes(e,t,s,r,n){this.store.commitNodesAlongPath(e,t,s,n)}async callProvider(e){let t=this.getProvider(),s=new AbortController,r=setTimeout(()=>s.abort(),3e4);try{return(await t.generate([{role:"system",content:"You are a taxonomy classifier. Respond with a single JSON object on one line. No prose, no code fences."},{role:"user",content:e}],{model:this.classifierModel,maxTokens:800})).content||""}finally{clearTimeout(r)}}};function ce(w){let e=w.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").replace(/-{2,}/g,"-");return e?/^[a-z0-9]/.test(e)?e:`n-${e}`.replace(/[-_]+$/,""):""}function U(w){return me("sha1").update(w.join("")).digest("hex").slice(0,16)}function q(w,e){return w.map(t=>{let s=e.find(n=>n.id===t);return s&&(s.axes?.name||s.axes?.what)||t}).join(" \u203A ")}function z(w,e){if(w.length===0||e.length===0)return 0;let t=0;for(let r=0;r<Math.min(w.length,e.length)&&w[r]===e[r];r++)t++;if(t===0)return 0;let s=Math.max(w.length,e.length);return t/s}import{readFileSync as N,writeFileSync as x,appendFileSync as ve,existsSync as $,mkdirSync as j,readdirSync as E,statSync as ye}from"fs";import{resolve as y,join as we,relative as S,dirname as be}from"path";he();var le=class{baseDir;rawDir;log;constructor(e=y(process.cwd(),".agentx/wiki"),t=console.error.bind(console,"[wiki]")){this.baseDir=e,this.rawDir=y(e,"raw/entries"),this.log=t,j(this.rawDir,{recursive:!0}),j(y(e,"raw"),{recursive:!0}),this.ensureSchema()}canRead(e,t){return e.access==="public"?!0:t?!!(e.owner===t||e.access==="shared"&&e.sharedWith?.includes(t)):!1}canWrite(e,t){return e.owner===t}addEntry(e){let t=`${e.date}_${e.id}.md`,s=y(this.rawDir,t),r=["---",`id: ${e.id}`,`date: ${e.date}`,`agent: ${e.agentId}`,`source: ${e.source}`];if(e.sourceContext&&r.push(`context: ${e.sourceContext}`),e.meta)for(let[n,a]of Object.entries(e.meta))r.push(`${n}: ${JSON.stringify(a)}`);return r.push("---","",e.content),x(s,r.join(`
|
|
6
|
+
`)),this.appendLog("ingest",`${e.id} from ${e.agentId} via ${e.source}`),t}listEntries(e){if(!$(this.rawDir))return[];let t=E(this.rawDir).filter(r=>r.endsWith(".md")).sort(),s=[];for(let r of t){let n=N(y(this.rawDir,r),"utf-8"),a=this.parseEntry(n,r);a&&(e?.agentId&&a.agentId!==e.agentId||e?.after&&a.date<e.after||e?.before&&a.date>e.before||s.push(a))}return s}parseEntry(e,t){let s=e.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let r=s[1],n=s[2].trim(),a=c=>r.match(new RegExp(`^${c}:\\s*(.+)$`,"m"))?.[1]?.trim()||"",i=new Set(["id","date","agent","source","context"]),o={};for(let c of r.split(`
|
|
7
|
+
`)){let l=c.match(/^(\w+):\s*(.+)$/);if(!(!l||i.has(l[1])))try{o[l[1]]=JSON.parse(l[2])}catch{o[l[1]]=l[2].trim()}}return{id:a("id")||t.replace(".md",""),date:a("date"),agentId:a("agent"),source:a("source"),sourceContext:a("context")||void 0,content:n,meta:Object.keys(o).length>0?o:void 0}}writeArticle(e,t,s,r){let n=this.readArticle(e);if(n&&!this.canWrite(n.meta,r))return this.log(`Permission denied: "${r}" cannot write "${e}" (owner: ${n.meta.owner})`),!1;t.type&&!X(t.type)&&(this.log(`Dropping invalid article type "${t.type}" for "${e}" \u2014 enum is [person, project, place, concept, event, decision, pattern]`),t={...t,type:void 0});let a=y(this.baseDir,e);n&&this.saveVersion(e,a),j(be(a),{recursive:!0});let i=["---",`title: "${t.title}"`];t.type&&i.push(`type: ${t.type}`),t.related?.length&&i.push(`related: [${t.related.map(c=>`"${c}"`).join(", ")}]`),i.push(`tags: [${(t.tags||[]).map(c=>`"${c}"`).join(", ")}]`,`owner: ${t.owner}`,`access: ${t.access}`),t.sharedWith?.length&&i.push(`shared_with: [${t.sharedWith.map(c=>`"${c}"`).join(", ")}]`),i.push(`created: ${t.created}`,`last_updated: ${t.lastUpdated}`,`sources: [${t.sources.map(c=>`"${c}"`).join(", ")}]`),t.graphPath?.length&&i.push(`graph_path: [${t.graphPath.map(c=>`"${c}"`).join(", ")}]`),i.push("---","",s),x(a,i.join(`
|
|
8
|
+
`));let o=n?"update":"create";return this.appendLog(o,`${t.title} [${(t.tags||[]).slice(0,5).join(", ")}] by ${r} at ${e}`),!0}saveVersion(e,t){try{if(!$(t))return;let s=N(t,"utf-8"),r=new Date().toISOString().replace(/[:.]/g,"-"),n=y(this.baseDir,"_versions",e.replace(/\.md$/,""));j(n,{recursive:!0}),x(y(n,`${r}.md`),s)}catch{}}getVersions(e){let t=y(this.baseDir,"_versions",e.replace(/\.md$/,""));if(!$(t))return[];try{return E(t).filter(s=>s.endsWith(".md")).sort().reverse().map(s=>({timestamp:s.replace(/\.md$/,"").replace(/-/g,(r,n)=>n<19?n===10?"T":n===13||n===16?":":"-":r),path:y(t,s)}))}catch{return[]}}restoreVersion(e,t){let r=this.getVersions(e).find(n=>n.timestamp.startsWith(t));if(!r)return!1;try{let n=N(r.path,"utf-8"),a=y(this.baseDir,e);return this.saveVersion(e,a),x(a,n),this.appendLog("restore",`${e} restored to ${t}`),!0}catch{return!1}}readArticle(e){let t=y(this.baseDir,e);if(!$(t))return null;let s=N(t,"utf-8");return this.parseArticle(s,e)}readArticleAs(e,t){let s=this.readArticle(e);return!s||!this.canRead(s.meta,t)?null:s}parseArticle(e,t){let s=e.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let r=s[1],n=s[2].trim(),a=d=>r.match(new RegExp(`^${d}:\\s*(.+)$`,"m"))?.[1]?.trim().replace(/^"(.*)"$/,"$1")||"",i=d=>{let h=r.match(new RegExp(`^${d}:\\s*\\[(.*)\\]$`,"m"));return h?h[1].split(",").map(f=>f.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[]},o=a("type")||a("kind"),l=new Set(["person","project","place","concept","event","decision","pattern"]).has(o)?o:void 0,v=i("tags").filter((d,h,f)=>d&&f.indexOf(d)===h),p=i("related"),u=i("graph_path");return{meta:{title:a("title"),type:l,related:p.length?p:void 0,tags:v,owner:a("owner"),access:a("access")||"public",sharedWith:i("shared_with"),created:a("created"),lastUpdated:a("last_updated"),sources:i("sources"),graphPath:u.length?u:void 0},content:n,path:t}}listArticles(e){let t=[];return this.walkDir(this.baseDir,s=>{if(!s.endsWith(".md"))return;let r=S(this.baseDir,s);if(r.startsWith("raw/")||r.startsWith("_"))return;let n=this.readArticle(r);n&&this.canRead(n.meta,e)&&t.push(n)}),t}search(e,t,s=10){let r=e.toLowerCase(),n=[];if(this.walkDir(this.baseDir,p=>{if(!p.endsWith(".md"))return;let u=S(this.baseDir,p);if(u.startsWith("raw/")||u.startsWith("_"))return;let d=this.readArticle(u);!d||!this.canRead(d.meta,t)||n.push(d)}),n.length===0)return[];let a=n.map(p=>p.content),i=y(this.baseDir,"_bm25_cache.json"),o=T(a,i),c=O(e,o),l=new Map(c.map(p=>[p.docIndex,p.score]));return n.map((p,u)=>{let d=l.get(u)??0;return p.meta.title.toLowerCase().includes(r)&&(d+=10),p.meta.tags?.some(h=>h.toLowerCase().includes(r))&&(d+=5),{article:p,score:d}}).filter(p=>p.score>0).sort((p,u)=>u.score-p.score).slice(0,s).map(p=>p.article)}async findRelevantReranked(e,t,s=10,r={}){let n=Math.max(s,r.shortlist??Z),a=this.findRelevant(e,t,n);if(a.length<2)return a.slice(0,s);let i=a.map((l,v)=>({id:`c${v}`,title:l.meta.title||`(untitled ${v})`,tags:l.meta.tags,excerpt:l.content})),o=await Y(Q,ee({query:e,candidates:i,excerptChars:r.excerptChars}),te(i),{incumbent:{best:i[0].id},features:{agent:t??"unknown"}});return!o||o.mode!=="active"?a.slice(0,s):se(o.answers,i).ranked.map(l=>a[Number(l.slice(1))]).filter(l=>!!l).slice(0,s)}findRelevant(e,t,s=3,r,n={graph:.6,bm25:.4}){let a=[];if(this.walkDir(this.baseDir,h=>{if(!h.endsWith(".md"))return;let f=S(this.baseDir,h);if(f.startsWith("raw/")||f.startsWith("_"))return;let g=this.readArticle(f);!g||!this.canRead(g.meta,t)||a.push(g)}),a.length===0)return[];let i=a.map(h=>`${h.meta.title} ${(h.meta.tags||[]).join(" ")} ${h.content}`),o=y(this.baseDir,"_bm25_relevance_cache.json"),c=T(i,o),l=O(e,c),v=l.reduce((h,f)=>Math.max(h,f.score),0)||1,p=new Map(l.map(h=>[h.docIndex,h.score/v])),u=!!(r&&r.length>0);return a.map((h,f)=>{let g=p.get(f)??0,m=0;u&&h.meta.graphPath?.length&&(m=z(r,h.meta.graphPath));let b=u?n.graph*m+n.bm25*g:g;return{article:h,score:b}}).filter(h=>h.score>0).sort((h,f)=>f.score-h.score).slice(0,s).map(h=>h.article)}buildContext(e,t=4e3){if(e.length===0)return"";let s=["[Wiki Knowledge]"],r=0;for(let n of e){let a=`
|
|
9
|
+
## ${n.meta.title} [${(n.meta.tags||[]).slice(0,3).join(", ")}]`,i=n.content.length>600?n.content.slice(0,600)+"...":n.content,o=a+`
|
|
10
|
+
`+i;if(r+o.length>t)break;s.push(o),r+=o.length}return s.push(`
|
|
11
|
+
[End Wiki Knowledge]`),s.join(`
|
|
12
|
+
`)}rebuildIndex(){let e=[],t=new Map;this.walkDir(this.baseDir,a=>{if(!a.endsWith(".md"))return;let i=S(this.baseDir,a);if(i.startsWith("raw/")||i.startsWith("_"))return;let o=this.readArticle(i);if(!o)return;let c=o.content.match(/\[\[([^\]]+)\]\]/g)||[];for(let v of c){let p=v.replace(/\[\[|\]\]/g,"");t.set(p,(t.get(p)||0)+1)}let l=[o.meta.title.toLowerCase()];o.meta.tags&&l.push(...o.meta.tags.map(v=>v.toLowerCase())),e.push({path:i,title:o.meta.title,type:o.meta.type,related:o.meta.related,tags:o.meta.tags||[],owner:o.meta.owner,access:o.meta.access,sharedWith:o.meta.sharedWith,aliases:l,backlinks:t.get(o.meta.title)||0,sources:o.meta.sources,lastUpdated:o.meta.lastUpdated})});let s={articles:e,lastRebuilt:new Date().toISOString()};x(y(this.baseDir,"_index.json"),JSON.stringify(s,null,2)),this.writeCatalog(e,s.lastRebuilt);let r=["# Wiki Index","",`Last rebuilt: ${s.lastRebuilt}`,""],n=new Map;for(let a of e){let i=a.access||"public",o=n.get(i)||[];o.push(a),n.set(i,o)}for(let[a,i]of Array.from(n.entries()).sort()){r.push(`## ${a}`,"");for(let o of i.sort((c,l)=>c.title.localeCompare(l.title))){let c=o.type?` [${o.type}]`:"";r.push(`- [${o.title}](${o.path})${c} \u2014 owner: ${o.owner}`)}r.push("")}return x(y(this.baseDir,"WIKI.md"),r.join(`
|
|
13
|
+
`)),this.log(`Index rebuilt: ${e.length} articles`),this.appendLog("rebuild-index",`${e.length} articles indexed`),s}writeCatalog(e,t){let s=["person","project","place","concept","event","decision","pattern","untyped"],r={person:"## People",project:"## Projects",place:"## Places",concept:"## Concepts",event:"## Events",decision:"## Decisions",pattern:"## Patterns",untyped:"## Untyped (needs migration)"},n=new Map;for(let i of e){let o=i.type||"untyped",c=n.get(o)||[];c.push(i),n.set(o,c)}let a=["# Wiki Content Catalog","",`_Last rebuilt: ${t}_`,"","Articles grouped by type. Agentic query walks this file first to pick candidates.",""];for(let i of s){let o=n.get(i);if(!(!o||o.length===0)){a.push(r[i]||`## ${i}`,"");for(let c of o.sort((l,v)=>l.title.localeCompare(v.title))){let l=c.access==="private"?" (private)":c.access==="shared"?" (shared)":"",v=c.related?.length?` \u2192 [[${c.related.slice(0,3).join("]], [[")}]]${c.related.length>3?", \u2026":""}`:"";a.push(`- [${c.title}](${c.path})${l}${v}`)}a.push("")}}x(y(this.baseDir,"_index.md"),a.join(`
|
|
14
|
+
`))}stats(){let e=0,t={},s={},r={};this.walkDir(this.baseDir,a=>{if(!a.endsWith(".md"))return;let i=S(this.baseDir,a);if(i.startsWith("raw/")||i.startsWith("_")||i==="WIKI.md")return;let o=this.readArticle(i);if(o){e++;for(let c of o.meta.tags||[])t[c]=(t[c]||0)+1;s[o.meta.access]=(s[o.meta.access]||0)+1,r[o.meta.owner]=(r[o.meta.owner]||0)+1}});let n=$(this.rawDir)?E(this.rawDir).filter(a=>a.endsWith(".md")).length:0;return{totalArticles:e,totalEntries:n,articlesByType:t,articlesByAccess:s,articlesByOwner:r}}appendLog(e,t){let s=y(this.baseDir,"log.md"),n=`## [${new Date().toISOString().replace("T"," ").slice(0,16)}] ${e} | ${t}
|
|
15
|
+
|
|
16
|
+
`;$(s)||x(s,`# Wiki Log
|
|
17
|
+
|
|
18
|
+
Chronological record of all wiki operations.
|
|
19
|
+
|
|
20
|
+
`),ve(s,n)}getLog(e=20){let t=y(this.baseDir,"log.md");return $(t)?N(t,"utf-8").split(/^## /m).filter(n=>n.startsWith("[")).slice(-e).map(n=>n.trim()):[]}ensureSchema(){let e=y(this.baseDir,"_schema.md");if($(e))return;x(e,`# Wiki Schema
|
|
21
|
+
|
|
22
|
+
A personal wiki maintained by LLMs. Karpathy pattern: plain files, aggressive tagging,
|
|
23
|
+
structure emerges from data. The wiki is a compounding artifact.
|
|
24
|
+
|
|
25
|
+
## Structure
|
|
26
|
+
|
|
27
|
+
\`\`\`
|
|
28
|
+
wiki/
|
|
29
|
+
_schema.md # This file
|
|
30
|
+
worldview.md # YOUR mental model \u2014 the LLM reads this during absorb
|
|
31
|
+
raw/entries/ # Immutable raw sources (conversations, imports, anything)
|
|
32
|
+
[LLM-chosen dirs] # Structure emerges from data \u2014 the LLM picks paths
|
|
33
|
+
\`\`\`
|
|
34
|
+
|
|
35
|
+
The LLM decides how to organize articles. You describe YOUR world in worldview.md.
|
|
36
|
+
|
|
37
|
+
## Article Format
|
|
38
|
+
|
|
39
|
+
\`\`\`yaml
|
|
40
|
+
---
|
|
41
|
+
title: "Staging Deployment Process"
|
|
42
|
+
tags: ["deploy", "staging", "devops", "process", "2026-04-06"]
|
|
43
|
+
owner: devops-agent
|
|
44
|
+
access: public
|
|
45
|
+
created: 2026-04-06
|
|
46
|
+
last_updated: 2026-04-06
|
|
47
|
+
sources: ["entry-id-1", "entry-id-2"]
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
Article content with [[wikilinks]] and section tags.
|
|
51
|
+
|
|
52
|
+
## Deploy Steps
|
|
53
|
+
<!-- tags: process, runbook, staging -->
|
|
54
|
+
Content specific to this section...
|
|
55
|
+
\`\`\`
|
|
56
|
+
|
|
57
|
+
## Tags
|
|
58
|
+
|
|
59
|
+
Tags are the primary context-narrowing mechanism. The more tags, the better.
|
|
60
|
+
|
|
61
|
+
Tag aggressively:
|
|
62
|
+
- **Who**: people, agents, teams involved
|
|
63
|
+
- **What**: project, client, topic, technology
|
|
64
|
+
- **When**: dates, periods, milestones
|
|
65
|
+
- **Where**: server, environment, channel
|
|
66
|
+
- **How**: process, decision, pattern
|
|
67
|
+
- **Your terms**: whatever vocabulary makes sense in YOUR world
|
|
68
|
+
|
|
69
|
+
Section tags (\`<!-- tags: ... -->\`) let different parts of an article
|
|
70
|
+
match different queries. A deploy article might have sections tagged
|
|
71
|
+
"runbook" and "incident" separately.
|
|
72
|
+
|
|
73
|
+
## Operations
|
|
74
|
+
|
|
75
|
+
### Absorb
|
|
76
|
+
Read raw entries \u2192 read worldview.md \u2192 tag aggressively \u2192 create/update articles.
|
|
77
|
+
Also identify GAPS: "We mention X but have no article for it."
|
|
78
|
+
|
|
79
|
+
### Query
|
|
80
|
+
Match by tags first \u2192 then keyword within matched articles \u2192 synthesize.
|
|
81
|
+
If agent is working on a specific project, only send content tagged for that project.
|
|
82
|
+
|
|
83
|
+
### Lint
|
|
84
|
+
Check for: orphan articles, broken [[wikilinks]], untagged articles,
|
|
85
|
+
articles over 100 lines that should split, mentioned-but-missing topics.
|
|
86
|
+
|
|
87
|
+
## Worldview
|
|
88
|
+
|
|
89
|
+
Edit \`worldview.md\` to describe YOUR world. This is not a schema \u2014 it's your
|
|
90
|
+
mental model. The LLM reads it during absorb to understand where things go.
|
|
91
|
+
|
|
92
|
+
Example worldview.md:
|
|
93
|
+
\`\`\`
|
|
94
|
+
I'm the founder of Acme Corp.
|
|
95
|
+
We build software products.
|
|
96
|
+
Our agents: Marketing Bot, DevOps Bot, Coordinator.
|
|
97
|
+
Clients: ClientA (enterprise), ClientB (startup).
|
|
98
|
+
Infrastructure: local dev machine, cloud server.
|
|
99
|
+
We use GitLab for version control.
|
|
100
|
+
\`\`\`
|
|
101
|
+
`),this.log("Created _schema.md")}extractWikilinks(e){return(e.match(/\[\[([^\]]+)\]\]/g)||[]).map(s=>s.replace(/\[\[|\]\]/g,""))}buildBacklinks(){let e={};return this.walkDir(this.baseDir,t=>{if(!t.endsWith(".md"))return;let s=S(this.baseDir,t);if(s.startsWith("raw/")||s.startsWith("_")||s==="WIKI.md"||s==="log.md")return;let r=N(t,"utf-8"),n=this.extractWikilinks(r);for(let a of n)e[a]||(e[a]=[]),e[a].push(s)}),x(y(this.baseDir,"_backlinks.json"),JSON.stringify(e,null,2)),e}getBacklinks(e){let t=y(this.baseDir,"_backlinks.json");if(!$(t))return[];try{return JSON.parse(N(t,"utf-8"))[e]||[]}catch{return[]}}findByTags(e,t,s=10){let r=e.map(a=>a.toLowerCase()),n=[];return this.walkDir(this.baseDir,a=>{if(!a.endsWith(".md"))return;let i=S(this.baseDir,a);if(i.startsWith("raw/")||i.startsWith("_"))return;let o=this.readArticle(i);if(!o||t&&!this.canRead(o.meta,t))return;let c=(o.meta.tags||[]).map(u=>u.toLowerCase()),l=(o.content.match(/<!--\s*tags?:\s*([^>]+)\s*-->/gi)||[]).flatMap(u=>u.replace(/<!--\s*tags?:\s*|\s*-->/gi,"").split(",").map(d=>d.trim().toLowerCase())),v=[...c,...l],p=r.filter(u=>v.includes(u)).length;p>0&&n.push({article:o,score:p})}),n.sort((a,i)=>i.score-a.score).slice(0,s).map(a=>a.article)}getAllTags(){let e=new Map;return this.walkDir(this.baseDir,t=>{if(!t.endsWith(".md"))return;let s=S(this.baseDir,t);if(s.startsWith("raw/")||s.startsWith("_"))return;let r=this.readArticle(s);if(r?.meta.tags)for(let n of r.meta.tags)e.set(n,(e.get(n)||0)+1)}),e}getWorldview(){let e=y(this.baseDir,"worldview.md");return $(e)?N(e,"utf-8"):null}setWorldview(e){x(y(this.baseDir,"worldview.md"),e),this.appendLog("worldview","Updated worldview")}lint(){let e=[],t=new Set,s=new Map,r=new Map;this.walkDir(this.baseDir,a=>{if(!a.endsWith(".md"))return;let i=S(this.baseDir,a);if(i.startsWith("raw/")||i.startsWith("_")||i==="WIKI.md"||i==="log.md")return;let o=this.readArticle(i);if(!o)return;t.add(o.meta.title),r.set(o.meta.title,i);let c=this.extractWikilinks(o.content);s.set(i,c);let l=o.content.split(`
|
|
102
|
+
`).length;l>100&&e.push({type:"bloated",article:i,message:`${l} lines \u2014 consider splitting`}),o.meta.sources?.length||e.push({type:"unsourced",article:i,message:"No sources listed in frontmatter"}),l<10&&o.content.trim().length<100&&e.push({type:"stub",article:i,message:"Very short article \u2014 needs enrichment"})});for(let[a,i]of s)for(let o of i)t.has(o)||e.push({type:"broken-link",article:a,message:`[[${o}]] \u2014 target article not found`});let n=this.buildBacklinks();for(let[a,i]of r)(!n[a]||n[a].length===0)&&e.push({type:"orphan",article:i,message:`No other articles link to "${a}"`});return this.appendLog("lint",`Found ${e.length} issues`),e}getUnabsorbedEntries(){let e=new Set;return this.walkDir(this.baseDir,s=>{if(!s.endsWith(".md"))return;let r=S(this.baseDir,s);if(r.startsWith("raw/")||r.startsWith("_"))return;let n=this.readArticle(r);if(n?.meta.sources)for(let a of n.meta.sources)e.add(a)}),this.listEntries().filter(s=>!e.has(s.id))}buildAbsorbPrompt(e=20){let t=this.getUnabsorbedEntries().slice(0,e);if(t.length===0)return null;let s=t.map(r=>`[${r.date} ${r.agentId} via ${r.source}] ${r.content.slice(0,200)}`).join(`
|
|
103
|
+
|
|
104
|
+
`);return`/wiki absorb
|
|
105
|
+
|
|
106
|
+
There are ${t.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.
|
|
107
|
+
|
|
108
|
+
${s}`}walkDir(e,t){if($(e))for(let s of E(e)){let r=we(e,s);ye(r).isDirectory()?this.walkDir(r,t):t(r)}}};export{A as a,J as b,H as c,q as d,le as e};
|
|
109
|
+
//# sourceMappingURL=chunk-M6HJDSLS.js.map
|