agentix-cli 0.60.0 → 0.61.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,29 +0,0 @@
1
- import{g as ye,h as ke,i as we,k as xe,l as Se}from"./chunk-27P5NLTC.js";import{t as ve,u as Ae}from"./chunk-LXUG2X26.js";import{d as $e,e as Ie}from"./chunk-AQASR6KR.js";import{b as J}from"./chunk-WIBMNQKJ.js";import{q as be}from"./chunk-JORXRF4E.js";import{w as he,z as ct}from"./chunk-S7TCVIET.js";import{existsSync as ut,readdirSync as dt,readFileSync as gt,statSync as ft}from"fs";import{resolve as mt}from"path";function Re(n,e,t=Date.now(),s=7){let r=s*864e5,i=new Map;for(let a of e){let o=i.get(a.workflowId);o?o.push(a):i.set(a.workflowId,[a])}return n.map(a=>{let o=i.get(a.id)??[],l=o.filter(m=>t-m.at<=r),c=o.filter(m=>t-m.at>r&&t-m.at<=r*2),u=l.filter(m=>m.status==="failed").length,g=o.filter(m=>m.status==="paused").length,d=o.length?Math.max(...o.map(m=>m.at)):null,f=o.length?c.length>0&&l.length===0?"dormant":l.length>0&&u*2>=l.length?"failing":l.length>0?"active":"quiet":"never";return{id:a.id,name:a.name||a.id,state:f,lastRunAt:d,recent:l.length,prior:c.length,failed:u,paused:g}}).sort((a,o)=>{let l={dormant:0,failing:1,active:2,quiet:3,never:4};return l[a.state]-l[o.state]||(o.lastRunAt??0)-(a.lastRunAt??0)})}var U=new Map;function Fn(n,e=1e3){if(!ut(n))return[];let t=dt(n).filter(i=>i.endsWith(".jsonl")).map(i=>{let a=mt(n,i);return{path:a,mtime:ft(a).mtimeMs}}).sort((i,a)=>a.mtime-i.mtime).slice(0,e),s=new Set(t.map(i=>i.path));for(let i of U.keys())s.has(i)||U.delete(i);let r=[];for(let{path:i,mtime:a}of t){let o=U.get(i);if(o&&o.mtime===a){o.summary&&r.push(o.summary);continue}let l=pt(i,a);U.set(i,{mtime:a,summary:l}),l&&r.push(l)}return r}function pt(n,e){try{let t=gt(n,"utf-8").split(`
2
- `).filter(Boolean);if(!t.length)return null;let s=JSON.parse(t[0]),r=s.run?.workflowId;if(!r)return null;let i=s.run?.status??"unknown";for(let a=t.length-1;a>=0;a--){let o=JSON.parse(t[a]),l=o.status??o.run?.status;if(l){i=l;break}}return{workflowId:r,status:i,at:e}}catch{return null}}var ht={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},k={routines:200,summary:160,filters:6,filterValue:60,text:120},bt=(n,e,t)=>{try{return be(n,e,t)}catch{return null}},_e=864e5;function Wn(n){let e=n.now??Date.now(),t={...ht,...n.thresholds},s=n.nextFire??bt,r=[];for(let o of n.crons){let l=n.cronRuns.get(o.id)??[],c=o.timezone||"UTC",u=l.map(f=>({at:Date.parse(f.startedAt),status:f.status})),g=l[0],d={id:`cron:${o.id}`,source:"cron",kind:"schedule",name:S(o.id,k.text),trigger:{schedule:S(o.schedule,k.text),timezone:c},agent:o.agent||null,enabled:o.enabled,state:o.enabled?"enabled":"disabled",nextRunAt:o.enabled?G(o.nextRun)??G(s(o.schedule,new Date(e),c)):null,lastRun:g?{at:g.startedAt,status:g.status,summary:$t(g.status==="success"?void 0:g.errorSummary,k.summary)}:null,lastSuccessAt:l.find(f=>f.status==="success")?.startedAt??null,consecutiveFailures:De(u),sampledRuns:l.length,flags:[],attention:null};d.flags=Ce(d,u,o.schedule,c,null,e,t,s),r.push(Te(d))}let i=new Map(Re(n.workflows.map(o=>({id:o.id,name:o.title})),n.workflowRuns,e).map(o=>[o.id,o])),a=new Map;for(let o of n.workflowRuns){let l=a.get(o.workflowId);l?l.push(o):a.set(o.workflowId,[o])}for(let o of n.workflows){let l=o.nodes.find(v=>v.type.startsWith("trigger."));if(!l||l.type!=="trigger.cron"&&l.type!=="trigger.hook")continue;let c=l.config??{},u=o.state||"active",g=u==="active",d=(a.get(o.id)??[]).slice().sort((v,q)=>q.at-v.at),f=d.map(v=>({at:v.at,status:wt(v.status)})),m=f[0],h=l.type==="trigger.cron",b=typeof c.spec=="string"?c.spec:"",K=typeof c.timezone=="string"?c.timezone:"UTC",L={id:`workflow:${o.id}`,source:"workflow",kind:h?"schedule":"event",name:S(o.title||o.id,k.text),trigger:h?{schedule:S(b,k.text),timezone:K}:{event:S(typeof c.event=="string"?c.event:"",k.text),filters:St(c.filter,o)},agent:xt(o),enabled:g,state:u,nextRunAt:h&&g&&b?G(s(b,new Date(e),K)):null,lastRun:m?{at:new Date(m.at).toISOString(),status:m.status}:null,lastSuccessAt:(()=>{let v=f.find(q=>q.status==="success");return v?new Date(v.at).toISOString():null})(),consecutiveFailures:De(f),sampledRuns:d.length,flags:[],attention:null},P=Date.parse(o.updated||o.created||"");L.flags=h?Ce(L,f,b,K,Number.isFinite(P)?P:null,e,t,s):yt(L,i.get(o.id)?.state==="dormant",Number.isFinite(P)?P:null,e,t),r.push(Te(L))}return r.sort(kt).slice(0,k.routines)}function De(n){let e=0;for(let t of n)if(!(t.status==="running"||t.status==="paused"||t.status==="unknown"))if(t.status==="failed"||t.status==="timeout")e++;else break;return e}function Ce(n,e,t,s,r,i,a,o){let l=[],c=e.length?e[0].at:null;if(!n.enabled){let d=Ee(c,r,i,a);return d&&l.push(d),l}if(n.consecutiveFailures>=a.failStreak&&l.push({reason:"failing",detail:`${n.consecutiveFailures} failed attempts in a row`}),c===null)return l.push({reason:"never-ran",detail:"No persisted attempt"}),l;let u=new Date(c),g=null;for(let d=0;d<a.missedFires&&(g=o(t,u,s),!!g);d++)u=g;return g&&i>g.getTime()+a.graceMs&&l.push({reason:"overdue",detail:`No attempt since ${new Date(c).toISOString()}; ${a.missedFires} scheduled fires missed`}),l}function yt(n,e,t,s,r){let i=[],a=n.lastRun?Date.parse(n.lastRun.at):null;if(!n.enabled){let o=Ee(a,t,s,r);return o&&i.push(o),i}return n.consecutiveFailures>=r.failStreak&&i.push({reason:"failing",detail:`${n.consecutiveFailures} failed runs in a row`}),a===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 Ee(n,e,t,s){let r=Math.max(n??0,e??0);return r&&t-r<s.disabledDays*_e?null:{reason:"disabled-long",detail:r?`Disabled; no activity for ${Math.floor((t-r)/_e)} days`:"Disabled and never ran"}}function Te(n){let e=new Set(n.flags.map(t=>t.reason));return n.attention=e.has("failing")?"critical":e.has("overdue")||e.has("dormant")||e.has("never-ran")?"warning":e.has("disabled-long")?"info":null,n}var je={critical:0,warning:1,info:2};function kt(n,e){let t=n.attention?je[n.attention]:3,s=e.attention?je[e.attention]:3;return t-s||Number(e.enabled)-Number(n.enabled)||n.name.localeCompare(e.name)}function wt(n){switch(n){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 xt(n){if(n.ownerAgent)return S(n.ownerAgent,k.text);let e=n.nodes.find(t=>t.type==="agent"&&typeof t.config?.agentId=="string"&&t.config.agentId);return e?S(String(e.config.agentId),k.text):null}function St(n,e){let t=[],s=e?.project;if(s&&t.push(S(`project=${s}`,k.filterValue)),n&&typeof n=="object"&&!Array.isArray(n))for(let[r,i]of Object.entries(n)){let a=Array.isArray(i)?i.map(String):i==null?[]:[String(i)];a.length&&t.push(S(`${r}=${a.join(",")}`,k.filterValue))}return t.slice(0,k.filters)}function G(n){if(!n)return null;let e=n instanceof Date?n:new Date(n);return Number.isFinite(e.getTime())?e.toISOString():null}function S(n,e){return n.length<=e?n:n.slice(0,e-3)+"..."}function $t(n,e){return n===void 0?void 0:S(n,e)}import{createHash as It,randomBytes as Oe}from"crypto";import{existsSync as vt,mkdirSync as At,readFileSync as Rt,writeFileSync as _t}from"fs";import{resolve as Dt,dirname as Ct}from"path";var V="agx_live_",Tt=".agentx/tokens.json",Le=class{file;constructor(e=process.cwd(),t=Tt){this.file=Dt(e,t)}load(){if(!vt(this.file))return[];try{return JSON.parse(Rt(this.file,"utf-8"))}catch{return[]}}save(e){At(Ct(this.file),{recursive:!0}),_t(this.file,JSON.stringify(e,null,2)+`
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 a of e.scopes)if(!jt(a))throw new Error(`Invalid scope: ${a}`);let t=Oe(32).toString("hex"),s=V+t,r={id:"tok_"+Oe(4).toString("hex"),name:e.name.trim(),prefix:V+t.slice(0,4),hash:Pe(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 t=this.load(),s=t.find(r=>r.id===e);return s?(s.revokedAt=new Date().toISOString(),this.save(t),s):null}isActive(e){let t=this.load().find(s=>s.id===e);return!!t&&!t.revokedAt&&!(t.expiresAt&&Date.parse(t.expiresAt)<Date.now())}verify(e){if(!e||!e.startsWith(V))return null;let t=Pe(e),s=this.load(),r=s.find(o=>o.hash===t);if(!r||r.revokedAt||r.expiresAt&&Date.parse(r.expiresAt)<Date.now())return null;let i=Date.now(),a=r.lastUsedAt?Date.parse(r.lastUsedAt):0;if(i-a>6e4){r.lastUsedAt=new Date(i).toISOString();try{this.save(s)}catch{}}return r}};function Jn(n,e){return!!(n.scopes.includes(e)||e.startsWith("agent:")&&n.scopes.includes("agent:*")||e==="dashboard:read"&&n.scopes.includes("dashboard:write"))}function jt(n){return n==="dashboard:read"||n==="dashboard:write"||n==="agent:*"||/^agent:[a-z0-9][a-z0-9_-]*$/.test(n)||n==="mesh:peer"||n==="app"}function Pe(n){return"sha256:"+It("sha256").update(n).digest("hex")}function Gn(n){let e=n.headers.authorization,t=Array.isArray(e)?e[0]:e;if(t&&t.toLowerCase().startsWith("bearer "))return t.slice(7).trim();if(n.url)try{let r=new URL(n.url,"http://localhost").searchParams.get("token");if(r)return r}catch{}return null}import{existsSync as X,readdirSync as Vt,readFileSync as Xt}from"fs";import{resolve as D}from"path";import{existsSync as Et,mkdirSync as Ot,readdirSync as Lt,readFileSync as Pt,renameSync as Ut,writeFileSync as Ft}from"fs";import{resolve as Fe}from"path";var Ue=["discard","keep","pause","approve"],$={title:120,ask:300,recommend:300,source:500,note:500,pendingPerAgent:25},Bt={defaultExpiryDays:3,maxExpiryDays:30};function _(n){return Fe(n,".agentx","approvals")}var Nt=/^[a-z0-9][a-z0-9-]{0,80}$/;function Be(n){return Nt.test(n)}function Ne(n,e){if(!Be(e))throw new Error(`invalid card id: ${e}`);return Fe(_(n),`${e}.json`)}function Mt(n,e){let t=new Date(n).toISOString().slice(0,10),s=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40);return`${t}-${s||"card"}-${Math.random().toString(36).slice(2,6)}`}function F(n,e){Ot(_(n),{recursive:!0});let t=Ne(n,e.id),s=`${t}.${process.pid}.tmp`;Ft(s,JSON.stringify(e,null,2)+`
4
- `),Ut(s,t)}function T(n,e){if(!Be(e))return null;try{return JSON.parse(Pt(Ne(n,e),"utf-8"))}catch{return null}}function j(n,e){let t=_(n);if(!Et(t))return[];let s=[];for(let r of Lt(t).filter(i=>i.endsWith(".json")&&!i.startsWith("_")).sort()){let i=T(n,r.slice(0,-5));i&&(!e||i.status===e)&&s.push(i)}return s}function y(n){return typeof n=="string"?n.replace(/\s+/g," ").trim():""}function Wt(n,e,t){let s=e+t.maxExpiryDays*864e5,r,i=y(n);if(!i)r=e+t.defaultExpiryDays*864e5;else{let a=/^(\d+)\s*([hd])$/i.exec(i);if(a)r=e+Number(a[1])*(a[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 zt(n,e={}){let t=e.now??Date.now(),s=e.settings??Bt,r=y(n.title),i=y(n.ask),a=y(n.recommend),o=y(n.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(!a)return{ok:!1,error:"recommend is required: your advice and why, in one line"};if(!o)return{ok:!1,error:"raised_by is required: the agent id"};if(r.length>$.title)return{ok:!1,error:`title is longer than ${$.title} characters`};if(i.length>$.ask)return{ok:!1,error:`ask is longer than ${$.ask} characters`};if(a.length>$.recommend)return{ok:!1,error:`recommend is longer than ${$.recommend} characters`};let l=y(n.if_silent).toLowerCase();if(!Ue.includes(l))return{ok:!1,error:`if_silent must be one of ${Ue.join(", ")}`};let c=Wt(n.expires,t,s);if(!c.ok)return c;let u=y(n.source);if(u.length>$.source)return{ok:!1,error:`source is longer than ${$.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 g,d=n.reply;return d&&typeof d=="object"&&y(d.channel)&&y(d.chatId)&&(g={channel:y(d.channel),chatId:y(d.chatId),...y(d.accountId)?{accountId:y(d.accountId)}:{}}),{ok:!0,card:{id:Mt(t,r),title:r,ask:i,recommend:a,if_silent:l,expires:c.at,...u?{source:u}:{},raised_by:o,created_at:new Date(t).toISOString(),...g?{reply:g}:{},status:"pending"}}}function Qn(n,e,t={}){let s=zt(e,t);if(!s.ok)return s;let r=j(n,"pending").filter(i=>i.raised_by===s.card.raised_by).length;return r>=$.pendingPerAgent?{ok:!1,error:`${s.card.raised_by} already has ${r} cards waiting; wait for decisions before raising more`}:(F(n,s.card),s)}function Me(n,e,t,s={}){let r=T(n,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=y(s.note).slice(0,$.note),a={...r,status:"decided",verdict:t,decided_by:s.by??"operator",decided_at:new Date(s.now??Date.now()).toISOString(),...i?{note:i}:{}};return F(n,a),{ok:!0,card:a}}function Zn(n,e=Date.now()){let t=[];for(let s of j(n,"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()};F(n,r),t.push(r)}return t}function er(n){return j(n).filter(e=>e.status!=="pending"&&!e.agent_notified_at)}function tr(n,e,t=Date.now()){let s=T(n,e);!s||s.agent_notified_at||F(n,{...s,agent_notified_at:new Date(t).toISOString()})}function nr(n){let e=n.status==="decided"?n.verdict==="yes"?"The operator said YES.":"The operator said NO.":`Nobody answered before it expired, so the default applied: ${n.outcome??n.if_silent}.`,t=[`[Approval result] Your decision card "${n.title}" (${n.id}) is closed.`,`Question: ${n.ask}`,e];return n.note&&t.push(`Operator note: ${n.note}`),n.source&&t.push(`Source: ${n.source}`),n.reply&&t.push(`You raised it from ${n.reply.channel} chat ${n.reply.chatId}; reply there if the requester should know.`),t.push("Act on this result now. Do not raise the same card again."),t.join(`
5
- `)}import{mkdirSync as Ht,readFileSync as Kt,renameSync as qt,writeFileSync as Jt}from"fs";import{resolve as Gt}from"path";function We(n){return Gt(_(n),"_state.json")}function B(n){try{let e=JSON.parse(Kt(We(n),"utf-8"));return{snoozed:e&&typeof e.snoozed=="object"&&e.snoozed?e.snoozed:{},...typeof e?.lastDigest=="string"?{lastDigest:e.lastDigest}:{}}}catch{return{snoozed:{}}}}function ze(n,e){Ht(_(n),{recursive:!0});let t=We(n),s=`${t}.${process.pid}.tmp`;Jt(s,JSON.stringify(e,null,2)+`
6
- `),qt(s,t)}function He(n,e,t,s=Date.now()){let r=B(n),i={};for(let[a,o]of Object.entries(r.snoozed))Date.parse(o)>s&&(i[a]=o);i[e]=t.toISOString(),ze(n,{...r,snoozed:i})}function ar(n,e){ze(n,{...B(n),lastDigest:e})}var Ke=["card","schedule","memory","wiki"],Yt=280;function Y(n,e=Yt){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function qe(n){if(n.configPath)return D(n.configPath);let e=[D(n.root,"agentx.json"),D(n.root,".agentx","config.json")];return e.find(t=>X(t))??e[0]}function Q(n){return n.wikiDir?D(n.wikiDir):D(n.root,".agentx","wiki")}function Qt(n){return j(n.root,"pending").map(Zt)}function Zt(n){return{key:`card:${n.id}`,kind:"card",title:n.title,ask:n.ask,yes:`tell ${n.raised_by} yes`,no:`tell ${n.raised_by} no`,recommend:n.recommend,if_silent:n.if_silent,expires:n.expires,...n.source?{source:n.source}:{},raised_by:n.raised_by,created_at:n.created_at}}function en(n){let e=qe(n);if(!X(e))return[];let t;try{t=JSON.parse(Xt(e,"utf-8"))}catch{return[]}let s=new Date(n.now??Date.now()),r=[];for(let[i,a]of Object.entries(t?.crons??{})){let o=a?.approval;if(!o||o.action!=="create"&&o.action!=="delete")continue;let l=a.timezone||"UTC",c=a.schedule?ye(a.schedule):"",u=a.schedule?`${c.charAt(0).toLowerCase()}${c.slice(1)} (${a.schedule})`:"no schedule",g=String(a.prompt??a.command??""),d=o.action==="create";r.push({key:`schedule:${i}`,kind:"schedule",title:d?`New schedule "${i}" for ${a.agent??"an agent"}`:`Delete schedule "${i}"`,ask:d?`Let ${a.agent??"the agent"} run this ${u}?`:`Remove the schedule "${i}" (${u})?`,yes:d?"enable it":"remove it",no:d?"drop the request":"keep the schedule",raised_by:String(o.requestedBy??"unknown"),created_at:String(o.requestedAt??""),detail:Y(`${g}${d&&a.schedule?` \xB7 first run ${we(ke(a.schedule,l,s),l)}`:""}`),more:"agentx schedule list"})}return r}function Je(n){let e=D(n,".agentx","memory");return X(e)?Vt(e).filter(t=>t.endsWith(".jsonl")).map(t=>t.slice(0,-6)).sort():[]}function tn(n){let e=Je(n.root);if(e.length===0)return[];let t=new J(n.root),s=[];for(let r of e)for(let i of t.held(r))s.push({key:`memory:${r}/${i.id}`,kind:"memory",title:`Fact ${r} learned from ${i.source.channel}`,ask:`Let ${r} use this fact in its prompts?`,yes:"use it",no:"keep it out for good",raised_by:r,created_at:i.createdAt,detail:Y(i.content),more:`agentx memory facts held --agent ${r}`});return s}function nn(n){let e=n.sources.filter(t=>t.failure);return e.length?e.map(t=>`Recurring failure: ${t.agentId}'s ${t.failure.tool} fails with "${t.failure.errorClass}" in ${t.occurrences??1} sessions (${t.failure.runs} runs).`).join(" "):`${n.sources.length} source(s)${n.occurrences>1?`, seen in ${n.occurrences} sessions`:""}.`}function rn(n){return Ie(Q(n),"pending").map(e=>{let t=e.evidence;return{key:`wiki:${e.id}`,kind:"wiki",title:e.article.title,ask:e.replaces?`Update "${e.article.path}" in the shared wiki?`:`Add "${e.article.path}" to the shared wiki?`,yes:"write the article",no:"decline it",raised_by:t.agents.join(", ")||"wiki promote",created_at:e.createdAt,detail:Y(`${nn(t)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}var Ge={card:Qt,schedule:en,memory:tn,wiki:rn};function sn(n,e){let t=n.expires?Date.parse(n.expires):1/0,s=e.expires?Date.parse(e.expires):1/0;return t!==s?t-s:(Date.parse(n.created_at)||0)-(Date.parse(e.created_at)||0)}function br(n,e={}){let t=n.now??Date.now(),{snoozed:s}=B(n.root),r=[],i=[],a=0;for(let o of e.kinds??Ke){let l;try{l=Ge[o](n)}catch(c){i.push({kind:o,error:String(c?.message??c).slice(0,200)});continue}for(let c of l){let u=s[c.key];if(u&&Date.parse(u)>t){if(!e.includeSnoozed){a++;continue}c.snoozed_until=u}r.push(c)}}return r.sort(sn),{items:r,snoozed:a,errors:i}}function on(n){let e=n.indexOf(":");if(e<=0)return null;let t=n.slice(0,e),s=n.slice(e+1);return!Ke.includes(t)||!s?null:{kind:t,ref:s}}function an(n,e,t){switch(e){case"card":return T(n.root,t)?.status==="pending";case"wiki":return $e(Q(n),t)?.status==="pending";default:return Ge[e](n).some(s=>s.key===`${e}:${t}`)}}async function yr(n,e,t,s={}){let r=on(e);if(!r)return{ok:!1,error:`unknown item "${e}": use a key from \`agentx approvals list\``};let{kind:i,ref:a}=r,o=n.now??Date.now(),l=s.by??"operator";if(t==="later"){if(!an(n,i,a))return{ok:!1,error:`nothing waiting for "${e}"`};let u=s.laterHours&&s.laterHours>0?s.laterHours:24,g=new Date(o+u*36e5);return He(n.root,e,g,o),{ok:!0,message:`${e} put off until ${g.toISOString()}`}}let c=t==="yes";switch(i){case"card":{let u=Me(n.root,a,c?"yes":"no",{by:l,note:s.note,now:o});return u.ok?{ok:!0,message:`${e}: ${u.card.raised_by} will be told ${c?"yes":"no"}`}:u}case"schedule":{let u=await(c?xe:Se)(a,{configPath:qe(n),reload:n.reload});return u.success?{ok:!0,message:u.message}:{ok:!1,error:u.message}}case"memory":{let u=a.indexOf("/");if(u<=0)return{ok:!1,error:"memory keys look like memory:<agent>/<fact-id>"};let g=a.slice(0,u),d=a.slice(u+1);if(!Je(n.root).includes(g))return{ok:!1,error:`no memory for agent "${g}"`};let f=new J(n.root);return f.held(g).some(m=>m.id===d)?(f.review(g,d,c?"approved":"rejected",l),{ok:!0,message:`${e} ${c?"approved: the agent may use it":"rejected: it stays out of prompts"}`}):{ok:!1,error:`fact "${d}" isn't waiting for review`}}case"wiki":{let u=Q(n),g=c?ve(u,a,{by:l,force:s.force,now:o}):Ae(u,a,{by:l,reason:s.note,now:o});return g.ok?{ok:!0,message:c?`${g.proposal.article.path} written to the shared wiki`:`${e} rejected`}:g}}}var Ve=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]);function wr(n){return n==="/api/memory"||n.startsWith("/api/memory/")||n==="/approvals"||n.startsWith("/approvals/")||n==="/events/recent"||/^\/agents\/[^/]+\/events$/.test(n)||n==="/traces"||n.startsWith("/traces/")||n==="/voice/history"||n.startsWith("/voice/history/")}function xr(n){return n==="/reload"||n==="/api/processes/kill"||n==="/send"||n==="/send/agent"||n==="/send/contact"||n==="/mesh/announce"||n==="/voice/settings"||n==="/voice/preview"||/^\/api\/tasks\/[^/]+\/(cancel|followup)$/.test(n)||/^\/crons\/[^/]+\/enabled$/.test(n)}function Sr(n){return Ve.has(n)}function $r(n){if(n.foreignBrowser)return{allowed:!1,reason:"foreign-browser-origin"};if(n.enforcementDisabled)return{allowed:!0,reason:"disabled"};if(Ve.has(n.remoteAddress))return{allowed:!0,reason:"loopback"};if(n.acceptedTokens.size===0)return{allowed:!0,reason:"no-tokens-configured"};let e=n.authorizationHeader||"",t=e.startsWith("Bearer ")?e.slice(7).trim():"";return t&&n.acceptedTokens.has(t)?{allowed:!0,reason:"token"}:{allowed:!1,reason:"missing-or-invalid-token"}}function Ir(n,e=process.env){let t=new Set;e.MESH_TOKEN&&t.add(e.MESH_TOKEN);for(let s of n.mesh?.peers||[])s.token&&t.add(s.token);return t}function vr(n,e,t=process.env){let s=i=>i.replace(/\/+$/,"");return(e===s(n.daemonUrl)?n.token:n.daemons.find(i=>s(i.url)===e)?.token)||t.MESH_TOKEN||void 0}function N(n){return(Array.isArray(n)?n[0]:n)?.trim()??""}function ln(n){try{return new URL(n).host.toLowerCase()}catch{return null}}function cn(n=process.env){return new Set((n.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function Rr(n,e=cn()){let t=N(n.origin);if(t){if(e.has(t.replace(/\/+$/,"").toLowerCase()))return"same-origin";let r=ln(t),i=[N(n.host),N(n["x-forwarded-host"])].filter(Boolean).map(a=>a.toLowerCase());return r&&i.includes(r)?"same-origin":"foreign"}let s=N(n["sec-fetch-site"]).toLowerCase();return s==="cross-site"||s==="same-site"?"foreign":"none"}function _r(n){let e=(n||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}import{readFileSync as ee,writeFileSync as tt,existsSync as te,readdirSync as yn,statSync as kn}from"fs";import{resolve as ne,join as wn}from"path";import{existsSync as Xe,mkdirSync as un,readFileSync as dn,writeFileSync as Ye}from"fs";import{dirname as gn,resolve as Qe}from"path";import{z as p}from"zod";var fn=p.object({type:p.enum(["gitlab","github"]),host:p.string().optional(),project:p.string(),iid:p.number().int().positive(),url:p.string()}),mn=p.object({id:p.string(),title:p.string(),description:p.string().optional(),assignee:p.string().optional(),labels:p.array(p.string()).default([]),milestone:p.string().optional(),status:p.enum(["todo","doing","blocked","done"]).default("todo"),priority:p.number().int().optional(),estimatedSeconds:p.number().int().optional(),source:fn.optional(),importedAt:p.string().optional(),createdAt:p.string(),updatedAt:p.string(),blocker:p.string().optional(),doneNote:p.string().optional()}),pn=p.object({version:p.literal(1),items:p.array(mn).default([])}),M=class{constructor(e){this.path=e}jsonPath(){return Qe(process.cwd(),this.path).replace(/\.md$/i,".json")}mdPath(){return Qe(process.cwd(),this.path).replace(/\.json$/i,".md")}exists(){return Xe(this.jsonPath())}load(){let e=this.jsonPath();if(!Xe(e))return{version:1,items:[]};let t=dn(e,"utf-8");try{return pn.parse(JSON.parse(t))}catch(s){throw new Error(`Backlog file invalid (${e}): ${s.message}`)}}save(e){let t=this.jsonPath();un(gn(t),{recursive:!0}),Ye(t,JSON.stringify(e,null,2)+`
7
- `),Ye(this.mdPath(),this.toMarkdown(e))}list(){return this.load().items}findById(e){return this.list().find(t=>t.id===e)}add(e){let t=this.load();if(t.items.some(i=>i.id===e.id))throw new Error(`backlog item ${e.id} already exists`);let s=new Date().toISOString(),r={...e,labels:e.labels??[],status:e.status??"todo",createdAt:e.createdAt??s,updatedAt:s};return t.items.push(r),this.save(t),r}addMany(e){let t=this.load(),s=new Set(t.items.map(a=>a.id)),r=new Date().toISOString(),i=[];for(let a of e){if(s.has(a.id))continue;let o={...a,labels:a.labels??[],status:a.status??"todo",createdAt:a.createdAt??r,updatedAt:r};t.items.push(o),i.push(o),s.add(o.id)}return i.length&&this.save(t),i}update(e,t){let s=this.load(),r=s.items.findIndex(a=>a.id===e);if(r<0)throw new Error(`backlog item ${e} not found`);let i={...s.items[r],...t,id:s.items[r].id,createdAt:s.items[r].createdAt,updatedAt:new Date().toISOString()};return s.items[r]=i,this.save(s),i}remove(e){let t=this.load(),s=t.items.length;return t.items=t.items.filter(r=>r.id!==e),t.items.length===s?!1:(this.save(t),!0)}toMarkdown(e){let t=["# Backlog","","_Generated from `backlog.json`. Do not edit by hand \u2014 use `agentx backlog` commands._",""],s={doing:[],blocked:[],todo:[],done:[]};for(let i of e.items)s[i.status].push(i);let r=[["doing","Doing"],["blocked","Blocked"],["todo","To Do"],["done","Done"]];for(let[i,a]of r)if(s[i].length){t.push(`## ${a}`,"");for(let o of s[i]){let l=i==="done"?"x":" ",c=o.assignee?`@${o.assignee} `:"",u=o.estimatedSeconds?` [time: ${Math.round(o.estimatedSeconds/60)}m]`:"",g=o.source?` (${o.source.type}: ${o.source.project}#${o.source.iid})`:"";t.push(`- [${l}] ${c}${o.title}${u}${g}`),o.source?.url&&t.push(` - <${o.source.url}>`),o.labels.length&&t.push(` - labels: ${o.labels.join(", ")}`),o.milestone&&t.push(` - milestone: ${o.milestone}`),o.blocker&&t.push(` - BLOCKED: ${o.blocker}`)}t.push("")}return t.join(`
8
- `)}};function Er(n){return`${n.type}:${n.project}:${n.iid}`}function Ze(n,e,t){let s=[];if(e.type==="gitlab"){let r=t.channels.gitlab?.agentMappings??[];for(let i of n){let a=r.find(o=>o.agentId===i);a?.gitlabUsernames?.length?s.push(a.gitlabUsernames[0]):s.push(i)}}else if(e.type==="github"){let r=t.channels.github?.agentMappings??[];for(let i of n){let a=r.find(o=>o.agentId===i);a?.githubUsernames?.length?s.push(a.githubUsernames[0]):s.push(i)}}return s}async function Z(n,e,t,s=()=>{}){return n.source?n.source.type==="gitlab"?hn(n.source,e,t,s):n.source.type==="github"?bn(n.source,e,t,s):{ok:!1,error:`unknown source.type ${n.source.type}`,attempts:[]}:{ok:!0,attempts:[]}}async function hn(n,e,t,s){let r=t.channels.gitlab,i=r?.token,a=r?.host||(n.host?`https://${n.host}`:void 0);if(!i||!a)return{ok:!1,error:"gitlab token/host not configured",attempts:[]};let o=[],l=async(f,m={})=>fetch(`${a}/api/v4${f}`,{...m,headers:{"PRIVATE-TOKEN":i,"Content-Type":"application/json",...m.headers||{}}}),c=encodeURIComponent(n.project),u;e.assigneeUsernames!==void 0&&(u=(await Promise.all(e.assigneeUsernames.map(async m=>{try{let h=await fetch(`${a}/api/v4/users?username=${encodeURIComponent(m)}`,{headers:{"PRIVATE-TOKEN":i}});if(!h.ok)return null;let b=await h.json();return Array.isArray(b)&&b[0]?.id?b[0].id:null}catch{return null}}))).filter(m=>typeof m=="number"));let g;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")g=0;else try{let f=await l(`/projects/${c}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);if(f.ok){let m=await f.json();Array.isArray(m)&&m[0]?.id&&(g=m[0].id)}}catch(f){s(`[backlog-sync] milestone lookup failed: ${f.message}`)}let d={};if(e.title!==void 0&&(d.title=e.title),e.description!==void 0&&(d.description=e.description),e.labels!==void 0&&(d.labels=e.labels.join(",")),e.addLabels?.length&&(d.add_labels=e.addLabels.join(",")),e.removeLabels?.length&&(d.remove_labels=e.removeLabels.join(",")),u!==void 0&&(d.assignee_ids=u),g!==void 0&&(d.milestone_id=g),e.state&&(d.state_event=e.state==="closed"?"close":"reopen"),Object.keys(d).length)try{let f=await l(`/projects/${c}/issues/${n.iid}`,{method:"PUT",body:JSON.stringify(d)});if(o.push({kind:"PUT issue",ok:f.ok,status:f.status}),!f.ok){let m=await f.text().catch(()=>"");return{ok:!1,attempts:o,error:`PUT issue ${f.status}: ${m.slice(0,200)}`,url:n.url}}}catch(f){return o.push({kind:"PUT issue",ok:!1,error:f.message}),{ok:!1,attempts:o,error:f.message,url:n.url}}if(e.note)try{let f=await l(`/projects/${c}/issues/${n.iid}/notes`,{method:"POST",body:JSON.stringify({body:e.note})});o.push({kind:"POST note",ok:f.ok,status:f.status})}catch(f){o.push({kind:"POST note",ok:!1,error:f.message})}return{ok:o.every(f=>f.ok),attempts:o,url:n.url}}async function bn(n,e,t,s){let i=t.channels.github?.token;if(!i)return{ok:!1,error:"github token not configured",attempts:[]};let a=[],o=async(d,f={})=>fetch(`https://api.github.com${d}`,{...f,headers:{Authorization:`Bearer ${i}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",...f.headers||{}}}),l=n.project,c;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")c=null;else try{let d=await o(`/repos/${l}/milestones?state=all&per_page=100`);if(d.ok){let f=await d.json(),m=Array.isArray(f)?f.find(h=>h.title===e.milestoneTitle):null;m?.number&&(c=m.number)}}catch(d){s(`[backlog-sync] github milestone lookup failed: ${d.message}`)}let u;if(e.labels!==void 0)u=e.labels;else if(e.addLabels?.length||e.removeLabels?.length)try{let d=await o(`/repos/${l}/issues/${n.iid}`);if(d.ok){let f=await d.json(),m=Array.isArray(f.labels)?f.labels.map(b=>typeof b=="string"?b:b.name):[],h=new Set([...m,...e.addLabels??[]]);for(let b of e.removeLabels??[])h.delete(b);u=[...h]}}catch(d){s(`[backlog-sync] github label fetch failed: ${d.message}`)}let g={};if(e.title!==void 0&&(g.title=e.title),e.description!==void 0&&(g.body=e.description),u!==void 0&&(g.labels=u),e.assigneeUsernames!==void 0&&(g.assignees=e.assigneeUsernames),c!==void 0&&(g.milestone=c),e.state&&(g.state=e.state),Object.keys(g).length)try{let d=await o(`/repos/${l}/issues/${n.iid}`,{method:"PATCH",body:JSON.stringify(g)});if(a.push({kind:"PATCH issue",ok:d.ok,status:d.status}),!d.ok){let f=await d.text().catch(()=>"");return{ok:!1,attempts:a,error:`PATCH issue ${d.status}: ${f.slice(0,200)}`,url:n.url}}}catch(d){return a.push({kind:"PATCH issue",ok:!1,error:d.message}),{ok:!1,attempts:a,error:d.message,url:n.url}}if(e.note)try{let d=await o(`/repos/${l}/issues/${n.iid}/comments`,{method:"POST",body:JSON.stringify({body:e.note})});a.push({kind:"POST comment",ok:d.ok,status:d.status})}catch(d){a.push({kind:"POST comment",ok:!1,error:d.message})}return{ok:a.every(d=>d.ok),attempts:a,url:n.url}}var re=/^(\s*)-\s*\[( |x|X)\]\s*(.*)$/,W=/@([a-z0-9_-]+)/i,et=/\[time:\s*([0-9hm\s]+)\]/i;function xn(n){let e=n.match(/(\d+)\s*h/i),t=n.match(/(\d+)\s*m/i);return(e?parseInt(e[1],10)*3600:0)+(t?parseInt(t[1],10)*60:0)}var se=class{constructor(e,t,s=()=>{}){this.path=e;this.daemon=t;this.log=s;this.store=new M(this.path)}type="backlog";capabilities={listAll:!0,create:!1,transition:!1,labels:!0,search:!1};store;getStore(){return this.store}readMd(){let e=ne(process.cwd(),this.path);return te(e)?ee(e,"utf-8").split(`
9
- `):[]}writeMd(e){let t=ne(process.cwd(),this.path);tt(t,e.join(`
10
- `))}async listOpen(e){if(this.store.exists())return this.store.list().filter(i=>i.status!=="done"&&(!i.assignee||i.assignee.toLowerCase()===e.toLowerCase())).map(i=>this.toWorkItem(i));let t=this.readMd(),s=[];for(let r=0;r<t.length;r++){let i=t[r].match(re);if(!i||i[2].toLowerCase()==="x")continue;let o=i[3],l=o.match(W);if(l&&l[1].toLowerCase()!==e.toLowerCase())continue;let c=o.match(et),u=o.replace(W,"").replace(et,"").trim();s.push({id:`backlog:${r}`,title:u||`Task at line ${r+1}`,assignee:l?l[1]:void 0,estimatedSeconds:c?xn(c[1]):void 0,priority:r})}return s}async listAll(e={}){return this.store.exists()?this.store.list().map(t=>this.toWorkItem(t)):[]}async claim(e,t){if(!this.store.exists())return;let s=this.store.findById(t);if(!s)return;let r=this.store.update(t,{assignee:s.assignee||e,status:"doing"});if(r.source&&this.daemon){let i=Ze([r.assignee||e],r.source,this.daemon);Z(r,{assigneeUsernames:i,addLabels:["Doing"],removeLabels:["To Do"]},this.daemon,this.log).catch(a=>this.log(`[backlog-sync] claim failed for ${t}: ${a?.message??a}`))}}async report(e,t){if(this.store.exists()&&this.store.findById(e)){let o={};t.status==="done"?o.status="done":t.status==="blocked"?(o.status="blocked",o.blocker=t.blocker||t.note||void 0):t.status==="in-progress"&&(o.status="doing"),t.timeSeconds&&(o.estimatedSeconds=t.timeSeconds);let l=this.store.update(e,o);if(l.source&&this.daemon){let c={};t.status==="done"?(c.addLabels=["Done"],c.removeLabels=["Doing"]):t.status==="blocked"&&(c.addLabels=["Blocked"]),t.note&&(c.note=t.note),Object.keys(c).length&&Z(l,c,this.daemon,this.log).catch(u=>this.log(`[backlog-sync] report failed for ${e}: ${u?.message??u}`))}return}if(!e.startsWith("backlog:"))throw new Error(`not a backlog id: ${e}`);let s=parseInt(e.slice(8),10),r=this.readMd(),i=r[s];if(!i)throw new Error(`backlog line ${s} missing`);if(!i.match(re))throw new Error(`backlog line ${s} not a checkbox`);if(t.status==="done"){r[s]=i.replace(/- \[ \]/,"- [x]");let o=t.timeSeconds?` <!-- done by agent, ${Math.round(t.timeSeconds/60)}m -->`:" <!-- done by agent -->";r.splice(s+1,0,o)}else t.status==="blocked"?r.splice(s+1,0,` <!-- BLOCKED: ${t.blocker||t.note||"?"} -->`):t.note&&r.splice(s+1,0,` <!-- ${t.note.replace(/-->/g,"\u2014 >")} -->`);this.writeMd(r)}toWorkItem(e){let t={todo:"todo",doing:"doing",blocked:"onhold",done:"done"}[e.status];return{id:e.id,title:e.title,description:e.description,assignee:e.assignee,estimatedSeconds:e.estimatedSeconds,priority:e.priority,labels:e.labels,stage:t,milestone:e.milestone,url:e.source?.url,updatedAt:e.updatedAt,state:e.status==="done"?"closed":"opened"}}},ie=class{constructor(e,t){this.root=e;this.glob=t}type="wiki";capabilities={listAll:!1,create:!1,transition:!1,labels:!1,search:!1};walk(e,t){if(te(e))for(let s of yn(e)){let r=wn(e,s);kn(r).isDirectory()?this.walk(r,t):s.endsWith(".md")&&t.push(r)}}async listOpen(e){let t=[];this.walk(ne(process.cwd(),this.root),t);let s=[];for(let r of t){let i=ee(r,"utf-8").split(`
11
- `);for(let a=0;a<i.length;a++){let o=i[a].match(re);if(!o||o[2].toLowerCase()==="x")continue;let l=o[3].match(W);!l||l[1].toLowerCase()!==e.toLowerCase()||s.push({id:`wiki:${r}:${a}`,title:o[3].replace(W,"").trim(),assignee:l[1],priority:a})}}return s}async claim(){}async report(e,t){let s=e.split(":"),r=parseInt(s[s.length-1],10),i=s.slice(1,-1).join(":");if(!te(i))return;let a=ee(i,"utf-8").split(`
12
- `);t.status==="done"&&a[r]&&(a[r]=a[r].replace(/- \[ \]/,"- [x]"),tt(i,a.join(`
13
- `)))}},oe=class{constructor(e,t,s,r,i){this.host=e;this.token=t;this.projects=s;this.agentUsernames=r;this.log=i}type="gitlab";capabilities={listAll:!0,create:!0,transition:!0,labels:!0,search:!0};usernameToAgent(e){for(let[t,s]of Object.entries(this.agentUsernames))if(s.some(r=>r.toLowerCase()===e.toLowerCase()))return t}mapIssue(e,t){let s=e.references?.full?.split("#")[0]||t,r=[],i;Array.isArray(e.labels)&&(e.labels.length&&typeof e.labels[0]=="object"?(i=e.labels.map(c=>({name:c.name,color:c.color,text_color:c.text_color})),r=i.map(c=>c.name)):r=e.labels);let o=(Array.isArray(e.assignees)&&e.assignees.length?e.assignees:e.assignee?[e.assignee]:[]).map(c=>({username:c.username,name:c.name,avatarUrl:c.avatar_url})),l=o[0]?.username;return{id:`gitlab:${s}:issue:${e.iid}`,title:e.title,description:e.description||void 0,assignee:l?this.usernameToAgent(l)||l:void 0,assignees:o,url:e.web_url,priority:e.weight??99,estimatedSeconds:e.time_stats?.time_estimate||void 0,labels:r,labelDetails:i,updatedAt:e.updated_at,state:e.state==="closed"?"closed":"opened",milestone:e.milestone?.title||void 0}}async api(e,t={}){let s=await fetch(`${this.host}/api/v4${e}`,{...t,headers:{"PRIVATE-TOKEN":this.token,"Content-Type":"application/json",...t.headers||{}}});if(!s.ok)throw new Error(`GitLab ${s.status}: ${await s.text().catch(()=>"")}`);return s.json()}async listOpen(e){let t=this.agentUsernames[e]||[];if(!t.length)return[];let s=[],r=this.projects.length?this.projects:["__ALL__"];for(let i of t)for(let a of r)try{let o=`assignee_username=${encodeURIComponent(i)}&state=opened&scope=all&per_page=20`,l=a==="__ALL__"?`/issues?${o}`:`/projects/${encodeURIComponent(a)}/issues?${o}`,c=await this.api(l);for(let u of c){let g=this.mapIssue(u,a);g.assignee=e,s.push(g)}}catch(o){this.log(`[business] GitLab listOpen failed for ${i} on ${a}: ${o.message}`)}return s}async claim(e,t){let{project:s,iid:r,type:i}=this.parseId(t),a=`/projects/${encodeURIComponent(s)}/${i==="issue"?"issues":"merge_requests"}/${r}?add_labels=Doing&remove_labels=To Do`;try{await this.api(a,{method:"PUT"})}catch(o){this.log(`[business] claim label update failed: ${o.message}`)}}async report(e,t){let{project:s,iid:r,type:i}=this.parseId(e),a=i==="issue"?"issues":"merge_requests";if(t.timeSeconds&&t.timeSeconds>0){let o=Math.max(1,Math.round(t.timeSeconds/60)),l=o>=60?`${Math.floor(o/60)}h${o%60?` ${o%60}m`:""}`:`${o}m`;try{await this.api(`/projects/${encodeURIComponent(s)}/${a}/${r}/add_spent_time?duration=${encodeURIComponent(l)}`,{method:"POST"})}catch(c){this.log(`[business] add_spent_time failed: ${c.message}`)}}if(t.status==="done")try{await this.api(`/projects/${encodeURIComponent(s)}/${a}/${r}?add_labels=Done&remove_labels=Doing`,{method:"PUT"})}catch(o){this.log(`[business] done label update failed: ${o.message}`)}else if(t.status==="blocked")try{await this.api(`/projects/${encodeURIComponent(s)}/${a}/${r}?add_labels=Blocked`,{method:"PUT"})}catch(o){this.log(`[business] blocked label update failed: ${o.message}`)}if(t.note)try{await this.api(`/projects/${encodeURIComponent(s)}/${a}/${r}/notes`,{method:"POST",body:JSON.stringify({body:t.note})})}catch(o){this.log(`[business] report note failed: ${o.message}`)}}async listAll(e={}){let t=e.sinceDays??30,s=new Date(Date.now()-t*24*36e5).toISOString(),r=new URLSearchParams,i=e.state??"opened";r.set("state",i),r.set("updated_after",s),r.set("scope","all"),r.set("per_page","100"),r.set("with_labels_details","true"),r.set("order_by","updated_at"),r.set("sort","desc"),e.labels?.length&&r.set("labels",e.labels.join(",")),e.milestone&&r.set("milestone",e.milestone),e.search&&r.set("search",e.search);let a=this.projects.length?this.projects:["__ALL__"],o=[];for(let c of a)try{let u=c==="__ALL__"?`/issues?${r.toString()}`:`/projects/${encodeURIComponent(c)}/issues?${r.toString()}`,g=await this.api(u);for(let d of g)o.push(this.mapIssue(d,c))}catch(u){this.log(`[business] GitLab listAll failed on ${c}: ${u.message}`)}let l=o;if(e.notLabels?.length){let c=new Set(e.notLabels);l=l.filter(u=>!(u.labels||[]).some(g=>c.has(g)))}if(e.withoutScopedPrefix){let c=e.withoutScopedPrefix+"::";l=l.filter(u=>!(u.labels||[]).some(g=>g.startsWith(c)))}return l}async setState(e,t){let{project:s,iid:r,type:i}=this.parseId(e),a=i==="issue"?"issues":"merge_requests";await this.api(`/projects/${encodeURIComponent(s)}/${a}/${r}?state_event=${t}`,{method:"PUT"})}async getItem(e){let{project:t,iid:s}=this.parseId(e);try{let r=await this.api(`/projects/${encodeURIComponent(t)}/issues/${s}?with_labels_details=true`);return{...this.mapIssue(r,t),descriptionHtml:r.description_html||void 0,createdAt:r.created_at,author:r.author?{username:r.author.username,name:r.author.name,avatarUrl:r.author.avatar_url}:void 0,allLabels:Array.isArray(r.labels)?typeof r.labels[0]=="object"?r.labels.map(a=>a.name):r.labels:[]}}catch(r){return this.log(`[board] GitLab getItem failed for ${e}: ${r.message}`),null}}async updateItem(e,t){let{project:s,iid:r}=this.parseId(e),i;t.assigneeUsernames&&(i=(await Promise.all(t.assigneeUsernames.map(async u=>{try{let g=await this.api(`/users?username=${encodeURIComponent(u)}`);return Array.isArray(g)&&g[0]?.id?g[0].id:null}catch{return null}}))).filter(u=>typeof u=="number"));let a;if(t.milestoneTitle!==void 0)if(t.milestoneTitle===null||t.milestoneTitle==="")a=0;else try{let c=await this.api(`/projects/${encodeURIComponent(s)}/milestones?title=${encodeURIComponent(t.milestoneTitle)}`);Array.isArray(c)&&c[0]?.id&&(a=c[0].id)}catch(c){this.log(`[board] milestone lookup failed for "${t.milestoneTitle}": ${c.message}`)}let o={};t.title!==void 0&&(o.title=t.title),t.description!==void 0&&(o.description=t.description),t.labels!==void 0&&(o.labels=t.labels.join(",")),t.addLabels?.length&&(o.add_labels=t.addLabels.join(",")),t.removeLabels?.length&&(o.remove_labels=t.removeLabels.join(",")),i!==void 0&&(o.assignee_ids=i),a!==void 0&&(o.milestone_id=a);let l=await this.api(`/projects/${encodeURIComponent(s)}/issues/${r}`,{method:"PUT",body:JSON.stringify(o)});return this.mapIssue(l,s)}async listMembers(){let e=new Map;for(let t of this.projects)try{let s=await this.api(`/projects/${encodeURIComponent(t)}/members/all?per_page=100`);for(let r of s)r.username&&!e.has(r.username)&&e.set(r.username,{username:r.username,name:r.name,avatarUrl:r.avatar_url})}catch(s){this.log(`[board] listMembers failed for ${t}: ${s.message}`)}return[...e.values()].sort((t,s)=>t.username.localeCompare(s.username))}async listMilestones(){let e=new Map;for(let s of this.projects)try{let r=await this.api(`/projects/${encodeURIComponent(s)}/milestones?per_page=100`);for(let i of r)i.title&&!e.has(i.title)&&e.set(i.title,{id:i.id,title:i.title,state:i.state,dueDate:i.due_date})}catch(r){this.log(`[board] listMilestones failed for ${s}: ${r.message}`)}let t=[...e.values()];return t.sort((s,r)=>s.state!==r.state?s.state==="active"?-1:1:s.title.localeCompare(r.title)),t}async create(e){let t=e.projectHint||this.projects[0];if(!t)throw new Error("GitLabWorkSource.create requires projectHint or configured projects");let s,r=e.assigneeUsernames?.length?e.assigneeUsernames:e.assignee?(this.agentUsernames[e.assignee]||[]).slice(0,1):[];r.length&&(s=(await Promise.all(r.map(async c=>{try{let u=await this.api(`/users?username=${encodeURIComponent(c)}`);return Array.isArray(u)&&u[0]?.id?u[0].id:null}catch(u){return this.log(`[board] user lookup failed for ${c}: ${u.message}`),null}}))).filter(c=>typeof c=="number"));let i;if(e.milestoneTitle)try{let l=await this.api(`/projects/${encodeURIComponent(t)}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);Array.isArray(l)&&l[0]?.id&&(i=l[0].id)}catch(l){this.log(`[board] milestone lookup failed for "${e.milestoneTitle}": ${l.message}`)}let a={title:e.title,description:e.description,labels:(e.labels||[]).join(",")};s?.length&&(a.assignee_ids=s),i!==void 0&&(a.milestone_id=i);let o=await this.api(`/projects/${encodeURIComponent(t)}/issues`,{method:"POST",body:JSON.stringify(a)});return this.mapIssue(o,t)}async transition(e,t,s){await this.transitionMany(e,t?[t]:[],s?[s]:[])}async transitionMany(e,t,s){let{project:r,iid:i,type:a}=this.parseId(e),o=a==="issue"?"issues":"merge_requests",l=new URLSearchParams;t.length&&l.set("add_labels",t.join(",")),s.length&&l.set("remove_labels",s.join(",")),l.toString()&&await this.api(`/projects/${encodeURIComponent(r)}/${o}/${i}?${l.toString()}`,{method:"PUT"})}parseId(e){let s=e.replace(/^gitlab:/,"").split(":"),r=s.pop(),i=s.pop()==="mr"?"mr":"issue";return{project:s.join(":"),type:i,iid:r}}};function Nr(n,e,t){let s=n.workSource;switch(s.type){case"backlog":return new se(s.path,e,t);case"wiki":return new ie(s.path,s.glob);case"gitlab":{let r=e.channels.gitlab;if(!r?.token)throw new Error("business.workSource.type=gitlab requires channels.gitlab.token");let i={};for(let o of r.agentMappings)o.gitlabUsernames.length&&(i[o.agentId]=o.gitlabUsernames);let a=s.projects.length?s.projects:r.routes.map(o=>o.project);return new oe(r.host,r.token,a,i,t)}}}var ae="unmapped";function le(n,e=[]){if(!n)return ae;let t=e.find(r=>r.id===n);if(t?.client)return t.client;let s=n.indexOf("/");return s>0?n.slice(0,s):n}function Sn(n){let e=new Map,t=n.projects??[],s=n.orgChart??{};for(let i of t)i.pm&&(e.has(i.pm)||e.set(i.pm,le(i.id,t)));let r=(i,a=new Set)=>{if(e.has(i))return e.get(i);if(a.has(i))return;a.add(i);let o=s[i]?.reportsTo;if(!o)return;let l=r(o,a);return l&&e.set(i,l),l};for(let i of Object.keys(s))r(i);return e}function $n(n,e,t=[]){if(!t.length)return;let s=t.filter(r=>!r.channel||r.channel===n);return s.find(r=>r.chatId&&e.chatId&&r.chatId===e.chatId)??s.find(r=>r.username&&e.username&&r.username===e.username)??s.find(r=>r.senderId&&e.senderId&&r.senderId===e.senderId)??s.find(r=>r.channel&&!r.chatId&&!r.username&&!r.senderId)}function Wr(n,e){let t=$n(n.channel,{chatId:n.chatId,username:n.username},e.contactMap);if(t)return t.client;if(n.project)return le(n.project,e.projects);if(n.agentId){let s=Sn(e).get(n.agentId);if(s)return s}return ae}function zr(n,e){let t=String(n||"").split(":");if(t.length<3)return{agentId:e};let[s,r,...i]=t,a=i.join(":"),o={agentId:e||s,channel:r};return r==="gitlab"||r==="github"?o.project=a.split(":")[0]:r==="cron"||r==="api"||(o.chatId=a.split("@")[0]),o}var In=n=>n===ae?"internal":"client";function vn(n,e){let t=e.clients?.[n];return{id:n,name:t?.name||n,kind:t?.kind??In(n),respondWithinMinutes:An(t?.respondWithin),standing:t?.standing??[],declared:!!t}}function Hr(n){let e=new Set;for(let t of n.projects??[])e.add(le(t.id,n.projects));for(let t of n.contactMap??[])e.add(t.client);for(let t of Object.keys(n.clients??{}))e.add(t);return[...e].sort().map(t=>vn(t,n))}function An(n){let e=/^(\d+)\s*([mhd])$/.exec(String(n??"").trim());if(!e)return;let t=Number(e[1]);return e[2]==="m"?t:e[2]==="h"?t*60:t*1440}var Rn=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n/i,_n=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*```[ \t]*(?=\n|$)/gi;function qr(n){if(!n||!n.includes("agentx:ui"))return{cleanText:n};let e=[...n.matchAll(_n)];if(e.length===0)return{cleanText:n};let t=e[e.length-1],s=t[2],r=Dn(s);if(!r)return{cleanText:n};let i=t.index??0,a=t[1]??"";return{cleanText:(n.slice(0,i)+a+n.slice(i+t[0].length)).trim(),ui:r}}function Jr(n){if(!n||!n.includes("agentx:ui"))return n;let e=Rn.exec(n);return e?n.slice(0,e.index).trimEnd():n}function Dn(n){let e;try{e=JSON.parse(n)}catch{return null}if(!e||typeof e!="object")return null;let t={};if(Array.isArray(e.buttons)){let s=[],r=[];for(let i of e.buttons)!i||typeof i.label!="string"||(typeof i.url=="string"&&/^https?:\/\//i.test(i.url)?s.push({label:i.label,url:i.url}):i.action!=null&&r.push(i.label));s.length&&(t.buttons=s),r.length&&(t.skippedActions=r)}if(e.poll&&typeof e.poll=="object"){let s=e.poll.question,r=e.poll.options;typeof s=="string"&&s.trim()&&Array.isArray(r)&&r.filter(i=>typeof i=="string").length>=2&&(t.poll={question:s,options:r.filter(i=>typeof i=="string"),multiple:e.poll.multiple===!0})}if(e.media&&typeof e.media=="object"){let{type:s,url:r,caption:i}=e.media;["image","document","audio","video"].includes(s)&&typeof r=="string"&&r&&(t.media={type:s,url:r,...typeof i=="string"?{caption:i}:{}})}return!t.buttons&&!t.poll&&!t.media&&!t.skippedActions?null:t}import{existsSync as x,readFileSync as ge,writeFileSync as fe,mkdirSync as z,readdirSync as de,rmSync as Cn,statSync as I}from"fs";import{resolve as nt,relative as Tn,dirname as me,join as R,extname as E,basename as pe}from"path";var w=200*1024,rt=new Set([".md",".markdown",".txt"]),C=new Set([".md",".markdown",".txt",".json",".jsonc",".yaml",".yml",".toml",".sh",".bash",".zsh",".py",".js",".mjs",".ts",".tsx",".jsx",".css",".html",".lock",".cfg",".ini",".env",".gitignore"]),jn=6,En=new Set(["CLAUDE.md","SOUL.md","IDENTITY.md","PERSONA.md","AGENT.md","BOOTSTRAP.md"]);function A(n,e){if(!n)throw new Error("Agent workspace is not configured.");let t=nt(n);if(x(t)||z(t,{recursive:!0}),!e||e.startsWith("/")||e.match(/^[a-zA-Z]:/))throw new Error(`Path must be relative to the workspace: ${e}`);let s=nt(t,e);if(Tn(t,s).startsWith(".."))throw new Error(`Path escapes the workspace: ${e}`);return s}function st(n){let e=E(n).toLowerCase();if(!rt.has(e))throw new Error(`Only text files (.md, .markdown, .txt) can be edited from the admin panel (got ${e}).`)}function ce(n,e){let t=n.split(/\r?\n/).find(s=>s.trim().startsWith("#"));return t&&t.replace(/^#+\s*/,"").trim().slice(0,120)||e}function Yr(n){let e=A(n,"."),t=[],s=new Set,r=[];try{r=de(e)}catch{}for(let o of En){let l=R(e,o);if(x(l)&&I(l).isFile()){let c=I(l).size,u=c>0&&c<w?ue(l):"";t.push({path:o,title:ce(u,o),size:c,exists:!0}),s.add(o)}else t.push({path:o,title:o,size:0,exists:!1}),s.add(o)}for(let o of r){if(s.has(o))continue;let l=R(e,o);try{let c=I(l);if(!c.isFile()||!rt.has(E(o).toLowerCase()))continue;let u=c.size>0&&c.size<w?ue(l):"";t.push({path:o,title:ce(u,o),size:c.size,exists:!0})}catch{}}let i=[],a=R(e,".claude","skills");if(x(a))try{for(let o of de(a)){let l=R(a,o),c;try{c=I(l)}catch{continue}if(!c.isDirectory())continue;let u=R(l,"SKILL.md");if(!x(u))continue;let g=I(u),d=g.size<w?ue(u):"";i.push({slug:o,title:ce(d,o),size:g.size,path:`.claude/skills/${o}/SKILL.md`})}}catch{}return i.sort((o,l)=>o.slug.localeCompare(l.slug)),{identity:t,skills:i,workspace:e}}function ue(n){try{return ge(n,"utf-8")}catch{return""}}function Qr(n,e){let t=A(n,e);if(st(t),!x(t))return{path:e,content:""};if(I(t).size>w)throw new Error(`File is too large to edit in the admin panel (> ${w/1024} KB).`);return{path:e,content:ge(t,"utf-8")}}function Zr(n,e,t){let s=A(n,e);st(s);let r=Buffer.from(t,"utf-8");if(r.length>w)throw new Error(`File too large (${r.length} > ${w} bytes).`);return z(me(s),{recursive:!0}),fe(s,r),{path:e,bytes:r.length}}function es(n,e,t={}){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error("Skill slug must be lowercase (letters, digits, -, _) and start with a letter or digit.");let s=`.claude/skills/${e}/SKILL.md`,r=A(n,s);if(x(r))throw new Error(`Skill "${e}" already exists.`);z(me(r),{recursive:!0});let i=t.content?.trim()?t.content:On(e,t.title);return fe(r,i),{slug:e,path:s}}function ts(n,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let t=A(n,`.claude/skills/${e}`);if(!x(t))throw new Error(`Skill "${e}" not found.`);if(!I(t).isDirectory())throw new Error(`Skill path is not a directory: ${e}`);return Cn(t,{recursive:!0,force:!0}),{slug:e}}function ns(n,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let t=A(n,`.claude/skills/${e}`);if(!x(t))throw new Error(`Skill "${e}" not found.`);let s=[];return r(t,"",0,s),s.sort((i,a)=>i.kind!==a.kind?i.kind==="dir"?-1:1:i.path.localeCompare(a.path)),s;function r(i,a,o,l){if(o>jn)return;let c=[];try{c=de(i)}catch{return}for(let u of c){if(u==="node_modules"||u===".git")continue;let g=R(i,u),d=a?`${a}/${u}`:u,f;try{f=I(g)}catch{continue}if(f.isDirectory())l.push({path:`${d}/`,kind:"dir",size:0,editable:!1}),r(g,d,o+1,l);else if(f.isFile()){let m=E(u).toLowerCase(),h=C.has(m)||C.has(u.toLowerCase());l.push({path:d,kind:"file",size:f.size,editable:h&&f.size<w})}}}}function rs(n,e,t){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);if(!t||t.includes(".."))throw new Error(`Invalid file path: ${t}`);let s=A(n,`.claude/skills/${e}/${t}`);if(!x(s)||!I(s).isFile())throw new Error(`File not found: ${t}`);let r=E(s).toLowerCase(),i=pe(s).toLowerCase();if(!C.has(r)&&!C.has(i))throw new Error(`File type not editable: ${t}`);if(I(s).size>w)throw new Error(`File too large to edit (> ${w/1024} KB): ${t}`);return{path:t,content:ge(s,"utf-8")}}function ss(n,e,t,s){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);if(!t||t.includes(".."))throw new Error(`Invalid file path: ${t}`);let r=A(n,`.claude/skills/${e}/${t}`),i=E(r).toLowerCase(),a=pe(r).toLowerCase();if(!C.has(i)&&!C.has(a))throw new Error(`File type not editable: ${t}`);let o=Buffer.from(s,"utf-8");if(o.length>w)throw new Error(`File too large (${o.length} > ${w} bytes).`);return z(me(r),{recursive:!0}),fe(r,o),{path:t,bytes:o.length}}function is(n,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let t=A(n,`.claude/skills/${e}`);if(!x(t))throw new Error(`Skill "${e}" not found.`);let s=r=>x(R(t,r));return s("pnpm-lock.yaml")?{manager:"pnpm",file:"pnpm-lock.yaml",command:"pnpm install"}:s("yarn.lock")?{manager:"yarn",file:"yarn.lock",command:"yarn install"}:s("package.json")?{manager:"npm",file:"package.json",command:"npm install"}:s("requirements.txt")?{manager:"pip",file:"requirements.txt",command:"pip install -r requirements.txt"}:s("Gemfile")?{manager:"bundle",file:"Gemfile",command:"bundle install"}:{manager:null,file:null,command:null}}function On(n,e){return`# ${e?.trim()||n}
14
-
15
- Describe what this skill does and when the agent should use it. Keep it under ~5 lines \u2014 the agent reads this to decide whether to invoke the skill.
16
-
17
- ## When to use
18
- - Trigger condition 1
19
- - Trigger condition 2
20
-
21
- ## How to use
22
- Document the arguments, commands, or files the skill expects. Example:
23
-
24
- \`\`\`bash
25
- # Example invocation
26
- claude-code ${pe(n)} --arg value
27
- \`\`\`
28
- `}ct();var it={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function ot(n){return{...it,...n??{},regions:{...n?.regions??{}},buffer:{...it.buffer,...n?.buffer??{}}}}function ls(n){try{return ot(he(n).screen)}catch{return ot(void 0)}}var Ln=/^[a-z][\w-]*$/,at=["window","screen","menubar","notifications"];function O(n,e,t,s){let r=Number(n);if(n===""||n===null||!Number.isFinite(r)||!t(r))throw new Error(`${e} must be ${s}`);return r}var H=(n,e)=>O(n,e,t=>Number.isInteger(t)&&t>0,"a whole number above 0");function lt(n){let e=typeof n=="string"?n.split(",").map(Number):[n?.x,n?.y,n?.width,n?.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 cs(n,e){let t={...n??{}};if("maxPixels"in e&&(t.maxPixels=H(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(t.timeoutMs=H(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(t.intervalMs=H(e.intervalMs,"intervalMs")),"stableMs"in e&&(t.stableMs=O(e.stableMs,"stableMs",r=>Number.isInteger(r)&&r>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(t.changeThreshold=O(e.changeThreshold,"changeThreshold",r=>r>=0&&r<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let r={...t.regions??{}};for(let[i,a]of Object.entries(e.regions)){if(!Ln.test(i))throw new Error(`region name "${i}" must be lowercase letters, digits, - or _`);a===null?delete r[i]:r[i]=lt(a)}t.regions=r}if(e.buffer&&typeof e.buffer=="object"){let r=e.buffer,i={...t.buffer??{}};"enabled"in r&&(i.enabled=!!r.enabled),"seconds"in r&&(i.seconds=O(r.seconds,"buffer.seconds",a=>a>0&&a<=120,"above 0 and at most 120")),"fps"in r&&(i.fps=O(r.fps,"buffer.fps",a=>a>0&&a<=10,"above 0 and at most 10")),"maxPixels"in r&&(i.maxPixels=H(r.maxPixels,"buffer.maxPixels")),"region"in r&&(i.region=String(r.region).trim()),t.buffer=i}let s=t.buffer?.region;if(s!==void 0&&!at.includes(s)&&!t.regions?.[s])try{lt(s)}catch{throw new Error(`buffer.region "${s}" is not a region \u2014 use ${[...at,...Object.keys(t.regions??{})].join(", ")}, or x,y,w,h`)}return t}export{Re as a,Fn as b,le as c,Sn as d,$n as e,Wr as f,zr as g,Hr as h,qr as i,Jr as j,k,Wn as l,Le as m,Jn as n,Gn as o,Ue as p,Be as q,T as r,Qn as s,Zn as t,er as u,tr as v,nr as w,B as x,ar as y,br as z,yr as A,wr as B,xr as C,Sr as D,$r as E,Ir as F,vr as G,Rr as H,_r as I,M as J,Er as K,Ze as L,Z as M,oe as N,Nr as O,Yr as P,Qr as Q,Zr as R,es as S,ts as T,ns as U,rs as V,ss as W,is as X,it as Y,ot as Z,ls as _,at as $,cs as aa};
29
- //# sourceMappingURL=chunk-PAOV37KQ.js.map