agentix-cli 0.64.0 → 0.65.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.
Files changed (28) hide show
  1. package/dist/{agent-3M5EI4S6.js → agent-HUKCS3AK.js} +2 -2
  2. package/dist/{board-dashboard-JBRO26JC.js → board-dashboard-S4V4WR2N.js} +225 -170
  3. package/dist/{board-dashboard-JBRO26JC.js.map → board-dashboard-S4V4WR2N.js.map} +1 -1
  4. package/dist/{chunk-KZDG26LI.js → chunk-AVDWFQZ5.js} +2 -2
  5. package/dist/{chunk-NNXHRO7H.js → chunk-ECBKTFTL.js} +17 -17
  6. package/dist/chunk-ECBKTFTL.js.map +1 -0
  7. package/dist/{chunk-S2VETB7B.js → chunk-EOKOGQZG.js} +26 -26
  8. package/dist/chunk-EOKOGQZG.js.map +1 -0
  9. package/dist/{chunk-HYKILAEJ.js → chunk-HSJRI3NW.js} +183 -183
  10. package/dist/chunk-HSJRI3NW.js.map +1 -0
  11. package/dist/{chunk-VVQDKHF5.js → chunk-LEFRNHZF.js} +4 -4
  12. package/dist/{chunk-VUB6XYWD.js → chunk-OTTAKMGC.js} +54 -54
  13. package/dist/chunk-OTTAKMGC.js.map +1 -0
  14. package/dist/cli.js +1 -1
  15. package/dist/index.js +1 -1
  16. package/dist/{program-FSRL275V.js → program-DZCKFNHD.js} +2 -2
  17. package/dist/registry-P7IAAFCX.js +2 -0
  18. package/package.json +1 -1
  19. package/dist/chunk-HYKILAEJ.js.map +0 -1
  20. package/dist/chunk-NNXHRO7H.js.map +0 -1
  21. package/dist/chunk-S2VETB7B.js.map +0 -1
  22. package/dist/chunk-VUB6XYWD.js.map +0 -1
  23. package/dist/registry-T4R7LVFZ.js +0 -2
  24. /package/dist/{agent-3M5EI4S6.js.map → agent-HUKCS3AK.js.map} +0 -0
  25. /package/dist/{chunk-KZDG26LI.js.map → chunk-AVDWFQZ5.js.map} +0 -0
  26. /package/dist/{chunk-VVQDKHF5.js.map → chunk-LEFRNHZF.js.map} +0 -0
  27. /package/dist/{program-FSRL275V.js.map → program-DZCKFNHD.js.map} +0 -0
  28. /package/dist/{registry-T4R7LVFZ.js.map → registry-P7IAAFCX.js.map} +0 -0
@@ -1,16 +1,16 @@
1
- import{g as Xe,h as qe,i as Je,k as Ye,l as Ze}from"./chunk-I2SD4XZ6.js";import{t as tt,u as nt}from"./chunk-XT3E5MLX.js";import{d as Qe,e as et}from"./chunk-AQASR6KR.js";import{b as ie,p as Ge,q as H,r as oe}from"./chunk-NNXHRO7H.js";import{q as Ke}from"./chunk-BHE5TJSN.js";import{w as ze,z as In}from"./chunk-OVF37EXJ.js";import{existsSync as An,readdirSync as _n,readFileSync as Rn,statSync as Cn}from"fs";import{resolve as Tn}from"path";function rt(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 ki(t,e=1e3){if(!An(t))return[];let n=_n(t).filter(i=>i.endsWith(".jsonl")).map(i=>{let o=Tn(t,i);return{path:o,mtime:Cn(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=En(i,o);z.set(i,{mtime:o,summary:c}),c&&r.push(c)}return r}function En(t,e){try{let n=Rn(t,"utf-8").split(`
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 Dn={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},w={routines:200,summary:160,filters:6,filterValue:60,text:120},Ln=(t,e,n)=>{try{return Ke(t,e,n)}catch{return null}},st=864e5;function $i(t){let e=t.now??Date.now(),n={...Dn,...t.thresholds},s=t.nextFire??Ln,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?ae(a.nextRun)??ae(s(a.schedule,new Date(e),l)):null,lastRun:d?{at:d.startedAt,status:d.status,summary:Vn(d.status==="success"?void 0:d.errorSummary,w.summary)}:null,lastSuccessAt:c.find(f=>f.status==="success")?.startedAt??null,consecutiveFailures:it(u),sampledRuns:c.length,flags:[],attention:null};g.flags=ot(g,u,a.schedule,l,null,e,n,s),r.push(at(g))}let i=new Map(rt(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:On(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:Mn(l.filter,a)},agent:Nn(a),enabled:d,state:u,nextRunAt:h&&d&&y?ae(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:it(f),sampledRuns:g.length,flags:[],attention:null},W=Date.parse(a.updated||a.created||"");E.flags=h?ot(E,f,y,R,Number.isFinite(W)?W:null,e,n,s):Pn(E,i.get(a.id)?.state==="dormant",Number.isFinite(W)?W:null,e,n),r.push(at(E))}return r.sort(jn).slice(0,w.routines)}function it(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 ot(t,e,n,s,r,i,o,a){let c=[],l=e.length?e[0].at:null;if(!t.enabled){let g=ct(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 Pn(t,e,n,s,r){let i=[],o=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=ct(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 ct(t,e,n,s){let r=Math.max(t??0,e??0);return r&&n-r<s.disabledDays*st?null:{reason:"disabled-long",detail:r?`Disabled; no activity for ${Math.floor((n-r)/st)} days`:"Disabled and never ran"}}function at(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 lt={critical:0,warning:1,info:2};function jn(t,e){let n=t.attention?lt[t.attention]:3,s=e.attention?lt[e.attention]:3;return n-s||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function On(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 Nn(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 Mn(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 ae(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 Vn(t,e){return t===void 0?void 0:$(t,e)}import{createHash as Fn,randomBytes as ut}from"crypto";import{existsSync as Un,mkdirSync as Bn,readFileSync as Wn,writeFileSync as Hn}from"fs";import{resolve as zn,dirname as Kn}from"path";var le="agx_live_",Gn=".agentx/tokens.json",dt=class{file;constructor(e=process.cwd(),n=Gn){this.file=zn(e,n)}load(){if(!Un(this.file))return[];try{return JSON.parse(Wn(this.file,"utf-8"))}catch{return[]}}save(e){Bn(Kn(this.file),{recursive:!0}),Hn(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 o of e.scopes)if(!Xn(o))throw new Error(`Invalid scope: ${o}`);let n=ut(32).toString("hex"),s=le+n,r={id:"tok_"+ut(4).toString("hex"),name:e.name.trim(),prefix:le+n.slice(0,4),hash:gt(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(le))return null;let n=gt(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 Ri(t,e){return!!(t.scopes.includes(e)||e.startsWith("agent:")&&t.scopes.includes("agent:*")||e==="dashboard:read"&&t.scopes.includes("dashboard:write"))}function Xn(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 gt(t){return"sha256:"+Fn("sha256").update(t).digest("hex")}function Ci(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 ce,readdirSync as dr,readFileSync as gr}from"fs";import{resolve as L}from"path";import{existsSync as qn,mkdirSync as Jn,readdirSync as Yn,readFileSync as Zn,renameSync as Qn,writeFileSync as er}from"fs";import{resolve as mt}from"path";var ft=["discard","keep","pause","approve"],v={title:120,ask:300,recommend:300,source:500,note:500,pendingPerAgent:25},tr={defaultExpiryDays:3,maxExpiryDays:30};function D(t){return mt(t,".agentx","approvals")}var nr=/^[a-z0-9][a-z0-9-]{0,80}$/;function pt(t){return nr.test(t)}function ht(t,e){if(!pt(e))throw new Error(`invalid card id: ${e}`);return mt(D(t),`${e}.json`)}function rr(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){Jn(D(t),{recursive:!0});let n=ht(t,e.id),s=`${n}.${process.pid}.tmp`;er(s,JSON.stringify(e,null,2)+`
4
- `),Qn(s,n)}function M(t,e){if(!pt(e))return null;try{return JSON.parse(Zn(ht(t,e),"utf-8"))}catch{return null}}function V(t,e){let n=D(t);if(!qn(n))return[];let s=[];for(let r of Yn(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 sr(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 ir(t,e={}){let n=e.now??Date.now(),s=e.settings??tr,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(!ft.includes(c))return{ok:!1,error:`if_silent must be one of ${ft.join(", ")}`};let l=sr(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:rr(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 Li(t,e,n={}){let s=ir(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 yt(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 Pi(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 Oi(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 Ni(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(`
5
- `)}import{mkdirSync as or,readFileSync as ar,renameSync as lr,writeFileSync as cr}from"fs";import{resolve as ur}from"path";function bt(t){return ur(D(t),"_state.json")}function G(t){try{let e=JSON.parse(ar(bt(t),"utf-8"));return{snoozed:e&&typeof e.snoozed=="object"&&e.snoozed?e.snoozed:{},...typeof e?.lastDigest=="string"?{lastDigest:e.lastDigest}:{}}}catch{return{snoozed:{}}}}function kt(t,e){or(D(t),{recursive:!0});let n=bt(t),s=`${n}.${process.pid}.tmp`;cr(s,JSON.stringify(e,null,2)+`
6
- `),lr(s,n)}function wt(t,e,n,s=Date.now()){let r=G(t),i={};for(let[o,a]of Object.entries(r.snoozed))Date.parse(a)>s&&(i[o]=a);i[e]=n.toISOString(),kt(t,{...r,snoozed:i})}function Bi(t,e){kt(t,{...G(t),lastDigest:e})}var St=["card","schedule","memory","wiki"],fr=280;function ue(t,e=fr){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function xt(t){if(t.configPath)return L(t.configPath);let e=[L(t.root,"agentx.json"),L(t.root,".agentx","config.json")];return e.find(n=>ce(n))??e[0]}function de(t){return t.wikiDir?L(t.wikiDir):L(t.root,".agentx","wiki")}function mr(t){return V(t.root,"pending").map(pr)}function pr(t){return{key:`card:${t.id}`,kind:"card",title:t.title,ask:t.ask,yes:`tell ${t.raised_by} yes`,no:`tell ${t.raised_by} no`,recommend:t.recommend,if_silent:t.if_silent,expires:t.expires,...t.source?{source:t.source}:{},raised_by:t.raised_by,created_at:t.created_at}}function hr(t){let e=xt(t);if(!ce(e))return[];let n;try{n=JSON.parse(gr(e,"utf-8"))}catch{return[]}let s=new Date(t.now??Date.now()),r=[];for(let[i,o]of Object.entries(n?.crons??{})){let a=o?.approval;if(!a||a.action!=="create"&&a.action!=="delete")continue;let c=o.timezone||"UTC",l=o.schedule?Xe(o.schedule):"",u=o.schedule?`${l.charAt(0).toLowerCase()}${l.slice(1)} (${o.schedule})`:"no schedule",d=String(o.prompt??o.command??""),g=a.action==="create";r.push({key:`schedule:${i}`,kind:"schedule",title:g?`New schedule "${i}" for ${o.agent??"an agent"}`:`Delete schedule "${i}"`,ask:g?`Let ${o.agent??"the agent"} run this ${u}?`:`Remove the schedule "${i}" (${u})?`,yes:g?"enable it":"remove it",no:g?"drop the request":"keep the schedule",raised_by:String(a.requestedBy??"unknown"),created_at:String(a.requestedAt??""),detail:ue(`${d}${g&&o.schedule?` \xB7 first run ${Je(qe(o.schedule,c,s),c)}`:""}`),more:"agentx schedule list"})}return r}function $t(t){let e=L(t,".agentx","memory");return ce(e)?dr(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function yr(t){let e=$t(t.root);if(e.length===0)return[];let n=new ie(t.root),s=[];for(let r of e)for(let i of n.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:ue(i.content),more:`agentx memory facts held --agent ${r}`});return s}function br(t){let e=t.sources.filter(n=>n.failure);return e.length?e.map(n=>`Recurring failure: ${n.agentId}'s ${n.failure.tool} fails with "${n.failure.errorClass}" in ${n.occurrences??1} sessions (${n.failure.runs} runs).`).join(" "):`${t.sources.length} source(s)${t.occurrences>1?`, seen in ${t.occurrences} sessions`:""}.`}function kr(t){return et(de(t),"pending").map(e=>{let n=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:n.agents.join(", ")||"wiki promote",created_at:e.createdAt,detail:ue(`${br(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}var vt={card:mr,schedule:hr,memory:yr,wiki:kr};function wr(t,e){let n=t.expires?Date.parse(t.expires):1/0,s=e.expires?Date.parse(e.expires):1/0;return n!==s?n-s:(Date.parse(t.created_at)||0)-(Date.parse(e.created_at)||0)}function Zi(t,e={}){let n=t.now??Date.now(),{snoozed:s}=G(t.root),r=[],i=[],o=0;for(let a of e.kinds??St){let c;try{c=vt[a](t)}catch(l){i.push({kind:a,error:String(l?.message??l).slice(0,200)});continue}for(let l of c){let u=s[l.key];if(u&&Date.parse(u)>n){if(!e.includeSnoozed){o++;continue}l.snoozed_until=u}r.push(l)}}return r.sort(wr),{items:r,snoozed:o,errors:i}}function Sr(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),s=t.slice(e+1);return!St.includes(n)||!s?null:{kind:n,ref:s}}function xr(t,e,n){switch(e){case"card":return M(t.root,n)?.status==="pending";case"wiki":return Qe(de(t),n)?.status==="pending";default:return vt[e](t).some(s=>s.key===`${e}:${n}`)}}async function Qi(t,e,n,s={}){let r=Sr(e);if(!r)return{ok:!1,error:`unknown item "${e}": use a key from \`agentx approvals list\``};let{kind:i,ref:o}=r,a=t.now??Date.now(),c=s.by??"operator";if(n==="later"){if(!xr(t,i,o))return{ok:!1,error:`nothing waiting for "${e}"`};let u=s.laterHours&&s.laterHours>0?s.laterHours:24,d=new Date(a+u*36e5);return wt(t.root,e,d,a),{ok:!0,message:`${e} put off until ${d.toISOString()}`}}let l=n==="yes";switch(i){case"card":{let u=yt(t.root,o,l?"yes":"no",{by:c,note:s.note,now:a});return u.ok?{ok:!0,message:`${e}: ${u.card.raised_by} will be told ${l?"yes":"no"}`}:u}case"schedule":{let u=await(l?Ye:Ze)(o,{configPath:xt(t),reload:t.reload});return u.success?{ok:!0,message:u.message}:{ok:!1,error:u.message}}case"memory":{let u=o.indexOf("/");if(u<=0)return{ok:!1,error:"memory keys look like memory:<agent>/<fact-id>"};let d=o.slice(0,u),g=o.slice(u+1);if(!$t(t.root).includes(d))return{ok:!1,error:`no memory for agent "${d}"`};let f=new ie(t.root);return f.held(d).some(m=>m.id===g)?(f.review(d,g,l?"approved":"rejected",c),{ok:!0,message:`${e} ${l?"approved: the agent may use it":"rejected: it stays out of prompts"}`}):{ok:!1,error:`fact "${g}" isn't waiting for review`}}case"wiki":{let u=de(t),d=l?tt(u,o,{by:c,force:s.force,now:a}):nt(u,o,{by:c,reason:s.note,now:a});return d.ok?{ok:!0,message:l?`${d.proposal.article.path} written to the shared wiki`:`${e} rejected`}:d}}}var It=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]);function to(t){return t==="/api/memory"||t.startsWith("/api/memory/")||t==="/approvals"||t.startsWith("/approvals/")||t==="/events/recent"||/^\/agents\/[^/]+\/events$/.test(t)||t==="/traces"||t.startsWith("/traces/")||t==="/voice/history"||t.startsWith("/voice/history/")||t==="/voice/transcribe"||t==="/voice/speak"||t==="/app-files"}function no(t){return t==="/reload"||t==="/api/processes/kill"||t==="/send"||t==="/send/agent"||t==="/send/contact"||t==="/mesh/announce"||t==="/voice/settings"||t==="/voice/preview"||/^\/api\/tasks\/[^/]+\/(cancel|followup)$/.test(t)||/^\/crons\/[^/]+\/enabled$/.test(t)}function ro(t){return It.has(t)}function so(t){if(t.foreignBrowser)return{allowed:!1,reason:"foreign-browser-origin"};if(t.enforcementDisabled)return{allowed:!0,reason:"disabled"};if(It.has(t.remoteAddress))return{allowed:!0,reason:"loopback"};if(t.acceptedTokens.size===0)return{allowed:!0,reason:"no-tokens-configured"};let e=t.authorizationHeader||"",n=e.startsWith("Bearer ")?e.slice(7).trim():"";return n&&t.acceptedTokens.has(n)?{allowed:!0,reason:"token"}:{allowed:!1,reason:"missing-or-invalid-token"}}function io(t,e=process.env){let n=new Set;e.MESH_TOKEN&&n.add(e.MESH_TOKEN);for(let s of t.mesh?.peers||[])s.token&&n.add(s.token);return n}function oo(t,e,n=process.env){let s=i=>i.replace(/\/+$/,"");return(e===s(t.daemonUrl)?t.token:t.daemons.find(i=>s(i.url)===e)?.token)||n.MESH_TOKEN||void 0}function X(t){return(Array.isArray(t)?t[0]:t)?.trim()??""}function $r(t){try{return new URL(t).host.toLowerCase()}catch{return null}}function vr(t=process.env){return new Set((t.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function lo(t,e=vr()){let n=X(t.origin);if(n){if(e.has(n.replace(/\/+$/,"").toLowerCase()))return"same-origin";let r=$r(n),i=[X(t.host),X(t["x-forwarded-host"])].filter(Boolean).map(o=>o.toLowerCase());return r&&i.includes(r)?"same-origin":"foreign"}let s=X(t["sec-fetch-site"]).toLowerCase();return s==="cross-site"||s==="same-site"?"foreign":"none"}function co(t){let e=(t||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}import{readFileSync as fe,writeFileSync as Et,existsSync as me,readdirSync as Lr,statSync as Pr}from"fs";import{resolve as pe,join as jr}from"path";import{existsSync as At,mkdirSync as Ir,readFileSync as Ar,writeFileSync as _t}from"fs";import{dirname as _r,resolve as Rt}from"path";import{z as p}from"zod";var Rr=p.object({type:p.enum(["gitlab","github"]),host:p.string().optional(),project:p.string(),iid:p.number().int().positive(),url:p.string()}),Cr=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:Rr.optional(),importedAt:p.string().optional(),createdAt:p.string(),updatedAt:p.string(),blocker:p.string().optional(),doneNote:p.string().optional()}),Tr=p.object({version:p.literal(1),items:p.array(Cr).default([])}),q=class{constructor(e){this.path=e}jsonPath(){return Rt(process.cwd(),this.path).replace(/\.md$/i,".json")}mdPath(){return Rt(process.cwd(),this.path).replace(/\.json$/i,".md")}exists(){return At(this.jsonPath())}load(){let e=this.jsonPath();if(!At(e))return{version:1,items:[]};let n=Ar(e,"utf-8");try{return Tr.parse(JSON.parse(n))}catch(s){throw new Error(`Backlog file invalid (${e}): ${s.message}`)}}save(e){let n=this.jsonPath();Ir(_r(n),{recursive:!0}),_t(n,JSON.stringify(e,null,2)+`
7
- `),_t(this.mdPath(),this.toMarkdown(e))}list(){return this.load().items}findById(e){return this.list().find(n=>n.id===e)}add(e){let n=this.load();if(n.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 n.items.push(r),this.save(n),r}addMany(e){let n=this.load(),s=new Set(n.items.map(o=>o.id)),r=new Date().toISOString(),i=[];for(let o of e){if(s.has(o.id))continue;let a={...o,labels:o.labels??[],status:o.status??"todo",createdAt:o.createdAt??r,updatedAt:r};n.items.push(a),i.push(a),s.add(a.id)}return i.length&&this.save(n),i}update(e,n){let s=this.load(),r=s.items.findIndex(o=>o.id===e);if(r<0)throw new Error(`backlog item ${e} not found`);let i={...s.items[r],...n,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 n=this.load(),s=n.items.length;return n.items=n.items.filter(r=>r.id!==e),n.items.length===s?!1:(this.save(n),!0)}toMarkdown(e){let n=["# 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,o]of r)if(s[i].length){n.push(`## ${o}`,"");for(let a of s[i]){let c=i==="done"?"x":" ",l=a.assignee?`@${a.assignee} `:"",u=a.estimatedSeconds?` [time: ${Math.round(a.estimatedSeconds/60)}m]`:"",d=a.source?` (${a.source.type}: ${a.source.project}#${a.source.iid})`:"";n.push(`- [${c}] ${l}${a.title}${u}${d}`),a.source?.url&&n.push(` - <${a.source.url}>`),a.labels.length&&n.push(` - labels: ${a.labels.join(", ")}`),a.milestone&&n.push(` - milestone: ${a.milestone}`),a.blocker&&n.push(` - BLOCKED: ${a.blocker}`)}n.push("")}return n.join(`
8
- `)}};function po(t){return`${t.type}:${t.project}:${t.iid}`}function Ct(t,e,n){let s=[];if(e.type==="gitlab"){let r=n.channels.gitlab?.agentMappings??[];for(let i of t){let o=r.find(a=>a.agentId===i);o?.gitlabUsernames?.length?s.push(o.gitlabUsernames[0]):s.push(i)}}else if(e.type==="github"){let r=n.channels.github?.agentMappings??[];for(let i of t){let o=r.find(a=>a.agentId===i);o?.githubUsernames?.length?s.push(o.githubUsernames[0]):s.push(i)}}return s}async function ge(t,e,n,s=()=>{}){return t.source?t.source.type==="gitlab"?Er(t.source,e,n,s):t.source.type==="github"?Dr(t.source,e,n,s):{ok:!1,error:`unknown source.type ${t.source.type}`,attempts:[]}:{ok:!0,attempts:[]}}async function Er(t,e,n,s){let r=n.channels.gitlab,i=r?.token,o=r?.host||(t.host?`https://${t.host}`:void 0);if(!i||!o)return{ok:!1,error:"gitlab token/host not configured",attempts:[]};let a=[],c=async(f,m={})=>fetch(`${o}/api/v4${f}`,{...m,headers:{"PRIVATE-TOKEN":i,"Content-Type":"application/json",...m.headers||{}}}),l=encodeURIComponent(t.project),u;e.assigneeUsernames!==void 0&&(u=(await Promise.all(e.assigneeUsernames.map(async m=>{try{let h=await fetch(`${o}/api/v4/users?username=${encodeURIComponent(m)}`,{headers:{"PRIVATE-TOKEN":i}});if(!h.ok)return null;let y=await h.json();return Array.isArray(y)&&y[0]?.id?y[0].id:null}catch{return null}}))).filter(m=>typeof m=="number"));let d;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")d=0;else try{let f=await c(`/projects/${l}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);if(f.ok){let m=await f.json();Array.isArray(m)&&m[0]?.id&&(d=m[0].id)}}catch(f){s(`[backlog-sync] milestone lookup failed: ${f.message}`)}let g={};if(e.title!==void 0&&(g.title=e.title),e.description!==void 0&&(g.description=e.description),e.labels!==void 0&&(g.labels=e.labels.join(",")),e.addLabels?.length&&(g.add_labels=e.addLabels.join(",")),e.removeLabels?.length&&(g.remove_labels=e.removeLabels.join(",")),u!==void 0&&(g.assignee_ids=u),d!==void 0&&(g.milestone_id=d),e.state&&(g.state_event=e.state==="closed"?"close":"reopen"),Object.keys(g).length)try{let f=await c(`/projects/${l}/issues/${t.iid}`,{method:"PUT",body:JSON.stringify(g)});if(a.push({kind:"PUT issue",ok:f.ok,status:f.status}),!f.ok){let m=await f.text().catch(()=>"");return{ok:!1,attempts:a,error:`PUT issue ${f.status}: ${m.slice(0,200)}`,url:t.url}}}catch(f){return a.push({kind:"PUT issue",ok:!1,error:f.message}),{ok:!1,attempts:a,error:f.message,url:t.url}}if(e.note)try{let f=await c(`/projects/${l}/issues/${t.iid}/notes`,{method:"POST",body:JSON.stringify({body:e.note})});a.push({kind:"POST note",ok:f.ok,status:f.status})}catch(f){a.push({kind:"POST note",ok:!1,error:f.message})}return{ok:a.every(f=>f.ok),attempts:a,url:t.url}}async function Dr(t,e,n,s){let i=n.channels.github?.token;if(!i)return{ok:!1,error:"github token not configured",attempts:[]};let o=[],a=async(g,f={})=>fetch(`https://api.github.com${g}`,{...f,headers:{Authorization:`Bearer ${i}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",...f.headers||{}}}),c=t.project,l;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")l=null;else try{let g=await a(`/repos/${c}/milestones?state=all&per_page=100`);if(g.ok){let f=await g.json(),m=Array.isArray(f)?f.find(h=>h.title===e.milestoneTitle):null;m?.number&&(l=m.number)}}catch(g){s(`[backlog-sync] github milestone lookup failed: ${g.message}`)}let u;if(e.labels!==void 0)u=e.labels;else if(e.addLabels?.length||e.removeLabels?.length)try{let g=await a(`/repos/${c}/issues/${t.iid}`);if(g.ok){let f=await g.json(),m=Array.isArray(f.labels)?f.labels.map(y=>typeof y=="string"?y:y.name):[],h=new Set([...m,...e.addLabels??[]]);for(let y of e.removeLabels??[])h.delete(y);u=[...h]}}catch(g){s(`[backlog-sync] github label fetch failed: ${g.message}`)}let d={};if(e.title!==void 0&&(d.title=e.title),e.description!==void 0&&(d.body=e.description),u!==void 0&&(d.labels=u),e.assigneeUsernames!==void 0&&(d.assignees=e.assigneeUsernames),l!==void 0&&(d.milestone=l),e.state&&(d.state=e.state),Object.keys(d).length)try{let g=await a(`/repos/${c}/issues/${t.iid}`,{method:"PATCH",body:JSON.stringify(d)});if(o.push({kind:"PATCH issue",ok:g.ok,status:g.status}),!g.ok){let f=await g.text().catch(()=>"");return{ok:!1,attempts:o,error:`PATCH issue ${g.status}: ${f.slice(0,200)}`,url:t.url}}}catch(g){return o.push({kind:"PATCH issue",ok:!1,error:g.message}),{ok:!1,attempts:o,error:g.message,url:t.url}}if(e.note)try{let g=await a(`/repos/${c}/issues/${t.iid}/comments`,{method:"POST",body:JSON.stringify({body:e.note})});o.push({kind:"POST comment",ok:g.ok,status:g.status})}catch(g){o.push({kind:"POST comment",ok:!1,error:g.message})}return{ok:o.every(g=>g.ok),attempts:o,url:t.url}}var he=/^(\s*)-\s*\[( |x|X)\]\s*(.*)$/,J=/@([a-z0-9_-]+)/i,Tt=/\[time:\s*([0-9hm\s]+)\]/i;function Or(t){let e=t.match(/(\d+)\s*h/i),n=t.match(/(\d+)\s*m/i);return(e?parseInt(e[1],10)*3600:0)+(n?parseInt(n[1],10)*60:0)}var ye=class{constructor(e,n,s=()=>{}){this.path=e;this.daemon=n;this.log=s;this.store=new q(this.path)}type="backlog";capabilities={listAll:!0,create:!1,transition:!1,labels:!0,search:!1};store;getStore(){return this.store}readMd(){let e=pe(process.cwd(),this.path);return me(e)?fe(e,"utf-8").split(`
9
- `):[]}writeMd(e){let n=pe(process.cwd(),this.path);Et(n,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 n=this.readMd(),s=[];for(let r=0;r<n.length;r++){let i=n[r].match(he);if(!i||i[2].toLowerCase()==="x")continue;let a=i[3],c=a.match(J);if(c&&c[1].toLowerCase()!==e.toLowerCase())continue;let l=a.match(Tt),u=a.replace(J,"").replace(Tt,"").trim();s.push({id:`backlog:${r}`,title:u||`Task at line ${r+1}`,assignee:c?c[1]:void 0,estimatedSeconds:l?Or(l[1]):void 0,priority:r})}return s}async listAll(e={}){return this.store.exists()?this.store.list().map(n=>this.toWorkItem(n)):[]}async claim(e,n){if(!this.store.exists())return;let s=this.store.findById(n);if(!s)return;let r=this.store.update(n,{assignee:s.assignee||e,status:"doing"});if(r.source&&this.daemon){let i=Ct([r.assignee||e],r.source,this.daemon);ge(r,{assigneeUsernames:i,addLabels:["Doing"],removeLabels:["To Do"]},this.daemon,this.log).catch(o=>this.log(`[backlog-sync] claim failed for ${n}: ${o?.message??o}`))}}async report(e,n){if(this.store.exists()&&this.store.findById(e)){let a={};n.status==="done"?a.status="done":n.status==="blocked"?(a.status="blocked",a.blocker=n.blocker||n.note||void 0):n.status==="in-progress"&&(a.status="doing"),n.timeSeconds&&(a.estimatedSeconds=n.timeSeconds);let c=this.store.update(e,a);if(c.source&&this.daemon){let l={};n.status==="done"?(l.addLabels=["Done"],l.removeLabels=["Doing"]):n.status==="blocked"&&(l.addLabels=["Blocked"]),n.note&&(l.note=n.note),Object.keys(l).length&&ge(c,l,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(he))throw new Error(`backlog line ${s} not a checkbox`);if(n.status==="done"){r[s]=i.replace(/- \[ \]/,"- [x]");let a=n.timeSeconds?` <!-- done by agent, ${Math.round(n.timeSeconds/60)}m -->`:" <!-- done by agent -->";r.splice(s+1,0,a)}else n.status==="blocked"?r.splice(s+1,0,` <!-- BLOCKED: ${n.blocker||n.note||"?"} -->`):n.note&&r.splice(s+1,0,` <!-- ${n.note.replace(/-->/g,"\u2014 >")} -->`);this.writeMd(r)}toWorkItem(e){let n={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:n,milestone:e.milestone,url:e.source?.url,updatedAt:e.updatedAt,state:e.status==="done"?"closed":"opened"}}},be=class{constructor(e,n){this.root=e;this.glob=n}type="wiki";capabilities={listAll:!1,create:!1,transition:!1,labels:!1,search:!1};walk(e,n){if(me(e))for(let s of Lr(e)){let r=jr(e,s);Pr(r).isDirectory()?this.walk(r,n):s.endsWith(".md")&&n.push(r)}}async listOpen(e){let n=[];this.walk(pe(process.cwd(),this.root),n);let s=[];for(let r of n){let i=fe(r,"utf-8").split(`
11
- `);for(let o=0;o<i.length;o++){let a=i[o].match(he);if(!a||a[2].toLowerCase()==="x")continue;let c=a[3].match(J);!c||c[1].toLowerCase()!==e.toLowerCase()||s.push({id:`wiki:${r}:${o}`,title:a[3].replace(J,"").trim(),assignee:c[1],priority:o})}}return s}async claim(){}async report(e,n){let s=e.split(":"),r=parseInt(s[s.length-1],10),i=s.slice(1,-1).join(":");if(!me(i))return;let o=fe(i,"utf-8").split(`
12
- `);n.status==="done"&&o[r]&&(o[r]=o[r].replace(/- \[ \]/,"- [x]"),Et(i,o.join(`
13
- `)))}},ke=class{constructor(e,n,s,r,i){this.host=e;this.token=n;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[n,s]of Object.entries(this.agentUsernames))if(s.some(r=>r.toLowerCase()===e.toLowerCase()))return n}mapIssue(e,n){let s=e.references?.full?.split("#")[0]||n,r=[],i;Array.isArray(e.labels)&&(e.labels.length&&typeof e.labels[0]=="object"?(i=e.labels.map(l=>({name:l.name,color:l.color,text_color:l.text_color})),r=i.map(l=>l.name)):r=e.labels);let a=(Array.isArray(e.assignees)&&e.assignees.length?e.assignees:e.assignee?[e.assignee]:[]).map(l=>({username:l.username,name:l.name,avatarUrl:l.avatar_url})),c=a[0]?.username;return{id:`gitlab:${s}:issue:${e.iid}`,title:e.title,description:e.description||void 0,assignee:c?this.usernameToAgent(c)||c:void 0,assignees:a,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,n={}){let s=await fetch(`${this.host}/api/v4${e}`,{...n,headers:{"PRIVATE-TOKEN":this.token,"Content-Type":"application/json",...n.headers||{}}});if(!s.ok)throw new Error(`GitLab ${s.status}: ${await s.text().catch(()=>"")}`);return s.json()}async listOpen(e){let n=this.agentUsernames[e]||[];if(!n.length)return[];let s=[],r=this.projects.length?this.projects:["__ALL__"];for(let i of n)for(let o of r)try{let a=`assignee_username=${encodeURIComponent(i)}&state=opened&scope=all&per_page=20`,c=o==="__ALL__"?`/issues?${a}`:`/projects/${encodeURIComponent(o)}/issues?${a}`,l=await this.api(c);for(let u of l){let d=this.mapIssue(u,o);d.assignee=e,s.push(d)}}catch(a){this.log(`[business] GitLab listOpen failed for ${i} on ${o}: ${a.message}`)}return s}async claim(e,n){let{project:s,iid:r,type:i}=this.parseId(n),o=`/projects/${encodeURIComponent(s)}/${i==="issue"?"issues":"merge_requests"}/${r}?add_labels=Doing&remove_labels=To Do`;try{await this.api(o,{method:"PUT"})}catch(a){this.log(`[business] claim label update failed: ${a.message}`)}}async report(e,n){let{project:s,iid:r,type:i}=this.parseId(e),o=i==="issue"?"issues":"merge_requests";if(n.timeSeconds&&n.timeSeconds>0){let a=Math.max(1,Math.round(n.timeSeconds/60)),c=a>=60?`${Math.floor(a/60)}h${a%60?` ${a%60}m`:""}`:`${a}m`;try{await this.api(`/projects/${encodeURIComponent(s)}/${o}/${r}/add_spent_time?duration=${encodeURIComponent(c)}`,{method:"POST"})}catch(l){this.log(`[business] add_spent_time failed: ${l.message}`)}}if(n.status==="done")try{await this.api(`/projects/${encodeURIComponent(s)}/${o}/${r}?add_labels=Done&remove_labels=Doing`,{method:"PUT"})}catch(a){this.log(`[business] done label update failed: ${a.message}`)}else if(n.status==="blocked")try{await this.api(`/projects/${encodeURIComponent(s)}/${o}/${r}?add_labels=Blocked`,{method:"PUT"})}catch(a){this.log(`[business] blocked label update failed: ${a.message}`)}if(n.note)try{await this.api(`/projects/${encodeURIComponent(s)}/${o}/${r}/notes`,{method:"POST",body:JSON.stringify({body:n.note})})}catch(a){this.log(`[business] report note failed: ${a.message}`)}}async listAll(e={}){let n=e.sinceDays??30,s=new Date(Date.now()-n*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 o=this.projects.length?this.projects:["__ALL__"],a=[];for(let l of o)try{let u=l==="__ALL__"?`/issues?${r.toString()}`:`/projects/${encodeURIComponent(l)}/issues?${r.toString()}`,d=await this.api(u);for(let g of d)a.push(this.mapIssue(g,l))}catch(u){this.log(`[business] GitLab listAll failed on ${l}: ${u.message}`)}let c=a;if(e.notLabels?.length){let l=new Set(e.notLabels);c=c.filter(u=>!(u.labels||[]).some(d=>l.has(d)))}if(e.withoutScopedPrefix){let l=e.withoutScopedPrefix+"::";c=c.filter(u=>!(u.labels||[]).some(d=>d.startsWith(l)))}return c}async setState(e,n){let{project:s,iid:r,type:i}=this.parseId(e),o=i==="issue"?"issues":"merge_requests";await this.api(`/projects/${encodeURIComponent(s)}/${o}/${r}?state_event=${n}`,{method:"PUT"})}async getItem(e){let{project:n,iid:s}=this.parseId(e);try{let r=await this.api(`/projects/${encodeURIComponent(n)}/issues/${s}?with_labels_details=true`);return{...this.mapIssue(r,n),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(o=>o.name):r.labels:[]}}catch(r){return this.log(`[board] GitLab getItem failed for ${e}: ${r.message}`),null}}async updateItem(e,n){let{project:s,iid:r}=this.parseId(e),i;n.assigneeUsernames&&(i=(await Promise.all(n.assigneeUsernames.map(async u=>{try{let d=await this.api(`/users?username=${encodeURIComponent(u)}`);return Array.isArray(d)&&d[0]?.id?d[0].id:null}catch{return null}}))).filter(u=>typeof u=="number"));let o;if(n.milestoneTitle!==void 0)if(n.milestoneTitle===null||n.milestoneTitle==="")o=0;else try{let l=await this.api(`/projects/${encodeURIComponent(s)}/milestones?title=${encodeURIComponent(n.milestoneTitle)}`);Array.isArray(l)&&l[0]?.id&&(o=l[0].id)}catch(l){this.log(`[board] milestone lookup failed for "${n.milestoneTitle}": ${l.message}`)}let a={};n.title!==void 0&&(a.title=n.title),n.description!==void 0&&(a.description=n.description),n.labels!==void 0&&(a.labels=n.labels.join(",")),n.addLabels?.length&&(a.add_labels=n.addLabels.join(",")),n.removeLabels?.length&&(a.remove_labels=n.removeLabels.join(",")),i!==void 0&&(a.assignee_ids=i),o!==void 0&&(a.milestone_id=o);let c=await this.api(`/projects/${encodeURIComponent(s)}/issues/${r}`,{method:"PUT",body:JSON.stringify(a)});return this.mapIssue(c,s)}async listMembers(){let e=new Map;for(let n of this.projects)try{let s=await this.api(`/projects/${encodeURIComponent(n)}/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 ${n}: ${s.message}`)}return[...e.values()].sort((n,s)=>n.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 n=[...e.values()];return n.sort((s,r)=>s.state!==r.state?s.state==="active"?-1:1:s.title.localeCompare(r.title)),n}async create(e){let n=e.projectHint||this.projects[0];if(!n)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 l=>{try{let u=await this.api(`/users?username=${encodeURIComponent(l)}`);return Array.isArray(u)&&u[0]?.id?u[0].id:null}catch(u){return this.log(`[board] user lookup failed for ${l}: ${u.message}`),null}}))).filter(l=>typeof l=="number"));let i;if(e.milestoneTitle)try{let c=await this.api(`/projects/${encodeURIComponent(n)}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);Array.isArray(c)&&c[0]?.id&&(i=c[0].id)}catch(c){this.log(`[board] milestone lookup failed for "${e.milestoneTitle}": ${c.message}`)}let o={title:e.title,description:e.description,labels:(e.labels||[]).join(",")};s?.length&&(o.assignee_ids=s),i!==void 0&&(o.milestone_id=i);let a=await this.api(`/projects/${encodeURIComponent(n)}/issues`,{method:"POST",body:JSON.stringify(o)});return this.mapIssue(a,n)}async transition(e,n,s){await this.transitionMany(e,n?[n]:[],s?[s]:[])}async transitionMany(e,n,s){let{project:r,iid:i,type:o}=this.parseId(e),a=o==="issue"?"issues":"merge_requests",c=new URLSearchParams;n.length&&c.set("add_labels",n.join(",")),s.length&&c.set("remove_labels",s.join(",")),c.toString()&&await this.api(`/projects/${encodeURIComponent(r)}/${a}/${i}?${c.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 xo(t,e,n){let s=t.workSource;switch(s.type){case"backlog":return new ye(s.path,e,n);case"wiki":return new be(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 a of r.agentMappings)a.gitlabUsernames.length&&(i[a.agentId]=a.gitlabUsernames);let o=s.projects.length?s.projects:r.routes.map(a=>a.project);return new ke(r.host,r.token,o,i,n)}}}var we="unmapped";function Se(t,e=[]){if(!t)return we;let n=e.find(r=>r.id===t);if(n?.client)return n.client;let s=t.indexOf("/");return s>0?t.slice(0,s):t}function Nr(t){let e=new Map,n=t.projects??[],s=t.orgChart??{};for(let i of n)i.pm&&(e.has(i.pm)||e.set(i.pm,Se(i.id,n)));let r=(i,o=new Set)=>{if(e.has(i))return e.get(i);if(o.has(i))return;o.add(i);let a=s[i]?.reportsTo;if(!a)return;let c=r(a,o);return c&&e.set(i,c),c};for(let i of Object.keys(s))r(i);return e}function Mr(t,e,n=[]){if(!n.length)return;let s=n.filter(r=>!r.channel||r.channel===t);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 vo(t,e){let n=Mr(t.channel,{chatId:t.chatId,username:t.username},e.contactMap);if(n)return n.client;if(t.project)return Se(t.project,e.projects);if(t.agentId){let s=Nr(e).get(t.agentId);if(s)return s}return we}function Io(t,e){let n=String(t||"").split(":");if(n.length<3)return{agentId:e};let[s,r,...i]=n,o=i.join(":"),a={agentId:e||s,channel:r};return r==="gitlab"||r==="github"?a.project=o.split(":")[0]:r==="cron"||r==="api"||(a.chatId=o.split("@")[0]),a}var Vr=t=>t===we?"internal":"client";function Fr(t,e){let n=e.clients?.[t];return{id:t,name:n?.name||t,kind:n?.kind??Vr(t),respondWithinMinutes:Ur(n?.respondWithin),standing:n?.standing??[],declared:!!n}}function Ao(t){let e=new Set;for(let n of t.projects??[])e.add(Se(n.id,t.projects));for(let n of t.contactMap??[])e.add(n.client);for(let n of Object.keys(t.clients??{}))e.add(n);return[...e].sort().map(n=>Fr(n,t))}function Ur(t){let e=/^(\d+)\s*([mhd])$/.exec(String(t??"").trim());if(!e)return;let n=Number(e[1]);return e[2]==="m"?n:e[2]==="h"?n*60:n*1440}var Br=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n/i,Wr=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*```[ \t]*(?=\n|$)/gi;function Dt(t){if(!t||!t.includes("agentx:ui"))return{cleanText:t};let e=[...t.matchAll(Wr)];if(e.length===0)return{cleanText:t};let n=e[e.length-1],s=n[2],r=Hr(s);if(!r)return{cleanText:t};let i=n.index??0,o=n[1]??"";return{cleanText:(t.slice(0,i)+o+t.slice(i+n[0].length)).trim(),ui:r}}function Ro(t){if(!t||!t.includes("agentx:ui"))return t;let e=Br.exec(t);return e?t.slice(0,e.index).trimEnd():t}function Hr(t){let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object")return null;let n={};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&&(n.buttons=s),r.length&&(n.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&&(n.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&&(n.media={type:s,url:r,...typeof i=="string"?{caption:i}:{}})}return!n.buttons&&!n.poll&&!n.media&&!n.skippedActions?null:n}import{closeSync as F,createReadStream as zr,fstatSync as Kr,openSync as Gr,realpathSync as Lt}from"fs";import{isAbsolute as Xr,resolve as Pt,sep as jt}from"path";var Lo="/app-files",qr=/^[A-Za-z0-9_.:-]{1,64}$/;function Jr(t,e,n=process.cwd()){if(!e||e.length>H.pathChars||e.includes("\0"))return{ok:!1,status:400,error:"bad file path"};if(e.split(/[\\/]/).includes(".."))return{ok:!1,status:403,error:"the path leaves the workspace"};if(!oe(e))return{ok:!1,status:415,error:"this type of file is not served"};let s;try{s=Lt(Pt(n,t))}catch{return{ok:!1,status:404,error:"the agent's workspace is missing"}}let r;try{r=Lt(Xr(e)?e:Pt(s,e))}catch{return{ok:!1,status:404,error:"file not found"}}if(!r.startsWith(s+jt))return{ok:!1,status:403,error:"the file is outside the agent's workspace"};let i=oe(r);return i?{ok:!0,path:r,...i}:{ok:!1,status:415,error:"this type of file is not served"}}function Yr(t,e){let n=t.replace(/[^\x20-\x7e]/g,"_").replace(/["\\;]/g,"_").slice(0,120)||"file";return`${e==="file"?"attachment":"inline"}; filename="${n}"; filename*=UTF-8''${encodeURIComponent(t.slice(0,120))}`}function Zr(t,e,n){return{"Content-Type":t,"Content-Disposition":Yr(e,n),"X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; img-src 'self'; media-src 'self'; sandbox","Cache-Control":"private, max-age=3600","Accept-Ranges":"bytes"}}function Qr(t,e){let n=/^bytes=(\d*)-(\d*)$/.exec(String(t||"").trim());if(!n||!n[1]&&!n[2])return null;let s,r;return n[1]?(s=Number(n[1]),r=n[2]?Math.min(Number(n[2]),e-1):e-1):(s=Math.max(0,e-Number(n[2])),r=e-1),s>r||s>=e?"unsatisfiable":{start:s,end:r}}function Po(t,e,n,s){let r=(R,E)=>{e.writeHead(R,{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),e.end(JSON.stringify(E))};if(t.method!=="GET"&&t.method!=="HEAD")return r(405,{error:"GET only"});let i=n.searchParams.get("agent")||"",o=n.searchParams.get("file")||"";if(!qr.test(i))return r(400,{error:"bad agent id"});let a=s.workspaceOf(i);if(!a)return r(404,{error:`no agent "${i}" on this computer`});let c=Jr(a,o,s.cwd);if(!c.ok)return r(c.status,{error:c.error});let l;try{l=Gr(c.path,"r")}catch{return r(404,{error:"file not found"})}let u;try{let R=Kr(l);if(!R.isFile())return F(l),r(404,{error:"not a file"});u=R.size}catch{return F(l),r(404,{error:"file not found"})}if(u>H.bytes)return F(l),r(413,{error:`the file is larger than ${H.bytes/1024/1024} MB`});let d=c.path.split(jt).pop()||"file",g=Zr(c.mime,d,c.kind),f=Qr(t.headers.range,u);if(f==="unsatisfiable"){F(l),e.writeHead(416,{...g,"Content-Range":`bytes */${u}`}),e.end();return}let{start:m,end:h}=f??{start:0,end:u-1};if(e.writeHead(f?206:200,{...g,"Content-Length":String(u?h-m+1:0),...f?{"Content-Range":`bytes ${m}-${h}/${u}`}:{}}),t.method==="HEAD"||u===0){F(l),e.end();return}let y=zr("",{fd:l,start:m,end:h,autoClose:!0});y.on("error",()=>e.destroy()),e.on("close",()=>y.destroy()),y.pipe(e)}import{execFile as gs,execFileSync as fs}from"child_process";import{execFileSync as es}from"child_process";import{existsSync as Nt,mkdirSync as ts,readdirSync as ns,readFileSync as Mt,renameSync as rs,writeFileSync as ss}from"fs";import{homedir as Vt}from"os";import{join as $e}from"path";var ve="siri:",Ft="com.apple.ttsbundle.gryphon-neural_",Ut=t=>!!t&&t.startsWith(Ft),is=["/usr/bin/say","/usr/bin/defaults","/usr/bin/plutil"],os=()=>{try{return es("/usr/bin/defaults",["read","com.apple.Accessibility"],{stdio:"ignore",timeout:5e3}),!0}catch{return!1}},xe;function Ie(t={}){let e=t.platform!==void 0||t.exists!==void 0||t.prefDomain!==void 0;if(!e&&xe!==void 0)return xe;let{platform:n=process.platform,exists:s=Nt,prefDomain:r=os}=t,i=n==="darwin"&&is.every(o=>s(o))&&r();return e||(xe=i),i}var as=["/System/Library/AssetsV2/com_apple_MobileAsset_Trial_Siri_SiriTextToSpeech/purpose_auto","/System/Library/AssetsV2/com_apple_MobileAsset_UAF_Siri_TextToSpeech/purpose_auto"],ls={aaron:"male",damon:"male",daniel:"male",pierre:"male",samer:"male",arthur:"male",gordon:"male",martin:"male",nora:"female",simone:"female",marie:"female",soha:"female",martha:"female",catherine:"female",helena:"female",nicky:"female"},cs=/com\.apple\.siri\.tts\.voice\.([a-z]{2})_([A-Z]{2})\.([a-z]+)\.neural\.premium/g;function us(t){let e=new Map;for(let n of t)for(let[,s,r,i]of n.matchAll(cs)){let o=`${s}-${r}`,a=`${Ft}${i}_${o}_premium`;e.has(a)||e.set(a,{id:a,name:i[0].toUpperCase()+i.slice(1),locale:o,quality:"premium",gender:ls[i]??null,siri:!0})}return[...e.values()]}function Y(t=as,e={}){if(!Ie(e))return[];let n=[];for(let s of t){let r;try{r=ns(s)}catch{continue}for(let i of r)try{n.push(Mt($e(s,i,"Info.plist"),"latin1"))}catch{}}return us(n)}var Ot=`#!/bin/sh
1
+ import{g as qe,h as Je,i as Ye,k as Ze,l as Qe}from"./chunk-I2SD4XZ6.js";import{t as nt,u as rt}from"./chunk-XT3E5MLX.js";import{d as et,e as tt}from"./chunk-AQASR6KR.js";import{b as ie,p as Xe,r as H,s as oe,u as ae}from"./chunk-ECBKTFTL.js";import{q as Ge}from"./chunk-BHE5TJSN.js";import{w as Ke,z as An}from"./chunk-OVF37EXJ.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(p=>n-p.at<=r),l=a.filter(p=>n-p.at>r&&n-p.at<=r*2),u=c.filter(p=>p.status==="failed").length,d=a.filter(p=>p.status==="paused").length,g=a.length?Math.max(...a.map(p=>p.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
+ `).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)})),p=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:p?{at:new Date(p.at).toISOString(),status:p.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
+ `,"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 mt}from"path";var pt=["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 mt(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 mt(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
+ `),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(!pt.includes(c))return{ok:!1,error:`if_silent must be one of ${pt.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(`
5
+ `)}import{mkdirSync as ar,readFileSync as lr,renameSync as cr,writeFileSync as ur}from"fs";import{resolve as dr}from"path";function kt(t){return dr(D(t),"_state.json")}function G(t){try{let e=JSON.parse(lr(kt(t),"utf-8"));return{snoozed:e&&typeof e.snoozed=="object"&&e.snoozed?e.snoozed:{},...typeof e?.lastDigest=="string"?{lastDigest:e.lastDigest}:{}}}catch{return{snoozed:{}}}}function wt(t,e){ar(D(t),{recursive:!0});let n=kt(t),s=`${n}.${process.pid}.tmp`;ur(s,JSON.stringify(e,null,2)+`
6
+ `),cr(s,n)}function St(t,e,n,s=Date.now()){let r=G(t),i={};for(let[o,a]of Object.entries(r.snoozed))Date.parse(a)>s&&(i[o]=a);i[e]=n.toISOString(),wt(t,{...r,snoozed:i})}function Wi(t,e){wt(t,{...G(t),lastDigest:e})}var xt=["card","schedule","memory","wiki"],pr=280;function de(t,e=pr){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function $t(t){if(t.configPath)return L(t.configPath);let e=[L(t.root,"agentx.json"),L(t.root,".agentx","config.json")];return e.find(n=>ue(n))??e[0]}function ge(t){return t.wikiDir?L(t.wikiDir):L(t.root,".agentx","wiki")}function mr(t){return V(t.root,"pending").map(hr)}function hr(t){return{key:`card:${t.id}`,kind:"card",title:t.title,ask:t.ask,yes:`tell ${t.raised_by} yes`,no:`tell ${t.raised_by} no`,recommend:t.recommend,if_silent:t.if_silent,expires:t.expires,...t.source?{source:t.source}:{},raised_by:t.raised_by,created_at:t.created_at}}function yr(t){let e=$t(t);if(!ue(e))return[];let n;try{n=JSON.parse(fr(e,"utf-8"))}catch{return[]}let s=new Date(t.now??Date.now()),r=[];for(let[i,o]of Object.entries(n?.crons??{})){let a=o?.approval;if(!a||a.action!=="create"&&a.action!=="delete")continue;let c=o.timezone||"UTC",l=o.schedule?qe(o.schedule):"",u=o.schedule?`${l.charAt(0).toLowerCase()}${l.slice(1)} (${o.schedule})`:"no schedule",d=String(o.prompt??o.command??""),g=a.action==="create";r.push({key:`schedule:${i}`,kind:"schedule",title:g?`New schedule "${i}" for ${o.agent??"an agent"}`:`Delete schedule "${i}"`,ask:g?`Let ${o.agent??"the agent"} run this ${u}?`:`Remove the schedule "${i}" (${u})?`,yes:g?"enable it":"remove it",no:g?"drop the request":"keep the schedule",raised_by:String(a.requestedBy??"unknown"),created_at:String(a.requestedAt??""),detail:de(`${d}${g&&o.schedule?` \xB7 first run ${Ye(Je(o.schedule,c,s),c)}`:""}`),more:"agentx schedule list"})}return r}function vt(t){let e=L(t,".agentx","memory");return ue(e)?gr(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function br(t){let e=vt(t.root);if(e.length===0)return[];let n=new ie(t.root),s=[];for(let r of e)for(let i of n.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:de(i.content),more:`agentx memory facts held --agent ${r}`});return s}function kr(t){let e=t.sources.filter(n=>n.failure);return e.length?e.map(n=>`Recurring failure: ${n.agentId}'s ${n.failure.tool} fails with "${n.failure.errorClass}" in ${n.occurrences??1} sessions (${n.failure.runs} runs).`).join(" "):`${t.sources.length} source(s)${t.occurrences>1?`, seen in ${t.occurrences} sessions`:""}.`}function wr(t){return tt(ge(t),"pending").map(e=>{let n=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:n.agents.join(", ")||"wiki promote",created_at:e.createdAt,detail:de(`${kr(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}var It={card:mr,schedule:yr,memory:br,wiki:wr};function Sr(t,e){let n=t.expires?Date.parse(t.expires):1/0,s=e.expires?Date.parse(e.expires):1/0;return n!==s?n-s:(Date.parse(t.created_at)||0)-(Date.parse(e.created_at)||0)}function Qi(t,e={}){let n=t.now??Date.now(),{snoozed:s}=G(t.root),r=[],i=[],o=0;for(let a of e.kinds??xt){let c;try{c=It[a](t)}catch(l){i.push({kind:a,error:String(l?.message??l).slice(0,200)});continue}for(let l of c){let u=s[l.key];if(u&&Date.parse(u)>n){if(!e.includeSnoozed){o++;continue}l.snoozed_until=u}r.push(l)}}return r.sort(Sr),{items:r,snoozed:o,errors:i}}function xr(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),s=t.slice(e+1);return!xt.includes(n)||!s?null:{kind:n,ref:s}}function $r(t,e,n){switch(e){case"card":return M(t.root,n)?.status==="pending";case"wiki":return et(ge(t),n)?.status==="pending";default:return It[e](t).some(s=>s.key===`${e}:${n}`)}}async function eo(t,e,n,s={}){let r=xr(e);if(!r)return{ok:!1,error:`unknown item "${e}": use a key from \`agentx approvals list\``};let{kind:i,ref:o}=r,a=t.now??Date.now(),c=s.by??"operator";if(n==="later"){if(!$r(t,i,o))return{ok:!1,error:`nothing waiting for "${e}"`};let u=s.laterHours&&s.laterHours>0?s.laterHours:24,d=new Date(a+u*36e5);return St(t.root,e,d,a),{ok:!0,message:`${e} put off until ${d.toISOString()}`}}let l=n==="yes";switch(i){case"card":{let u=bt(t.root,o,l?"yes":"no",{by:c,note:s.note,now:a});return u.ok?{ok:!0,message:`${e}: ${u.card.raised_by} will be told ${l?"yes":"no"}`}:u}case"schedule":{let u=await(l?Ze:Qe)(o,{configPath:$t(t),reload:t.reload});return u.success?{ok:!0,message:u.message}:{ok:!1,error:u.message}}case"memory":{let u=o.indexOf("/");if(u<=0)return{ok:!1,error:"memory keys look like memory:<agent>/<fact-id>"};let d=o.slice(0,u),g=o.slice(u+1);if(!vt(t.root).includes(d))return{ok:!1,error:`no memory for agent "${d}"`};let f=new ie(t.root);return f.held(d).some(p=>p.id===g)?(f.review(d,g,l?"approved":"rejected",c),{ok:!0,message:`${e} ${l?"approved: the agent may use it":"rejected: it stays out of prompts"}`}):{ok:!1,error:`fact "${g}" isn't waiting for review`}}case"wiki":{let u=ge(t),d=l?nt(u,o,{by:c,force:s.force,now:a}):rt(u,o,{by:c,reason:s.note,now:a});return d.ok?{ok:!0,message:l?`${d.proposal.article.path} written to the shared wiki`:`${e} rejected`}:d}}}var At=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]);function no(t){return t==="/api/memory"||t.startsWith("/api/memory/")||t==="/approvals"||t.startsWith("/approvals/")||t==="/events/recent"||/^\/agents\/[^/]+\/events$/.test(t)||t==="/traces"||t.startsWith("/traces/")||t==="/voice/history"||t.startsWith("/voice/history/")||t==="/voice/transcribe"||t==="/voice/speak"||t==="/app-files"}function ro(t){return t==="/reload"||t==="/api/processes/kill"||t==="/send"||t==="/send/agent"||t==="/send/contact"||t==="/mesh/announce"||t==="/voice/settings"||t==="/voice/preview"||/^\/api\/tasks\/[^/]+\/(cancel|followup)$/.test(t)||/^\/crons\/[^/]+\/enabled$/.test(t)}function so(t){return At.has(t)}function io(t){if(t.foreignBrowser)return{allowed:!1,reason:"foreign-browser-origin"};if(t.enforcementDisabled)return{allowed:!0,reason:"disabled"};if(At.has(t.remoteAddress))return{allowed:!0,reason:"loopback"};if(t.acceptedTokens.size===0)return{allowed:!0,reason:"no-tokens-configured"};let e=t.authorizationHeader||"",n=e.startsWith("Bearer ")?e.slice(7).trim():"";return n&&t.acceptedTokens.has(n)?{allowed:!0,reason:"token"}:{allowed:!1,reason:"missing-or-invalid-token"}}function oo(t,e=process.env){let n=new Set;e.MESH_TOKEN&&n.add(e.MESH_TOKEN);for(let s of t.mesh?.peers||[])s.token&&n.add(s.token);return n}function ao(t,e,n=process.env){let s=i=>i.replace(/\/+$/,"");return(e===s(t.daemonUrl)?t.token:t.daemons.find(i=>s(i.url)===e)?.token)||n.MESH_TOKEN||void 0}function X(t){return(Array.isArray(t)?t[0]:t)?.trim()??""}function vr(t){try{return new URL(t).host.toLowerCase()}catch{return null}}function Ir(t=process.env){return new Set((t.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function co(t,e=Ir()){let n=X(t.origin);if(n){if(e.has(n.replace(/\/+$/,"").toLowerCase()))return"same-origin";let r=vr(n),i=[X(t.host),X(t["x-forwarded-host"])].filter(Boolean).map(o=>o.toLowerCase());return r&&i.includes(r)?"same-origin":"foreign"}let s=X(t["sec-fetch-site"]).toLowerCase();return s==="cross-site"||s==="same-site"?"foreign":"none"}function uo(t){let e=(t||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}import{readFileSync as pe,writeFileSync as Dt,existsSync as me,readdirSync as Pr,statSync as Or}from"fs";import{resolve as he,join as jr}from"path";import{existsSync as _t,mkdirSync as Ar,readFileSync as _r,writeFileSync as Rt}from"fs";import{dirname as Rr,resolve as Ct}from"path";import{z as m}from"zod";var Cr=m.object({type:m.enum(["gitlab","github"]),host:m.string().optional(),project:m.string(),iid:m.number().int().positive(),url:m.string()}),Tr=m.object({id:m.string(),title:m.string(),description:m.string().optional(),assignee:m.string().optional(),labels:m.array(m.string()).default([]),milestone:m.string().optional(),status:m.enum(["todo","doing","blocked","done"]).default("todo"),priority:m.number().int().optional(),estimatedSeconds:m.number().int().optional(),source:Cr.optional(),importedAt:m.string().optional(),createdAt:m.string(),updatedAt:m.string(),blocker:m.string().optional(),doneNote:m.string().optional()}),Er=m.object({version:m.literal(1),items:m.array(Tr).default([])}),q=class{constructor(e){this.path=e}jsonPath(){return Ct(process.cwd(),this.path).replace(/\.md$/i,".json")}mdPath(){return Ct(process.cwd(),this.path).replace(/\.json$/i,".md")}exists(){return _t(this.jsonPath())}load(){let e=this.jsonPath();if(!_t(e))return{version:1,items:[]};let n=_r(e,"utf-8");try{return Er.parse(JSON.parse(n))}catch(s){throw new Error(`Backlog file invalid (${e}): ${s.message}`)}}save(e){let n=this.jsonPath();Ar(Rr(n),{recursive:!0}),Rt(n,JSON.stringify(e,null,2)+`
7
+ `),Rt(this.mdPath(),this.toMarkdown(e))}list(){return this.load().items}findById(e){return this.list().find(n=>n.id===e)}add(e){let n=this.load();if(n.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 n.items.push(r),this.save(n),r}addMany(e){let n=this.load(),s=new Set(n.items.map(o=>o.id)),r=new Date().toISOString(),i=[];for(let o of e){if(s.has(o.id))continue;let a={...o,labels:o.labels??[],status:o.status??"todo",createdAt:o.createdAt??r,updatedAt:r};n.items.push(a),i.push(a),s.add(a.id)}return i.length&&this.save(n),i}update(e,n){let s=this.load(),r=s.items.findIndex(o=>o.id===e);if(r<0)throw new Error(`backlog item ${e} not found`);let i={...s.items[r],...n,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 n=this.load(),s=n.items.length;return n.items=n.items.filter(r=>r.id!==e),n.items.length===s?!1:(this.save(n),!0)}toMarkdown(e){let n=["# 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,o]of r)if(s[i].length){n.push(`## ${o}`,"");for(let a of s[i]){let c=i==="done"?"x":" ",l=a.assignee?`@${a.assignee} `:"",u=a.estimatedSeconds?` [time: ${Math.round(a.estimatedSeconds/60)}m]`:"",d=a.source?` (${a.source.type}: ${a.source.project}#${a.source.iid})`:"";n.push(`- [${c}] ${l}${a.title}${u}${d}`),a.source?.url&&n.push(` - <${a.source.url}>`),a.labels.length&&n.push(` - labels: ${a.labels.join(", ")}`),a.milestone&&n.push(` - milestone: ${a.milestone}`),a.blocker&&n.push(` - BLOCKED: ${a.blocker}`)}n.push("")}return n.join(`
8
+ `)}};function ho(t){return`${t.type}:${t.project}:${t.iid}`}function Tt(t,e,n){let s=[];if(e.type==="gitlab"){let r=n.channels.gitlab?.agentMappings??[];for(let i of t){let o=r.find(a=>a.agentId===i);o?.gitlabUsernames?.length?s.push(o.gitlabUsernames[0]):s.push(i)}}else if(e.type==="github"){let r=n.channels.github?.agentMappings??[];for(let i of t){let o=r.find(a=>a.agentId===i);o?.githubUsernames?.length?s.push(o.githubUsernames[0]):s.push(i)}}return s}async function fe(t,e,n,s=()=>{}){return t.source?t.source.type==="gitlab"?Dr(t.source,e,n,s):t.source.type==="github"?Lr(t.source,e,n,s):{ok:!1,error:`unknown source.type ${t.source.type}`,attempts:[]}:{ok:!0,attempts:[]}}async function Dr(t,e,n,s){let r=n.channels.gitlab,i=r?.token,o=r?.host||(t.host?`https://${t.host}`:void 0);if(!i||!o)return{ok:!1,error:"gitlab token/host not configured",attempts:[]};let a=[],c=async(f,p={})=>fetch(`${o}/api/v4${f}`,{...p,headers:{"PRIVATE-TOKEN":i,"Content-Type":"application/json",...p.headers||{}}}),l=encodeURIComponent(t.project),u;e.assigneeUsernames!==void 0&&(u=(await Promise.all(e.assigneeUsernames.map(async p=>{try{let h=await fetch(`${o}/api/v4/users?username=${encodeURIComponent(p)}`,{headers:{"PRIVATE-TOKEN":i}});if(!h.ok)return null;let y=await h.json();return Array.isArray(y)&&y[0]?.id?y[0].id:null}catch{return null}}))).filter(p=>typeof p=="number"));let d;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")d=0;else try{let f=await c(`/projects/${l}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);if(f.ok){let p=await f.json();Array.isArray(p)&&p[0]?.id&&(d=p[0].id)}}catch(f){s(`[backlog-sync] milestone lookup failed: ${f.message}`)}let g={};if(e.title!==void 0&&(g.title=e.title),e.description!==void 0&&(g.description=e.description),e.labels!==void 0&&(g.labels=e.labels.join(",")),e.addLabels?.length&&(g.add_labels=e.addLabels.join(",")),e.removeLabels?.length&&(g.remove_labels=e.removeLabels.join(",")),u!==void 0&&(g.assignee_ids=u),d!==void 0&&(g.milestone_id=d),e.state&&(g.state_event=e.state==="closed"?"close":"reopen"),Object.keys(g).length)try{let f=await c(`/projects/${l}/issues/${t.iid}`,{method:"PUT",body:JSON.stringify(g)});if(a.push({kind:"PUT issue",ok:f.ok,status:f.status}),!f.ok){let p=await f.text().catch(()=>"");return{ok:!1,attempts:a,error:`PUT issue ${f.status}: ${p.slice(0,200)}`,url:t.url}}}catch(f){return a.push({kind:"PUT issue",ok:!1,error:f.message}),{ok:!1,attempts:a,error:f.message,url:t.url}}if(e.note)try{let f=await c(`/projects/${l}/issues/${t.iid}/notes`,{method:"POST",body:JSON.stringify({body:e.note})});a.push({kind:"POST note",ok:f.ok,status:f.status})}catch(f){a.push({kind:"POST note",ok:!1,error:f.message})}return{ok:a.every(f=>f.ok),attempts:a,url:t.url}}async function Lr(t,e,n,s){let i=n.channels.github?.token;if(!i)return{ok:!1,error:"github token not configured",attempts:[]};let o=[],a=async(g,f={})=>fetch(`https://api.github.com${g}`,{...f,headers:{Authorization:`Bearer ${i}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",...f.headers||{}}}),c=t.project,l;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")l=null;else try{let g=await a(`/repos/${c}/milestones?state=all&per_page=100`);if(g.ok){let f=await g.json(),p=Array.isArray(f)?f.find(h=>h.title===e.milestoneTitle):null;p?.number&&(l=p.number)}}catch(g){s(`[backlog-sync] github milestone lookup failed: ${g.message}`)}let u;if(e.labels!==void 0)u=e.labels;else if(e.addLabels?.length||e.removeLabels?.length)try{let g=await a(`/repos/${c}/issues/${t.iid}`);if(g.ok){let f=await g.json(),p=Array.isArray(f.labels)?f.labels.map(y=>typeof y=="string"?y:y.name):[],h=new Set([...p,...e.addLabels??[]]);for(let y of e.removeLabels??[])h.delete(y);u=[...h]}}catch(g){s(`[backlog-sync] github label fetch failed: ${g.message}`)}let d={};if(e.title!==void 0&&(d.title=e.title),e.description!==void 0&&(d.body=e.description),u!==void 0&&(d.labels=u),e.assigneeUsernames!==void 0&&(d.assignees=e.assigneeUsernames),l!==void 0&&(d.milestone=l),e.state&&(d.state=e.state),Object.keys(d).length)try{let g=await a(`/repos/${c}/issues/${t.iid}`,{method:"PATCH",body:JSON.stringify(d)});if(o.push({kind:"PATCH issue",ok:g.ok,status:g.status}),!g.ok){let f=await g.text().catch(()=>"");return{ok:!1,attempts:o,error:`PATCH issue ${g.status}: ${f.slice(0,200)}`,url:t.url}}}catch(g){return o.push({kind:"PATCH issue",ok:!1,error:g.message}),{ok:!1,attempts:o,error:g.message,url:t.url}}if(e.note)try{let g=await a(`/repos/${c}/issues/${t.iid}/comments`,{method:"POST",body:JSON.stringify({body:e.note})});o.push({kind:"POST comment",ok:g.ok,status:g.status})}catch(g){o.push({kind:"POST comment",ok:!1,error:g.message})}return{ok:o.every(g=>g.ok),attempts:o,url:t.url}}var ye=/^(\s*)-\s*\[( |x|X)\]\s*(.*)$/,J=/@([a-z0-9_-]+)/i,Et=/\[time:\s*([0-9hm\s]+)\]/i;function Nr(t){let e=t.match(/(\d+)\s*h/i),n=t.match(/(\d+)\s*m/i);return(e?parseInt(e[1],10)*3600:0)+(n?parseInt(n[1],10)*60:0)}var be=class{constructor(e,n,s=()=>{}){this.path=e;this.daemon=n;this.log=s;this.store=new q(this.path)}type="backlog";capabilities={listAll:!0,create:!1,transition:!1,labels:!0,search:!1};store;getStore(){return this.store}readMd(){let e=he(process.cwd(),this.path);return me(e)?pe(e,"utf-8").split(`
9
+ `):[]}writeMd(e){let n=he(process.cwd(),this.path);Dt(n,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 n=this.readMd(),s=[];for(let r=0;r<n.length;r++){let i=n[r].match(ye);if(!i||i[2].toLowerCase()==="x")continue;let a=i[3],c=a.match(J);if(c&&c[1].toLowerCase()!==e.toLowerCase())continue;let l=a.match(Et),u=a.replace(J,"").replace(Et,"").trim();s.push({id:`backlog:${r}`,title:u||`Task at line ${r+1}`,assignee:c?c[1]:void 0,estimatedSeconds:l?Nr(l[1]):void 0,priority:r})}return s}async listAll(e={}){return this.store.exists()?this.store.list().map(n=>this.toWorkItem(n)):[]}async claim(e,n){if(!this.store.exists())return;let s=this.store.findById(n);if(!s)return;let r=this.store.update(n,{assignee:s.assignee||e,status:"doing"});if(r.source&&this.daemon){let i=Tt([r.assignee||e],r.source,this.daemon);fe(r,{assigneeUsernames:i,addLabels:["Doing"],removeLabels:["To Do"]},this.daemon,this.log).catch(o=>this.log(`[backlog-sync] claim failed for ${n}: ${o?.message??o}`))}}async report(e,n){if(this.store.exists()&&this.store.findById(e)){let a={};n.status==="done"?a.status="done":n.status==="blocked"?(a.status="blocked",a.blocker=n.blocker||n.note||void 0):n.status==="in-progress"&&(a.status="doing"),n.timeSeconds&&(a.estimatedSeconds=n.timeSeconds);let c=this.store.update(e,a);if(c.source&&this.daemon){let l={};n.status==="done"?(l.addLabels=["Done"],l.removeLabels=["Doing"]):n.status==="blocked"&&(l.addLabels=["Blocked"]),n.note&&(l.note=n.note),Object.keys(l).length&&fe(c,l,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(ye))throw new Error(`backlog line ${s} not a checkbox`);if(n.status==="done"){r[s]=i.replace(/- \[ \]/,"- [x]");let a=n.timeSeconds?` <!-- done by agent, ${Math.round(n.timeSeconds/60)}m -->`:" <!-- done by agent -->";r.splice(s+1,0,a)}else n.status==="blocked"?r.splice(s+1,0,` <!-- BLOCKED: ${n.blocker||n.note||"?"} -->`):n.note&&r.splice(s+1,0,` <!-- ${n.note.replace(/-->/g,"\u2014 >")} -->`);this.writeMd(r)}toWorkItem(e){let n={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:n,milestone:e.milestone,url:e.source?.url,updatedAt:e.updatedAt,state:e.status==="done"?"closed":"opened"}}},ke=class{constructor(e,n){this.root=e;this.glob=n}type="wiki";capabilities={listAll:!1,create:!1,transition:!1,labels:!1,search:!1};walk(e,n){if(me(e))for(let s of Pr(e)){let r=jr(e,s);Or(r).isDirectory()?this.walk(r,n):s.endsWith(".md")&&n.push(r)}}async listOpen(e){let n=[];this.walk(he(process.cwd(),this.root),n);let s=[];for(let r of n){let i=pe(r,"utf-8").split(`
11
+ `);for(let o=0;o<i.length;o++){let a=i[o].match(ye);if(!a||a[2].toLowerCase()==="x")continue;let c=a[3].match(J);!c||c[1].toLowerCase()!==e.toLowerCase()||s.push({id:`wiki:${r}:${o}`,title:a[3].replace(J,"").trim(),assignee:c[1],priority:o})}}return s}async claim(){}async report(e,n){let s=e.split(":"),r=parseInt(s[s.length-1],10),i=s.slice(1,-1).join(":");if(!me(i))return;let o=pe(i,"utf-8").split(`
12
+ `);n.status==="done"&&o[r]&&(o[r]=o[r].replace(/- \[ \]/,"- [x]"),Dt(i,o.join(`
13
+ `)))}},we=class{constructor(e,n,s,r,i){this.host=e;this.token=n;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[n,s]of Object.entries(this.agentUsernames))if(s.some(r=>r.toLowerCase()===e.toLowerCase()))return n}mapIssue(e,n){let s=e.references?.full?.split("#")[0]||n,r=[],i;Array.isArray(e.labels)&&(e.labels.length&&typeof e.labels[0]=="object"?(i=e.labels.map(l=>({name:l.name,color:l.color,text_color:l.text_color})),r=i.map(l=>l.name)):r=e.labels);let a=(Array.isArray(e.assignees)&&e.assignees.length?e.assignees:e.assignee?[e.assignee]:[]).map(l=>({username:l.username,name:l.name,avatarUrl:l.avatar_url})),c=a[0]?.username;return{id:`gitlab:${s}:issue:${e.iid}`,title:e.title,description:e.description||void 0,assignee:c?this.usernameToAgent(c)||c:void 0,assignees:a,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,n={}){let s=await fetch(`${this.host}/api/v4${e}`,{...n,headers:{"PRIVATE-TOKEN":this.token,"Content-Type":"application/json",...n.headers||{}}});if(!s.ok)throw new Error(`GitLab ${s.status}: ${await s.text().catch(()=>"")}`);return s.json()}async listOpen(e){let n=this.agentUsernames[e]||[];if(!n.length)return[];let s=[],r=this.projects.length?this.projects:["__ALL__"];for(let i of n)for(let o of r)try{let a=`assignee_username=${encodeURIComponent(i)}&state=opened&scope=all&per_page=20`,c=o==="__ALL__"?`/issues?${a}`:`/projects/${encodeURIComponent(o)}/issues?${a}`,l=await this.api(c);for(let u of l){let d=this.mapIssue(u,o);d.assignee=e,s.push(d)}}catch(a){this.log(`[business] GitLab listOpen failed for ${i} on ${o}: ${a.message}`)}return s}async claim(e,n){let{project:s,iid:r,type:i}=this.parseId(n),o=`/projects/${encodeURIComponent(s)}/${i==="issue"?"issues":"merge_requests"}/${r}?add_labels=Doing&remove_labels=To Do`;try{await this.api(o,{method:"PUT"})}catch(a){this.log(`[business] claim label update failed: ${a.message}`)}}async report(e,n){let{project:s,iid:r,type:i}=this.parseId(e),o=i==="issue"?"issues":"merge_requests";if(n.timeSeconds&&n.timeSeconds>0){let a=Math.max(1,Math.round(n.timeSeconds/60)),c=a>=60?`${Math.floor(a/60)}h${a%60?` ${a%60}m`:""}`:`${a}m`;try{await this.api(`/projects/${encodeURIComponent(s)}/${o}/${r}/add_spent_time?duration=${encodeURIComponent(c)}`,{method:"POST"})}catch(l){this.log(`[business] add_spent_time failed: ${l.message}`)}}if(n.status==="done")try{await this.api(`/projects/${encodeURIComponent(s)}/${o}/${r}?add_labels=Done&remove_labels=Doing`,{method:"PUT"})}catch(a){this.log(`[business] done label update failed: ${a.message}`)}else if(n.status==="blocked")try{await this.api(`/projects/${encodeURIComponent(s)}/${o}/${r}?add_labels=Blocked`,{method:"PUT"})}catch(a){this.log(`[business] blocked label update failed: ${a.message}`)}if(n.note)try{await this.api(`/projects/${encodeURIComponent(s)}/${o}/${r}/notes`,{method:"POST",body:JSON.stringify({body:n.note})})}catch(a){this.log(`[business] report note failed: ${a.message}`)}}async listAll(e={}){let n=e.sinceDays??30,s=new Date(Date.now()-n*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 o=this.projects.length?this.projects:["__ALL__"],a=[];for(let l of o)try{let u=l==="__ALL__"?`/issues?${r.toString()}`:`/projects/${encodeURIComponent(l)}/issues?${r.toString()}`,d=await this.api(u);for(let g of d)a.push(this.mapIssue(g,l))}catch(u){this.log(`[business] GitLab listAll failed on ${l}: ${u.message}`)}let c=a;if(e.notLabels?.length){let l=new Set(e.notLabels);c=c.filter(u=>!(u.labels||[]).some(d=>l.has(d)))}if(e.withoutScopedPrefix){let l=e.withoutScopedPrefix+"::";c=c.filter(u=>!(u.labels||[]).some(d=>d.startsWith(l)))}return c}async setState(e,n){let{project:s,iid:r,type:i}=this.parseId(e),o=i==="issue"?"issues":"merge_requests";await this.api(`/projects/${encodeURIComponent(s)}/${o}/${r}?state_event=${n}`,{method:"PUT"})}async getItem(e){let{project:n,iid:s}=this.parseId(e);try{let r=await this.api(`/projects/${encodeURIComponent(n)}/issues/${s}?with_labels_details=true`);return{...this.mapIssue(r,n),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(o=>o.name):r.labels:[]}}catch(r){return this.log(`[board] GitLab getItem failed for ${e}: ${r.message}`),null}}async updateItem(e,n){let{project:s,iid:r}=this.parseId(e),i;n.assigneeUsernames&&(i=(await Promise.all(n.assigneeUsernames.map(async u=>{try{let d=await this.api(`/users?username=${encodeURIComponent(u)}`);return Array.isArray(d)&&d[0]?.id?d[0].id:null}catch{return null}}))).filter(u=>typeof u=="number"));let o;if(n.milestoneTitle!==void 0)if(n.milestoneTitle===null||n.milestoneTitle==="")o=0;else try{let l=await this.api(`/projects/${encodeURIComponent(s)}/milestones?title=${encodeURIComponent(n.milestoneTitle)}`);Array.isArray(l)&&l[0]?.id&&(o=l[0].id)}catch(l){this.log(`[board] milestone lookup failed for "${n.milestoneTitle}": ${l.message}`)}let a={};n.title!==void 0&&(a.title=n.title),n.description!==void 0&&(a.description=n.description),n.labels!==void 0&&(a.labels=n.labels.join(",")),n.addLabels?.length&&(a.add_labels=n.addLabels.join(",")),n.removeLabels?.length&&(a.remove_labels=n.removeLabels.join(",")),i!==void 0&&(a.assignee_ids=i),o!==void 0&&(a.milestone_id=o);let c=await this.api(`/projects/${encodeURIComponent(s)}/issues/${r}`,{method:"PUT",body:JSON.stringify(a)});return this.mapIssue(c,s)}async listMembers(){let e=new Map;for(let n of this.projects)try{let s=await this.api(`/projects/${encodeURIComponent(n)}/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 ${n}: ${s.message}`)}return[...e.values()].sort((n,s)=>n.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 n=[...e.values()];return n.sort((s,r)=>s.state!==r.state?s.state==="active"?-1:1:s.title.localeCompare(r.title)),n}async create(e){let n=e.projectHint||this.projects[0];if(!n)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 l=>{try{let u=await this.api(`/users?username=${encodeURIComponent(l)}`);return Array.isArray(u)&&u[0]?.id?u[0].id:null}catch(u){return this.log(`[board] user lookup failed for ${l}: ${u.message}`),null}}))).filter(l=>typeof l=="number"));let i;if(e.milestoneTitle)try{let c=await this.api(`/projects/${encodeURIComponent(n)}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);Array.isArray(c)&&c[0]?.id&&(i=c[0].id)}catch(c){this.log(`[board] milestone lookup failed for "${e.milestoneTitle}": ${c.message}`)}let o={title:e.title,description:e.description,labels:(e.labels||[]).join(",")};s?.length&&(o.assignee_ids=s),i!==void 0&&(o.milestone_id=i);let a=await this.api(`/projects/${encodeURIComponent(n)}/issues`,{method:"POST",body:JSON.stringify(o)});return this.mapIssue(a,n)}async transition(e,n,s){await this.transitionMany(e,n?[n]:[],s?[s]:[])}async transitionMany(e,n,s){let{project:r,iid:i,type:o}=this.parseId(e),a=o==="issue"?"issues":"merge_requests",c=new URLSearchParams;n.length&&c.set("add_labels",n.join(",")),s.length&&c.set("remove_labels",s.join(",")),c.toString()&&await this.api(`/projects/${encodeURIComponent(r)}/${a}/${i}?${c.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 $o(t,e,n){let s=t.workSource;switch(s.type){case"backlog":return new be(s.path,e,n);case"wiki":return new ke(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 a of r.agentMappings)a.gitlabUsernames.length&&(i[a.agentId]=a.gitlabUsernames);let o=s.projects.length?s.projects:r.routes.map(a=>a.project);return new we(r.host,r.token,o,i,n)}}}var Se="unmapped";function xe(t,e=[]){if(!t)return Se;let n=e.find(r=>r.id===t);if(n?.client)return n.client;let s=t.indexOf("/");return s>0?t.slice(0,s):t}function Mr(t){let e=new Map,n=t.projects??[],s=t.orgChart??{};for(let i of n)i.pm&&(e.has(i.pm)||e.set(i.pm,xe(i.id,n)));let r=(i,o=new Set)=>{if(e.has(i))return e.get(i);if(o.has(i))return;o.add(i);let a=s[i]?.reportsTo;if(!a)return;let c=r(a,o);return c&&e.set(i,c),c};for(let i of Object.keys(s))r(i);return e}function Vr(t,e,n=[]){if(!n.length)return;let s=n.filter(r=>!r.channel||r.channel===t);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 Io(t,e){let n=Vr(t.channel,{chatId:t.chatId,username:t.username},e.contactMap);if(n)return n.client;if(t.project)return xe(t.project,e.projects);if(t.agentId){let s=Mr(e).get(t.agentId);if(s)return s}return Se}function Ao(t,e){let n=String(t||"").split(":");if(n.length<3)return{agentId:e};let[s,r,...i]=n,o=i.join(":"),a={agentId:e||s,channel:r};return r==="gitlab"||r==="github"?a.project=o.split(":")[0]:r==="cron"||r==="api"||(a.chatId=o.split("@")[0]),a}var Ur=t=>t===Se?"internal":"client";function Fr(t,e){let n=e.clients?.[t];return{id:t,name:n?.name||t,kind:n?.kind??Ur(t),respondWithinMinutes:Br(n?.respondWithin),standing:n?.standing??[],declared:!!n}}function _o(t){let e=new Set;for(let n of t.projects??[])e.add(xe(n.id,t.projects));for(let n of t.contactMap??[])e.add(n.client);for(let n of Object.keys(t.clients??{}))e.add(n);return[...e].sort().map(n=>Fr(n,t))}function Br(t){let e=/^(\d+)\s*([mhd])$/.exec(String(t??"").trim());if(!e)return;let n=Number(e[1]);return e[2]==="m"?n:e[2]==="h"?n*60:n*1440}var Wr=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n/i,Hr=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*```[ \t]*(?=\n|$)/gi;function Lt(t){if(!t||!t.includes("agentx:ui"))return{cleanText:t};let e=[...t.matchAll(Hr)];if(e.length===0)return{cleanText:t};let n=e[e.length-1],s=n[2],r=zr(s);if(!r)return{cleanText:t};let i=n.index??0,o=n[1]??"";return{cleanText:(t.slice(0,i)+o+t.slice(i+n[0].length)).trim(),ui:r}}function Co(t){if(!t||!t.includes("agentx:ui"))return t;let e=Wr.exec(t);return e?t.slice(0,e.index).trimEnd():t}function zr(t){let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object")return null;let n={};if(Array.isArray(e.buttons)){let s=[],r=[],i=[];for(let o of e.buttons)!o||typeof o.label!="string"||(typeof o.url=="string"&&/^https?:\/\//i.test(o.url)?s.push({label:o.label,url:o.url}):typeof o.reply=="string"&&o.reply.trim()?r.push({label:o.label,reply:o.reply.trim()}):o.action!=null&&i.push(o.label));s.length&&(n.buttons=s),r.length&&(n.replies=r),i.length&&(n.skippedActions=i)}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&&(n.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&&(n.media={type:s,url:r,...typeof i=="string"?{caption:i}:{}})}if(Array.isArray(e.quickReplies)){let s=e.quickReplies.filter(r=>typeof r=="string"&&r.trim()).map(r=>r.trim());s.length&&(n.quickReplies=s)}return!n.buttons&&!n.poll&&!n.media&&!n.quickReplies&&!n.replies&&!n.skippedActions?null:n}import{closeSync as U,createReadStream as Kr,fstatSync as Gr,openSync as Xr,realpathSync as Pt}from"fs";import{isAbsolute as qr,resolve as Ot,sep as jt}from"path";var Oo="/app-files",Jr=/^[A-Za-z0-9_.:-]{1,64}$/;function Yr(t,e,n=process.cwd()){if(!e||e.length>H.pathChars||e.includes("\0"))return{ok:!1,status:400,error:"bad file path"};if(e.split(/[\\/]/).includes(".."))return{ok:!1,status:403,error:`the path leaves the workspace: copy the file into ${ae}/ first`};if(!oe(e))return{ok:!1,status:415,error:"this type of file is not served"};let s;try{s=Pt(Ot(n,t))}catch{return{ok:!1,status:404,error:"the agent's workspace is missing"}}let r;try{r=Pt(qr(e)?e:Ot(s,e))}catch{return{ok:!1,status:404,error:"file not found"}}if(!r.startsWith(s+jt))return{ok:!1,status:403,error:`the file is outside the agent's workspace: copy it into ${ae}/ first`};let i=oe(r);return i?{ok:!0,path:r,...i}:{ok:!1,status:415,error:"this type of file is not served"}}function Zr(t,e){let n=t.replace(/[^\x20-\x7e]/g,"_").replace(/["\\;]/g,"_").slice(0,120)||"file";return`${e==="file"?"attachment":"inline"}; filename="${n}"; filename*=UTF-8''${encodeURIComponent(t.slice(0,120))}`}function Qr(t,e,n){return{"Content-Type":t,"Content-Disposition":Zr(e,n),"X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; img-src 'self'; media-src 'self'; sandbox","Cache-Control":"private, max-age=3600","Accept-Ranges":"bytes"}}function es(t,e){let n=/^bytes=(\d*)-(\d*)$/.exec(String(t||"").trim());if(!n||!n[1]&&!n[2])return null;let s,r;return n[1]?(s=Number(n[1]),r=n[2]?Math.min(Number(n[2]),e-1):e-1):(s=Math.max(0,e-Number(n[2])),r=e-1),s>r||s>=e?"unsatisfiable":{start:s,end:r}}function jo(t,e,n,s){let r=(R,E)=>{e.writeHead(R,{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),e.end(JSON.stringify(E))};if(t.method!=="GET"&&t.method!=="HEAD")return r(405,{error:"GET only"});let i=n.searchParams.get("agent")||"",o=n.searchParams.get("file")||"";if(!Jr.test(i))return r(400,{error:"bad agent id"});let a=s.workspaceOf(i);if(!a)return r(404,{error:`no agent "${i}" on this computer`});let c=Yr(a,o,s.cwd);if(!c.ok)return s.log?.(`[app-files] refused ${JSON.stringify(o.slice(0,200))} from ${i}: ${c.error}`),r(c.status,{error:c.error});let l;try{l=Xr(c.path,"r")}catch{return r(404,{error:"file not found"})}let u;try{let R=Gr(l);if(!R.isFile())return U(l),r(404,{error:"not a file"});u=R.size}catch{return U(l),r(404,{error:"file not found"})}if(u>H.bytes)return U(l),r(413,{error:`the file is larger than ${H.bytes/1024/1024} MB`});let d=c.path.split(jt).pop()||"file",g=Qr(c.mime,d,c.kind),f=es(t.headers.range,u);if(f==="unsatisfiable"){U(l),e.writeHead(416,{...g,"Content-Range":`bytes */${u}`}),e.end();return}let{start:p,end:h}=f??{start:0,end:u-1};if(e.writeHead(f?206:200,{...g,"Content-Length":String(u?h-p+1:0),...f?{"Content-Range":`bytes ${p}-${h}/${u}`}:{}}),t.method==="HEAD"||u===0){U(l),e.end();return}let y=Kr("",{fd:l,start:p,end:h,autoClose:!0});y.on("error",()=>e.destroy()),e.on("close",()=>y.destroy()),y.pipe(e)}import{execFile as fs,execFileSync as ps}from"child_process";import{execFileSync as ts}from"child_process";import{existsSync as Mt,mkdirSync as ns,readdirSync as rs,readFileSync as Vt,renameSync as ss,writeFileSync as is}from"fs";import{homedir as Ut}from"os";import{join as ve}from"path";var Ie="siri:",Ft="com.apple.ttsbundle.gryphon-neural_",Bt=t=>!!t&&t.startsWith(Ft),os=["/usr/bin/say","/usr/bin/defaults","/usr/bin/plutil"],as=()=>{try{return ts("/usr/bin/defaults",["read","com.apple.Accessibility"],{stdio:"ignore",timeout:5e3}),!0}catch{return!1}},$e;function Ae(t={}){let e=t.platform!==void 0||t.exists!==void 0||t.prefDomain!==void 0;if(!e&&$e!==void 0)return $e;let{platform:n=process.platform,exists:s=Mt,prefDomain:r=as}=t,i=n==="darwin"&&os.every(o=>s(o))&&r();return e||($e=i),i}var ls=["/System/Library/AssetsV2/com_apple_MobileAsset_Trial_Siri_SiriTextToSpeech/purpose_auto","/System/Library/AssetsV2/com_apple_MobileAsset_UAF_Siri_TextToSpeech/purpose_auto"],cs={aaron:"male",damon:"male",daniel:"male",pierre:"male",samer:"male",arthur:"male",gordon:"male",martin:"male",nora:"female",simone:"female",marie:"female",soha:"female",martha:"female",catherine:"female",helena:"female",nicky:"female"},us=/com\.apple\.siri\.tts\.voice\.([a-z]{2})_([A-Z]{2})\.([a-z]+)\.neural\.premium/g;function ds(t){let e=new Map;for(let n of t)for(let[,s,r,i]of n.matchAll(us)){let o=`${s}-${r}`,a=`${Ft}${i}_${o}_premium`;e.has(a)||e.set(a,{id:a,name:i[0].toUpperCase()+i.slice(1),locale:o,quality:"premium",gender:cs[i]??null,siri:!0})}return[...e.values()]}function Y(t=ls,e={}){if(!Ae(e))return[];let n=[];for(let s of t){let r;try{r=rs(s)}catch{continue}for(let i of r)try{n.push(Vt(ve(s,i,"Info.plist"),"latin1"))}catch{}}return ds(n)}var Nt=`#!/bin/sh
14
14
  # Written by agentx; shared by the daemon and AgentX Voice. Do not edit.
15
15
  # siri-say.sh [voice] < text speak one line. A Siri voice id switches
16
16
  # the OS default for it; any other id is
@@ -98,21 +98,21 @@ wait "$say_pid"
98
98
  status=$?
99
99
  say_pid=
100
100
  finish $status
101
- `,ds=(t=Vt())=>$e(t,".agentx","voice","siri-say.sh");function Bt(t=Vt()){let e=ds(t);return Nt(e)&&Mt(e,"utf8")===Ot||(ts($e(t,".agentx","voice"),{recursive:!0}),ss(`${e}.tmp`,Ot,{mode:493}),rs(`${e}.tmp`,e)),e}var Wt=`ObjC.import("AVFoundation")
101
+ `,gs=(t=Ut())=>ve(t,".agentx","voice","siri-say.sh");function Wt(t=Ut()){let e=gs(t);return Mt(e)&&Vt(e,"utf8")===Nt||(ns(ve(t,".agentx","voice"),{recursive:!0}),is(`${e}.tmp`,Nt,{mode:493}),ss(`${e}.tmp`,e)),e}var Ht=`ObjC.import("AVFoundation")
102
102
  const vs = $.AVSpeechSynthesisVoice.speechVoices, out = []
103
103
  for (let i = 0; i < vs.count; i++) {
104
104
  const v = vs.objectAtIndex(i)
105
105
  out.push([v.identifier.js, v.name.js, v.language.js, Number(v.quality), Number(v.gender)].join("\\t"))
106
106
  }
107
- out.join("\\n")`,ms=new Set(["Fred","Kathy","Ralph","Junior"]),ps={Flo:"female",Sandy:"female",Shelley:"female",Grandma:"female",Kathy:"female",Eddy:"male",Reed:"male",Rocko:"male",Grandpa:"male",Fred:"male",Ralph:"male",Junior:"male"};function Ht(t){let e=[];for(let n of t.split(`
108
- `)){let[s,r,i,o,a]=n.split(" ");!s||!r||!i||s.includes(".siri_")||s.startsWith("com.apple.speech.synthesis.voice.")&&!ms.has(r)||e.push({id:s,name:r,locale:i,quality:o==="3"?"premium":o==="2"?"enhanced":"standard",gender:a==="1"?"male":a==="2"?"female":ps[r]??null})}return e}var hs=10*60*1e3,P=null,Ae=!1;function _e(t=Date.now()){if(process.platform!=="darwin")return[];if(P)t-P.at>hs&&!Ae&&(Ae=!0,gs("osascript",["-l","JavaScript","-e",Wt],{timeout:1e4},(e,n)=>{Ae=!1,e||(P={at:Date.now(),voices:[...Ht(String(n)),...Y()]})}));else try{P={at:t,voices:[...Ht(fs("osascript",["-l","JavaScript","-e",Wt],{encoding:"utf8",timeout:1e4})),...Y()]}}catch(e){Re(`[voice] could not list system voices: ${String(e?.message??e).split(`
109
- `)[0]}`),P={at:t,voices:Y()}}return P.voices}var Re=t=>process.stderr.write(t+`
110
- `),zt=new Set;function Wo(t){Re=t}function j(t,e){zt.has(t)||(zt.add(t),Re(e))}var ys={premium:3,enhanced:2,standard:1},bs=new Set(["Grandma","Grandpa"]);function Kt(t){let e=t.id.startsWith("com.apple.voice.")?2:t.id.startsWith("com.apple.eloquence.")&&!bs.has(t.name)?1:0;return ys[t.quality]*10+e}var Gt=t=>t.toLowerCase().split(/[-_]/)[0];function Z(t,e="en"){let n=e.toLowerCase().replace("_","-"),s=Gt(e),r=t.filter(i=>Gt(i.locale)===s);return(r.length?r:t).slice().sort((i,o)=>Kt(o)-Kt(i)||+(o.locale.toLowerCase()===n)-+(i.locale.toLowerCase()===n)||i.name.localeCompare(o.name)||i.locale.localeCompare(o.locale))}function Ce(t,e,n="en"){let s=t.trim();if(!s)return null;let r=e.find(l=>l.id===s);if(r)return r;if(s.toLowerCase().startsWith(ve)){let l=s.slice(ve.length).trim().toLowerCase(),u=Z(e.filter(g=>g.siri&&g.name.toLowerCase()===l),n)[0];if(u||!l)return u??null;let d=Ce(l,e,n);return d&&j(`siri:${l}`,`[voice] Siri voice "${l}" is not installed; speaking with ${d.name} (${d.locale}) instead.`),d}e=e.filter(l=>!l.siri);let i=/^(.+?)\s*\((premium|enhanced)\)$/i.exec(s),o=(i?i[1]:s.replace(/\s*\(.*\)\s*$/,"")).trim().toLowerCase(),a=Z(e.filter(l=>l.name.toLowerCase()===o),n);return(i?a.find(l=>l.quality===i[2].toLowerCase()):void 0)??a[0]??null}function Xt(t,e,n=new Set){let s=new Map;if(!e.length)return s;let r=new Set([...n].map(o=>o.toLowerCase())),i="female";for(let o of t){let a=o.gender==="female"||o.gender==="male",c=a?o.gender:i,l=e.filter(d=>!r.has(d.name.toLowerCase())),u=l.find(d=>d.gender===c)??(a?e.find(d=>d.gender===c):void 0)??l[0]??e[s.size%e.length];s.set(o.id,u),r.add(u.name.toLowerCase()),a||(i=i==="female"?"male":"female")}return s}import{spawn as ee}from"child_process";import{readFileSync as xs,writeFileSync as $s}from"fs";import{tmpdir as vs}from"os";import{join as Is}from"path";var ks=new Set("the and is are was were i you he she we they it this that to of in for with not but yes what have has will would can your my".split(" ")),ws=new Set("le la les des du de un une et est sont je tu il elle nous vous ils elles ce cette c'est pas pour que qui avec dans sur au aux mais tr\xE8s oui non merci bonjour votre mon".split(" ")),Ss=/[éèêëàâçùûîïôœ]/;function Q(t){let e=(t.match(/[؀-ۿ]/g)??[]).length,n=(t.match(/[a-zA-ZÀ-ÿ]/g)??[]).length;if(e&&e>=n)return"ar";let s=0,r=0;for(let i of t.toLowerCase().replace(/[’]/g,"'").match(/[a-zà-ÿœ']+/g)??[])ks.has(i)&&s++,ws.has(i)||i.startsWith("l'")||i.startsWith("d'")||i.startsWith("qu'")?r++:Ss.test(i)&&(r+=.5);return s===r?null:s>r?"en":"fr"}var qt=t=>t&&t!==1?Math.round(175*t):null,te=t=>t&&t!==1?Math.min(1.2,Math.max(.7,t)):null;function As(){if(process.env.ELEVENLABS_API_KEY)return process.env.ELEVENLABS_API_KEY;for(let t of[`${process.env.HOME}/.elevenlabs/key`,`${process.env.HOME}/.agentx/elevenlabs-key.txt`])try{let e=xs(t,"utf8").trim();if(e)return e}catch{}return null}function Qo(t=As()){let e=0;return async(n,s)=>{if(n.voice.provider==="system")return null;if(!t){if(n.voice.fallback)return null;throw new Error("ElevenLabs is the voice provider but no key is set")}try{let r=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${n.voice.elevenlabs}/stream?output_format=mp3_44100_128`,{method:"POST",headers:{"xi-api-key":t,"Content-Type":"application/json"},body:JSON.stringify({text:n.text,model_id:"eleven_flash_v2_5",...te(n.voice.rate)?{voice_settings:{speed:te(n.voice.rate)}}:{}}),signal:s});if(!r.ok)throw new Error(`ElevenLabs ${r.status}: ${(await r.text()).slice(0,160)}`);let i=Is(vs(),`agentx-say-${process.pid}-${++e}.mp3`);return $s(i,Buffer.from(await r.arrayBuffer())),i}catch(r){if(s.aborted||!n.voice.fallback)throw r;return j(`elevenlabs:${String(r?.message??r).slice(0,40)}`,`[voice] ElevenLabs failed (${String(r?.message??r).slice(0,160)}); speaking with the system voice`),null}}}function Jt(t,e){let n=t.languages&&Q(e);return n&&t.languages&&n in t.languages?t.languages[n]:t.system}var _s=(t,e="")=>{let n=Jt(t,e),s=qt(t.rate);return[...n&&!Ut(n)?["-v",n]:[],...s?["-r",String(s)]:[]]};function Rs(t,e,n){if(!n)return["say",_s(t,e)];let s=Jt(t,e);return["/bin/sh",[n,...s?[s]:[]]]}function ea(t){let e=t.split(/\s+/).filter(Boolean).length;return Math.min(300,5+Math.floor(e*6/10))*1e3}function ta(t=Yt()){if(t)try{ee("/bin/sh",[t,"--stop"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function Yt(t={},e){if(!Ie(t))return null;try{return Bt(e)}catch(n){return j("siri-say",`[voice] could not write the Siri voice script (${String(n?.message??n).split(`
111
- `)[0]}); Siri voices will not switch`),null}}var na=(t,e)=>{if(!t){let[n,s]=Rs(e.voice,e.text,Yt()),r=qt(e.voice.rate),i=r?{...process.env,AGENTX_SAY_RATE:String(r)}:process.env,o=ee(n,s,{stdio:["pipe","ignore","ignore"],env:i});return o.stdin?.on("error",()=>{}),o.stdin?.end(e.text),o}return process.platform==="darwin"?ee("afplay",[t],{stdio:"ignore"}):ee("mpg123",["-q",t],{stdio:"ignore"})};import{spawn as Zt}from"child_process";import{accessSync as Cs,constants as Ts,readFileSync as Qt}from"fs";import{homedir as Es}from"os";import{basename as O,delimiter as en,dirname as Ds,extname as Ls,join as Te}from"path";var C={ms:2*60*1e3,bitsPerSecond:64e3,bytes:2*1024*1024};function tn(t){let e=Array.isArray(t)?t[0]:t;return!e||!/^\d{1,9}$/.test(e.trim())?{status:400,error:"Say how long the recording is (X-Audio-Duration-Ms)."}:Number(e)>C.ms+2e3?{status:413,error:De()}:null}var De=()=>`The recording is longer than ${C.ms/6e4} minutes.`,Ps={"audio/webm":"webm","video/webm":"webm","audio/ogg":"ogg","audio/mp4":"m4a","video/mp4":"m4a","audio/x-m4a":"m4a","audio/aac":"aac","audio/mpeg":"mp3","audio/wav":"wav","audio/x-wav":"wav","audio/wave":"wav"};function nn(t){let e=String(t||"").split(";")[0].trim().toLowerCase();return Ps[e]??null}function rn(t,e){let n=[];return t!=="local"&&e.key&&n.push("elevenlabs"),e.ffmpeg&&(e.mlx?n.push("mlx-whisper"):e.whisper&&n.push("whisper")),n}function Le(t,e){return t==="local"&&e.key&&!e.ffmpeg?"Speech to text is set to local, and this computer has no ffmpeg.":(e.mlx||e.whisper)&&!e.ffmpeg?"This computer has Whisper but no ffmpeg to read the recording.":"Add an ElevenLabs key on this computer, or install mlx-whisper and ffmpeg."}function Ee(t,e,n=process.env.PATH??""){let s=Es(),r=[Te(s,".local","bin"),"/opt/homebrew/bin","/usr/local/bin",...n.split(en).filter(Boolean)];for(let i of[e,...r.map(o=>Te(o,t))])if(i)try{return Cs(i,Ts.X_OK),i}catch{}return null}function la(t){return{key:t,mlx:Ee("mlx_whisper",process.env.AGENTX_MLX_WHISPER),whisper:Ee("whisper",process.env.AGENTX_WHISPER),ffmpeg:js()}}var js=()=>Ee("ffmpeg",process.env.AGENTX_FFMPEG);async function sn(t,e){return e?Os(t,e):null}async function Os(t,e){let n=String(C.ms/1e3+5);try{let r=[...(await Ns(e,["-nostdin","-hide_banner","-t",n,"-i",t,"-f","null","-"],3e4)).matchAll(/time=(\d+):(\d+):(\d+(?:\.\d+)?)/g)],i=r[r.length-1];return i?Number(i[1])*3600+Number(i[2])*60+Number(i[3]):null}catch{return null}}async function on(t,e,n,s){let r=new FormData;r.set("model_id",process.env.AGENTX_STT_MODEL||"scribe_v1"),r.set("file",new Blob([Qt(t)],{type:e}),O(t));let i=await fetch("https://api.elevenlabs.io/v1/speech-to-text",{method:"POST",headers:{"xi-api-key":n},body:r,signal:s??AbortSignal.timeout(6e4)});if(!i.ok)throw new Error(`ElevenLabs ${i.status}: ${(await i.text().catch(()=>"")).slice(0,160)}`);let o=await i.json();if(typeof o.text!="string")throw new Error("ElevenLabs returned no text");return o.text.trim()}async function an(t,e,n,s,r){let i=t==="mlx-whisper"?["--model",process.env.AGENTX_MLX_MODEL||"mlx-community/whisper-large-v3-turbo","--output-format","txt","--output-dir",r,n]:[n,"--model",process.env.AGENTX_WHISPER_MODEL||"base","--output_format","txt","--output_dir",r,"--fp16","False"],o={...process.env,PATH:`${Ds(s)}${en}${process.env.PATH??""}`};await Ms(e,i,12e4,o);try{return Qt(Te(r,O(n,Ls(n))+".txt"),"utf8").trim()}catch{throw new Error(`${t} wrote no transcript`)}}function Ns(t,e,n){return new Promise((s,r)=>{let i=Zt(t,e,{stdio:["ignore","ignore","pipe"]}),o="",a=setTimeout(()=>{i.kill("SIGKILL"),r(new Error(`${O(t)} took too long`))},n);i.stderr.on("data",c=>{o=(o+c).slice(-8192)}),i.on("error",c=>{clearTimeout(a),r(c)}),i.on("exit",c=>{clearTimeout(a),c===0?s(o):r(new Error(`${O(t)} exited ${c}`))})})}function Ms(t,e,n,s=process.env){return new Promise((r,i)=>{let o=Zt(t,e,{stdio:["ignore","pipe","pipe"],env:s}),a="",c="",l=setTimeout(()=>{o.kill("SIGKILL"),i(new Error(`${O(t)} took longer than ${n/1e3}s`))},n);o.stdout.on("data",u=>{a.length<4096&&(a+=u)}),o.stderr.on("data",u=>{c.length<4096&&(c+=u)}),o.on("error",u=>{clearTimeout(l),i(u)}),o.on("exit",u=>{clearTimeout(l),u===0?r(a):i(new Error(`${O(t)} exited ${u}: ${c.trim().split(`
112
- `).pop()?.slice(0,160)??""}`))})})}function ln(t,e=800){let n=t;return n=n.replace(/```[\s\S]*?```/g,". "),n=n.replace(/`[^`]*`/g,""),n=n.replace(/\*\*(.*?)\*\*/g,"$1"),n=n.replace(/__(.*?)__/g,"$1"),n=n.replace(/\*([^*]+)\*/g,"$1"),n=n.replace(/_([^_]+)_/g,"$1"),n=n.replace(/~~(.*?)~~/g,"$1"),n=n.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1"),n=n.replace(/!\[([^\]]*)\]\([^)]+\)/g,"image$1 "),n=n.replace(/^#{1,6}\s+/gm,""),n=n.replace(/^[\s]*[-*+]\s+/gm,". "),n=n.replace(/^[\s]*\d+\.\s+/gm,". "),n=n.replace(/^[-=_]{3,}$/gm,""),n=n.replace(/^>\s*/gm,""),n=n.replace(/https?:\/\/\S+/g,"link"),n=n.replace(/\/\w+(\/\w+)+/g,s=>s.split("/").filter(Boolean).join(" slash ")),n=n.replace(/&/g," and "),n=n.replace(/@/g," at "),n=n.replace(/=>/g," returns "),n=n.replace(/->/g," to "),n=n.replace(/\|/g," or "),n=n.replace(/\be\.g\./gi,"for example"),n=n.replace(/\bi\.e\./gi,"that is"),n=n.replace(/\betc\./gi,"etcetera"),n=n.replace(/\bvs\.?\b/gi,"versus"),n=n.replace(/\n{2,}/g,". "),n=n.replace(/\n/g," "),n=n.replace(/\s+/g," "),n=n.replace(/\.\s*\./g,"."),n=n.replace(/\s+([.,!?])/g,"$1"),n=n.trim().replace(/^[.,:;]+\s*/,""),n.length>e&&(n=n.slice(0,e).replace(/\s+\S*$/,"")+"..."),n}var Vs="system",Fs=t=>t.trim().toLowerCase()===Vs,Us="21m00Tcm4TlvDq8ikWAM";function je(t,e,n={},s=_e()){let r=e[t],i=r?.name||t,o=r?.voice,a=zs(e,n,s).get(t)??null,c=Hs(t,o?.system,o?.gender,n,s);return{agentId:t,name:i,provider:o?.provider??n.provider??"system",elevenlabsVoiceId:o?.elevenlabsVoiceId||null,systemVoice:a?.id??null,systemVoiceName:a?gn(a):null,systemByLanguage:c,fallback:(n.fallback??"system")==="system",gender:o?.gender??null,style:o?.style||null,intro:o?.intro||Gs(i,r?.systemPrompt),...o?.rate?{rate:o.rate}:{},...o?.priority?{priority:o.priority}:{}}}var gn=t=>`${t.name}${t.siri?" (Siri)":t.quality==="standard"?"":` (${t.quality[0].toUpperCase()}${t.quality.slice(1)})`} ${t.locale}`;function Bs(t,e,n,s){if(!e||!n.length)return null;let r=Ce(e,n,s);return r||j(`${t}:${e}`,`[voice] ${t}: system voice "${e}" is not installed; using the next choice. Run \`agentx voice list\` to see installed voices.`),r}var fn=t=>t.toLowerCase().split(/[-_]/)[0],cn=(t,e)=>typeof t=="string"?t:t?.[fn(e)];function Pe(t,e,n,s){if(e!==void 0)return Fs(e)?null:Bs(t,e,n,s)??void 0}var mn=(t,e)=>!t||!t.gender||t.gender==="neutral"||!e||e==="neutral"||t.gender===e;function Ws(t,e,n,s=new Set){let r=e.locale??"en",i=new Map,o=[],a=Pe("voice.system",cn(e.system,r),n,r);for(let l of t){let u=Pe(l.id,cn(l.system,r),n,r),d=u!==void 0?u:a!==void 0&&mn(a,l.gender)?a:void 0;d!==void 0?i.set(l.id,d):o.push({id:l.id,gender:l.gender??null})}let c=new Set([...s,...[...i.values()].flatMap(l=>l?[l.name]:[])]);for(let[l,u]of Xt(o,Z(n.filter(d=>!d.siri),r),c))i.set(l,u);return i}function Hs(t,e,n,s,r){if(typeof e=="string")return{};let i={},o=(a,c,l)=>{if(!(!c||typeof c=="string"))for(let[u,d]of Object.entries(c)){let g=Pe(`${a}.${u}`,d,r,u);g!==void 0&&l(g)&&(i[fn(u)]=g)}};return o("voice.system",s.system,a=>mn(a,n)),o(t,e,()=>!0),i}function fa(t,e){let n=e?Q(e):null;if(!n||!(n in t.systemByLanguage))return t;let s=t.systemByLanguage[n];return{...t,systemVoice:s?.id??null,systemVoiceName:s?gn(s):null}}function zs(t,e={},n=_e()){let s=Object.entries(t).map(([r,i])=>({id:r,system:i.voice?.system,gender:i.voice?.gender}));return Ws(s,e,n)}function Oe(t,e){let n={provider:t.provider,elevenlabs:Ks(e,t.elevenlabsVoiceId),system:t.systemVoice,fallback:t.fallback},s=Object.entries(t.systemByLanguage??{});return s.length&&(n.languages=Object.fromEntries(s.map(([r,i])=>[r,i?.id??null]))),t.rate&&t.rate!==1&&(n.rate=t.rate),t.priority&&t.priority!=="normal"&&(n.priority=t.priority),n}function Ks(t,e){return t||e||process.env.AGENTX_VOICE_ID||Us}function Gs(t,e){let n=(e??"").split(/(?<=\.)\s/)[0]??"",s=/^You are (.+?)\.?$/i.exec(n.trim());if(!s)return`Hello, this is ${t}.`;let r=s[1].replace(/\s*\([^)]*\)/g,"").trim(),[i,...o]=r.split(/,\s*/),a=o.join(", ");return a&&i.toLowerCase()===t.toLowerCase()?`Hello, this is ${t}, ${a}.`:!/^an? /i.test(r)&&r.toLowerCase().includes(t.toLowerCase())?`Hello, this is ${r}.`:`Hello, this is ${t}, ${r}.`}var Xs=8*60*60*1e3,qs=500,un=class{constructor(e=Xs){this.gapMs=e}lastSpoke=new Map;needsIntro(e,n,s=Date.now()){let r=this.lastSpoke.get(dn(e,n));return r===void 0||s-r>this.gapMs}spoke(e,n,s=Date.now()){let r=dn(e,n);this.lastSpoke.delete(r),this.lastSpoke.set(r,s),this.lastSpoke.size>qs&&this.lastSpoke.delete(this.lastSpoke.keys().next().value)}},dn=(t,e)=>`${t}\0${e}`;function pn(t,e){let n=t.style?` Your speaking manner: ${t.style}.`:"";return e?`[VOICE INTRO] This is your first spoken exchange with this person in a while. Open with one short sentence introducing yourself in your own manner, along the lines of "${t.intro}", then answer.${n}`:"[VOICE CASUAL] You have already introduced yourself in this voice conversation. Do not introduce yourself or greet again; talk casually, like a colleague in the same office."+n}function ma(t,e,n,s={}){let r=e[t],i=je(t,e,s),o=(r?.systemPrompt??"").split(/\n\s*\n/)[0].slice(0,600).trim();return{agentId:t,name:i.name,voice:Oe(i),persona:o||`You are ${i.name}.`,introLine:pn(i,n)}}var Js="[VOICE MODE] This question arrived by voice and your reply will be spoken aloud by a TTS engine. Answer in two or three short sentences. Plain language, no markdown, no code blocks, no bullet points, no URLs. Speak conversationally.";function pa(t){let e=t;if(e?.channel!=="voice"||!e.voice||typeof e.voice!="object")return;let n=i=>typeof i=="string"?i.replace(/\s+/g," ").slice(0,200):"",s=n(e.voice.intro),r={agentId:"",name:"",provider:"system",elevenlabsVoiceId:null,systemVoice:null,systemVoiceName:null,systemByLanguage:{},fallback:!0,gender:null,style:n(e.voice.style)||null,intro:s||"Hello."};return`${Js}
113
- ${pn(r,e.voice.introduce===!0&&!!s)}`}import{mkdtemp as Ys,rm as Zs,writeFile as Qs}from"fs/promises";import{tmpdir as ei}from"os";import{join as hn}from"path";var ti=1500,ni=64*1024,ri=2,Ne=0;function Aa(t){return t==="/voice/transcribe"||t==="/voice/speak"}async function _a(t,e,n,s){return t.method!=="POST"?b(e,405,{error:"POST"}):n==="/voice/transcribe"?si(t,e,s):ai(t,e,s)}async function si(t,e,n){let s=String(t.headers["content-type"]||""),r=nn(s);if(!r)return b(e,415,{error:"Send the recording as audio (webm, mp4, ogg, mp3 or wav)."});let i=tn(t.headers["x-audio-duration-ms"]);if(i)return t.resume(),b(e,i.status,{error:i.error});let o=await yn(t,C.bytes);if(!o)return b(e,413,{error:ui()});if(!o.length)return b(e,400,{error:"The recording is empty."});if(Ne>=ri)return b(e,429,{error:"This computer is already writing down other recordings. Try again in a moment."});let a=n.stt(),c=n.host(),l=rn(a,c);if(!c.ffmpeg&&!n.allowUnmeasured?.()){let d=n.nodeName?`on ${n.nodeName}`:"on this computer",g=l.length?"":" "+Le(a,c);return b(e,503,{error:"Voice input isn't set up on this computer.",hint:`Install ffmpeg ${d} for voice input from the phone.${g}`,setup:!1})}if(!l.length)return b(e,503,{error:"Voice input isn't set up on this computer.",hint:Le(a,c),setup:!1});Ne++;let u;try{let d=await Ys(hn(ei(),"agentx-phone-voice-"));try{u=await ii(d,`speech.${r}`,o,s,c,l,n)}finally{await Zs(d,{recursive:!0,force:!0}).catch(()=>{})}}finally{Ne--}b(e,u[0],u[1])}async function ii(t,e,n,s,r,i,o){let a=hn(t,e);if(await Qs(a,n,{mode:384}),r.ffmpeg){let l=await(o.measure??sn)(a,r.ffmpeg);if(l==null)return[422,{error:"This computer couldn't read the recording. Try again."}];if(l*1e3>C.ms+2e3)return[413,{error:De()}]}let c=[];for(let l of i)try{let u=await oi(l,a,s,r,t,o);return o.log(`[voice] phone recording transcribed with ${l} (${Math.round(n.length/1024)} KB)`),u?[200,{text:u,engine:l}]:[422,{error:"No words were heard. Hold the orb and speak, then let go.",engine:l}]}catch(u){let d=String(u?.message??u).split(`
114
- `)[0].slice(0,200);c.push(`${l}: ${d}`),o.log(`[voice] phone transcription with ${l} failed: ${d}`)}return[502,{error:"Speech to text failed on this computer.",detail:c.join("; ")}]}function oi(t,e,n,s,r,i){let o=i.engines?.[t];if(o)return o(e,n,s,r);if(t==="elevenlabs")return on(e,n,s.key);let a=t==="mlx-whisper"?s.mlx:s.whisper;return an(t,a,e,s.ffmpeg,r)}async function ai(t,e,n){let s=await yn(t,ni);if(!s)return b(e,413,{error:"request too large"});let r;try{r=JSON.parse(s.toString("utf8")||"{}")}catch{return b(e,400,{error:"expected JSON"})}let i=typeof r?.agent=="string"?r.agent:"",o=typeof r?.peer=="string"&&r.peer?r.peer:void 0;if(!i)return b(e,400,{error:"agent is required"});let a=li(typeof r?.text=="string"?r.text:"");if(!a)return b(e,422,{error:"Nothing in this answer can be said aloud."});let c=n.voiceOf(i,o);if(!c)return b(e,404,{error:`Unknown agent: ${i}`});let l=(d,g=200)=>b(e,g,{fallback:"browser",reason:d,text:a});if(c.provider!=="elevenlabs")return l("This agent speaks with a system voice, which only plays on the computer.");let u=n.elevenLabsKey();if(!u)return l("No ElevenLabs key is set on this computer.");try{let d=await(n.synth??ci)(u,c,a);e.writeHead(200,{"Content-Type":"audio/mpeg","Content-Length":d.length,"Cache-Control":"no-store","X-Spoken-Chars":String(a.length)}),e.end(d)}catch(d){return n.log(`[voice] phone answer synthesis failed: ${String(d?.message??d).split(`
115
- `)[0].slice(0,160)}`),l("ElevenLabs could not speak this answer.",502)}}function li(t){let e=Dt(Ge(t).text).cleanText.replace(/!\[[^\]\n]*\]\([^)\n]*\)/g,"");return ln(e,ti)}async function ci(t,e,n){let s=te(e.rate),r=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(e.elevenlabs)}?output_format=mp3_44100_128`,{method:"POST",headers:{"xi-api-key":t,"Content-Type":"application/json"},body:JSON.stringify({text:n,model_id:"eleven_flash_v2_5",...s?{voice_settings:{speed:s}}:{}}),signal:AbortSignal.timeout(6e4)});if(!r.ok)throw new Error(`ElevenLabs ${r.status}: ${(await r.text().catch(()=>"")).slice(0,160)}`);return Buffer.from(await r.arrayBuffer())}var ui=()=>`The recording is larger than ${C.bytes/1024/1024} MB, more than ${C.ms/6e4} minutes of speech.`;function Ra(t,e,n,s){if(e)return s.speakerOn(e,t,!1)?.voice??null;let r=n.agents??{};return r[t]?Oe(je(t,r,n.voice)):null}function yn(t,e){return Number(t.headers["content-length"])>e?(t.resume(),Promise.resolve(null)):new Promise((n,s)=>{let r=[],i=0;t.on("data",o=>{if(!(i>e)){if(i+=o.length,i>e){r.length=0,n(null);return}r.push(o)}}),t.on("end",()=>{i<=e&&n(Buffer.concat(r))}),t.on("error",s)})}function b(t,e,n){t.writeHead(e,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(n))}import{existsSync as x,readFileSync as Ue,writeFileSync as Be,mkdirSync as ne,readdirSync as Fe,rmSync as di,statSync as I}from"fs";import{resolve as bn,relative as gi,dirname as We,join as T,extname as U,basename as He}from"path";var S=200*1024,kn=new Set([".md",".markdown",".txt"]),N=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"]),fi=6,mi=new Set(["CLAUDE.md","SOUL.md","IDENTITY.md","PERSONA.md","AGENT.md","BOOTSTRAP.md"]);function _(t,e){if(!t)throw new Error("Agent workspace is not configured.");let n=bn(t);if(x(n)||ne(n,{recursive:!0}),!e||e.startsWith("/")||e.match(/^[a-zA-Z]:/))throw new Error(`Path must be relative to the workspace: ${e}`);let s=bn(n,e);if(gi(n,s).startsWith(".."))throw new Error(`Path escapes the workspace: ${e}`);return s}function wn(t){let e=U(t).toLowerCase();if(!kn.has(e))throw new Error(`Only text files (.md, .markdown, .txt) can be edited from the admin panel (got ${e}).`)}function Me(t,e){let n=t.split(/\r?\n/).find(s=>s.trim().startsWith("#"));return n&&n.replace(/^#+\s*/,"").trim().slice(0,120)||e}function Da(t){let e=_(t,"."),n=[],s=new Set,r=[];try{r=Fe(e)}catch{}for(let a of mi){let c=T(e,a);if(x(c)&&I(c).isFile()){let l=I(c).size,u=l>0&&l<S?Ve(c):"";n.push({path:a,title:Me(u,a),size:l,exists:!0}),s.add(a)}else n.push({path:a,title:a,size:0,exists:!1}),s.add(a)}for(let a of r){if(s.has(a))continue;let c=T(e,a);try{let l=I(c);if(!l.isFile()||!kn.has(U(a).toLowerCase()))continue;let u=l.size>0&&l.size<S?Ve(c):"";n.push({path:a,title:Me(u,a),size:l.size,exists:!0})}catch{}}let i=[],o=T(e,".claude","skills");if(x(o))try{for(let a of Fe(o)){let c=T(o,a),l;try{l=I(c)}catch{continue}if(!l.isDirectory())continue;let u=T(c,"SKILL.md");if(!x(u))continue;let d=I(u),g=d.size<S?Ve(u):"";i.push({slug:a,title:Me(g,a),size:d.size,path:`.claude/skills/${a}/SKILL.md`})}}catch{}return i.sort((a,c)=>a.slug.localeCompare(c.slug)),{identity:n,skills:i,workspace:e}}function Ve(t){try{return Ue(t,"utf-8")}catch{return""}}function La(t,e){let n=_(t,e);if(wn(n),!x(n))return{path:e,content:""};if(I(n).size>S)throw new Error(`File is too large to edit in the admin panel (> ${S/1024} KB).`);return{path:e,content:Ue(n,"utf-8")}}function Pa(t,e,n){let s=_(t,e);wn(s);let r=Buffer.from(n,"utf-8");if(r.length>S)throw new Error(`File too large (${r.length} > ${S} bytes).`);return ne(We(s),{recursive:!0}),Be(s,r),{path:e,bytes:r.length}}function ja(t,e,n={}){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=_(t,s);if(x(r))throw new Error(`Skill "${e}" already exists.`);ne(We(r),{recursive:!0});let i=n.content?.trim()?n.content:pi(e,n.title);return Be(r,i),{slug:e,path:s}}function Oa(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=_(t,`.claude/skills/${e}`);if(!x(n))throw new Error(`Skill "${e}" not found.`);if(!I(n).isDirectory())throw new Error(`Skill path is not a directory: ${e}`);return di(n,{recursive:!0,force:!0}),{slug:e}}function Na(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=_(t,`.claude/skills/${e}`);if(!x(n))throw new Error(`Skill "${e}" not found.`);let s=[];return r(n,"",0,s),s.sort((i,o)=>i.kind!==o.kind?i.kind==="dir"?-1:1:i.path.localeCompare(o.path)),s;function r(i,o,a,c){if(a>fi)return;let l=[];try{l=Fe(i)}catch{return}for(let u of l){if(u==="node_modules"||u===".git")continue;let d=T(i,u),g=o?`${o}/${u}`:u,f;try{f=I(d)}catch{continue}if(f.isDirectory())c.push({path:`${g}/`,kind:"dir",size:0,editable:!1}),r(d,g,a+1,c);else if(f.isFile()){let m=U(u).toLowerCase(),h=N.has(m)||N.has(u.toLowerCase());c.push({path:g,kind:"file",size:f.size,editable:h&&f.size<S})}}}}function Ma(t,e,n){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);if(!n||n.includes(".."))throw new Error(`Invalid file path: ${n}`);let s=_(t,`.claude/skills/${e}/${n}`);if(!x(s)||!I(s).isFile())throw new Error(`File not found: ${n}`);let r=U(s).toLowerCase(),i=He(s).toLowerCase();if(!N.has(r)&&!N.has(i))throw new Error(`File type not editable: ${n}`);if(I(s).size>S)throw new Error(`File too large to edit (> ${S/1024} KB): ${n}`);return{path:n,content:Ue(s,"utf-8")}}function Va(t,e,n,s){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);if(!n||n.includes(".."))throw new Error(`Invalid file path: ${n}`);let r=_(t,`.claude/skills/${e}/${n}`),i=U(r).toLowerCase(),o=He(r).toLowerCase();if(!N.has(i)&&!N.has(o))throw new Error(`File type not editable: ${n}`);let a=Buffer.from(s,"utf-8");if(a.length>S)throw new Error(`File too large (${a.length} > ${S} bytes).`);return ne(We(r),{recursive:!0}),Be(r,a),{path:n,bytes:a.length}}function Fa(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=_(t,`.claude/skills/${e}`);if(!x(n))throw new Error(`Skill "${e}" not found.`);let s=r=>x(T(n,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 pi(t,e){return`# ${e?.trim()||t}
107
+ out.join("\\n")`,ms=new Set(["Fred","Kathy","Ralph","Junior"]),hs={Flo:"female",Sandy:"female",Shelley:"female",Grandma:"female",Kathy:"female",Eddy:"male",Reed:"male",Rocko:"male",Grandpa:"male",Fred:"male",Ralph:"male",Junior:"male"};function zt(t){let e=[];for(let n of t.split(`
108
+ `)){let[s,r,i,o,a]=n.split(" ");!s||!r||!i||s.includes(".siri_")||s.startsWith("com.apple.speech.synthesis.voice.")&&!ms.has(r)||e.push({id:s,name:r,locale:i,quality:o==="3"?"premium":o==="2"?"enhanced":"standard",gender:a==="1"?"male":a==="2"?"female":hs[r]??null})}return e}var ys=10*60*1e3,P=null,_e=!1;function Re(t=Date.now()){if(process.platform!=="darwin")return[];if(P)t-P.at>ys&&!_e&&(_e=!0,fs("osascript",["-l","JavaScript","-e",Ht],{timeout:1e4},(e,n)=>{_e=!1,e||(P={at:Date.now(),voices:[...zt(String(n)),...Y()]})}));else try{P={at:t,voices:[...zt(ps("osascript",["-l","JavaScript","-e",Ht],{encoding:"utf8",timeout:1e4})),...Y()]}}catch(e){Ce(`[voice] could not list system voices: ${String(e?.message??e).split(`
109
+ `)[0]}`),P={at:t,voices:Y()}}return P.voices}var Ce=t=>process.stderr.write(t+`
110
+ `),Kt=new Set;function zo(t){Ce=t}function O(t,e){Kt.has(t)||(Kt.add(t),Ce(e))}var bs={premium:3,enhanced:2,standard:1},ks=new Set(["Grandma","Grandpa"]);function Gt(t){let e=t.id.startsWith("com.apple.voice.")?2:t.id.startsWith("com.apple.eloquence.")&&!ks.has(t.name)?1:0;return bs[t.quality]*10+e}var Xt=t=>t.toLowerCase().split(/[-_]/)[0];function Z(t,e="en"){let n=e.toLowerCase().replace("_","-"),s=Xt(e),r=t.filter(i=>Xt(i.locale)===s);return(r.length?r:t).slice().sort((i,o)=>Gt(o)-Gt(i)||+(o.locale.toLowerCase()===n)-+(i.locale.toLowerCase()===n)||i.name.localeCompare(o.name)||i.locale.localeCompare(o.locale))}function Te(t,e,n="en"){let s=t.trim();if(!s)return null;let r=e.find(l=>l.id===s);if(r)return r;if(s.toLowerCase().startsWith(Ie)){let l=s.slice(Ie.length).trim().toLowerCase(),u=Z(e.filter(g=>g.siri&&g.name.toLowerCase()===l),n)[0];if(u||!l)return u??null;let d=Te(l,e,n);return d&&O(`siri:${l}`,`[voice] Siri voice "${l}" is not installed; speaking with ${d.name} (${d.locale}) instead.`),d}e=e.filter(l=>!l.siri);let i=/^(.+?)\s*\((premium|enhanced)\)$/i.exec(s),o=(i?i[1]:s.replace(/\s*\(.*\)\s*$/,"")).trim().toLowerCase(),a=Z(e.filter(l=>l.name.toLowerCase()===o),n);return(i?a.find(l=>l.quality===i[2].toLowerCase()):void 0)??a[0]??null}function qt(t,e,n=new Set){let s=new Map;if(!e.length)return s;let r=new Set([...n].map(o=>o.toLowerCase())),i="female";for(let o of t){let a=o.gender==="female"||o.gender==="male",c=a?o.gender:i,l=e.filter(d=>!r.has(d.name.toLowerCase())),u=l.find(d=>d.gender===c)??(a?e.find(d=>d.gender===c):void 0)??l[0]??e[s.size%e.length];s.set(o.id,u),r.add(u.name.toLowerCase()),a||(i=i==="female"?"male":"female")}return s}import{spawn as ee}from"child_process";import{readFileSync as $s,writeFileSync as vs}from"fs";import{tmpdir as Is}from"os";import{join as As}from"path";var ws=new Set("the and is are was were i you he she we they it this that to of in for with not but yes what have has will would can your my".split(" ")),Ss=new Set("le la les des du de un une et est sont je tu il elle nous vous ils elles ce cette c'est pas pour que qui avec dans sur au aux mais tr\xE8s oui non merci bonjour votre mon".split(" ")),xs=/[éèêëàâçùûîïôœ]/;function Q(t){let e=(t.match(/[؀-ۿ]/g)??[]).length,n=(t.match(/[a-zA-ZÀ-ÿ]/g)??[]).length;if(e&&e>=n)return"ar";let s=0,r=0;for(let i of t.toLowerCase().replace(/[’]/g,"'").match(/[a-zà-ÿœ']+/g)??[])ws.has(i)&&s++,Ss.has(i)||i.startsWith("l'")||i.startsWith("d'")||i.startsWith("qu'")?r++:xs.test(i)&&(r+=.5);return s===r?null:s>r?"en":"fr"}var Jt=t=>t&&t!==1?Math.round(175*t):null,te=t=>t&&t!==1?Math.min(1.2,Math.max(.7,t)):null;function _s(){if(process.env.ELEVENLABS_API_KEY)return process.env.ELEVENLABS_API_KEY;for(let t of[`${process.env.HOME}/.elevenlabs/key`,`${process.env.HOME}/.agentx/elevenlabs-key.txt`])try{let e=$s(t,"utf8").trim();if(e)return e}catch{}return null}function ta(t=_s()){let e=0;return async(n,s)=>{if(n.voice.provider==="system")return null;if(!t){if(n.voice.fallback)return null;throw new Error("ElevenLabs is the voice provider but no key is set")}try{let r=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${n.voice.elevenlabs}/stream?output_format=mp3_44100_128`,{method:"POST",headers:{"xi-api-key":t,"Content-Type":"application/json"},body:JSON.stringify({text:n.text,model_id:"eleven_flash_v2_5",...te(n.voice.rate)?{voice_settings:{speed:te(n.voice.rate)}}:{}}),signal:s});if(!r.ok)throw new Error(`ElevenLabs ${r.status}: ${(await r.text()).slice(0,160)}`);let i=As(Is(),`agentx-say-${process.pid}-${++e}.mp3`);return vs(i,Buffer.from(await r.arrayBuffer())),i}catch(r){if(s.aborted||!n.voice.fallback)throw r;return O(`elevenlabs:${String(r?.message??r).slice(0,40)}`,`[voice] ElevenLabs failed (${String(r?.message??r).slice(0,160)}); speaking with the system voice`),null}}}function Yt(t,e){let n=t.languages&&Q(e);return n&&t.languages&&n in t.languages?t.languages[n]:t.system}var Rs=(t,e="")=>{let n=Yt(t,e),s=Jt(t.rate);return[...n&&!Bt(n)?["-v",n]:[],...s?["-r",String(s)]:[]]};function Cs(t,e,n){if(!n)return["say",Rs(t,e)];let s=Yt(t,e);return["/bin/sh",[n,...s?[s]:[]]]}function na(t){let e=t.split(/\s+/).filter(Boolean).length;return Math.min(300,5+Math.floor(e*6/10))*1e3}function ra(t=Zt()){if(t)try{ee("/bin/sh",[t,"--stop"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function Zt(t={},e){if(!Ae(t))return null;try{return Wt(e)}catch(n){return O("siri-say",`[voice] could not write the Siri voice script (${String(n?.message??n).split(`
111
+ `)[0]}); Siri voices will not switch`),null}}var sa=(t,e)=>{if(!t){let[n,s]=Cs(e.voice,e.text,Zt()),r=Jt(e.voice.rate),i=r?{...process.env,AGENTX_SAY_RATE:String(r)}:process.env,o=ee(n,s,{stdio:["pipe","ignore","ignore"],env:i});return o.stdin?.on("error",()=>{}),o.stdin?.end(e.text),o}return process.platform==="darwin"?ee("afplay",[t],{stdio:"ignore"}):ee("mpg123",["-q",t],{stdio:"ignore"})};import{spawn as Qt}from"child_process";import{accessSync as Ts,constants as Es,readFileSync as en}from"fs";import{homedir as Ds}from"os";import{basename as j,delimiter as tn,dirname as Ls,extname as Ps,join as Ee}from"path";var C={ms:2*60*1e3,bitsPerSecond:64e3,bytes:2*1024*1024};function nn(t){let e=Array.isArray(t)?t[0]:t;return!e||!/^\d{1,9}$/.test(e.trim())?{status:400,error:"Say how long the recording is (X-Audio-Duration-Ms)."}:Number(e)>C.ms+2e3?{status:413,error:Le()}:null}var Le=()=>`The recording is longer than ${C.ms/6e4} minutes.`,Os={"audio/webm":"webm","video/webm":"webm","audio/ogg":"ogg","audio/mp4":"m4a","video/mp4":"m4a","audio/x-m4a":"m4a","audio/aac":"aac","audio/mpeg":"mp3","audio/wav":"wav","audio/x-wav":"wav","audio/wave":"wav"};function rn(t){let e=String(t||"").split(";")[0].trim().toLowerCase();return Os[e]??null}function sn(t,e){let n=[];return t!=="local"&&e.key&&n.push("elevenlabs"),e.ffmpeg&&(e.mlx?n.push("mlx-whisper"):e.whisper&&n.push("whisper")),n}function Pe(t,e){return t==="local"&&e.key&&!e.ffmpeg?"Speech to text is set to local, and this computer has no ffmpeg.":(e.mlx||e.whisper)&&!e.ffmpeg?"This computer has Whisper but no ffmpeg to read the recording.":"Add an ElevenLabs key on this computer, or install mlx-whisper and ffmpeg."}function De(t,e,n=process.env.PATH??""){let s=Ds(),r=[Ee(s,".local","bin"),"/opt/homebrew/bin","/usr/local/bin",...n.split(tn).filter(Boolean)];for(let i of[e,...r.map(o=>Ee(o,t))])if(i)try{return Ts(i,Es.X_OK),i}catch{}return null}function ua(t){return{key:t,mlx:De("mlx_whisper",process.env.AGENTX_MLX_WHISPER),whisper:De("whisper",process.env.AGENTX_WHISPER),ffmpeg:js()}}var js=()=>De("ffmpeg",process.env.AGENTX_FFMPEG);async function on(t,e){return e?Ns(t,e):null}async function Ns(t,e){let n=String(C.ms/1e3+5);try{let r=[...(await Ms(e,["-nostdin","-hide_banner","-t",n,"-i",t,"-f","null","-"],3e4)).matchAll(/time=(\d+):(\d+):(\d+(?:\.\d+)?)/g)],i=r[r.length-1];return i?Number(i[1])*3600+Number(i[2])*60+Number(i[3]):null}catch{return null}}async function an(t,e,n,s){let r=new FormData;r.set("model_id",process.env.AGENTX_STT_MODEL||"scribe_v1"),r.set("file",new Blob([en(t)],{type:e}),j(t));let i=await fetch("https://api.elevenlabs.io/v1/speech-to-text",{method:"POST",headers:{"xi-api-key":n},body:r,signal:s??AbortSignal.timeout(6e4)});if(!i.ok)throw new Error(`ElevenLabs ${i.status}: ${(await i.text().catch(()=>"")).slice(0,160)}`);let o=await i.json();if(typeof o.text!="string")throw new Error("ElevenLabs returned no text");return o.text.trim()}async function ln(t,e,n,s,r){let i=t==="mlx-whisper"?["--model",process.env.AGENTX_MLX_MODEL||"mlx-community/whisper-large-v3-turbo","--output-format","txt","--output-dir",r,n]:[n,"--model",process.env.AGENTX_WHISPER_MODEL||"base","--output_format","txt","--output_dir",r,"--fp16","False"],o={...process.env,PATH:`${Ls(s)}${tn}${process.env.PATH??""}`};await Vs(e,i,12e4,o);try{return en(Ee(r,j(n,Ps(n))+".txt"),"utf8").trim()}catch{throw new Error(`${t} wrote no transcript`)}}function Ms(t,e,n){return new Promise((s,r)=>{let i=Qt(t,e,{stdio:["ignore","ignore","pipe"]}),o="",a=setTimeout(()=>{i.kill("SIGKILL"),r(new Error(`${j(t)} took too long`))},n);i.stderr.on("data",c=>{o=(o+c).slice(-8192)}),i.on("error",c=>{clearTimeout(a),r(c)}),i.on("exit",c=>{clearTimeout(a),c===0?s(o):r(new Error(`${j(t)} exited ${c}`))})})}function Vs(t,e,n,s=process.env){return new Promise((r,i)=>{let o=Qt(t,e,{stdio:["ignore","pipe","pipe"],env:s}),a="",c="",l=setTimeout(()=>{o.kill("SIGKILL"),i(new Error(`${j(t)} took longer than ${n/1e3}s`))},n);o.stdout.on("data",u=>{a.length<4096&&(a+=u)}),o.stderr.on("data",u=>{c.length<4096&&(c+=u)}),o.on("error",u=>{clearTimeout(l),i(u)}),o.on("exit",u=>{clearTimeout(l),u===0?r(a):i(new Error(`${j(t)} exited ${u}: ${c.trim().split(`
112
+ `).pop()?.slice(0,160)??""}`))})})}function cn(t,e=800){let n=t;return n=n.replace(/```[\s\S]*?```/g,". "),n=n.replace(/`[^`]*`/g,""),n=n.replace(/\*\*(.*?)\*\*/g,"$1"),n=n.replace(/__(.*?)__/g,"$1"),n=n.replace(/\*([^*]+)\*/g,"$1"),n=n.replace(/_([^_]+)_/g,"$1"),n=n.replace(/~~(.*?)~~/g,"$1"),n=n.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1"),n=n.replace(/!\[([^\]]*)\]\([^)]+\)/g,"image$1 "),n=n.replace(/^#{1,6}\s+/gm,""),n=n.replace(/^[\s]*[-*+]\s+/gm,". "),n=n.replace(/^[\s]*\d+\.\s+/gm,". "),n=n.replace(/^[-=_]{3,}$/gm,""),n=n.replace(/^>\s*/gm,""),n=n.replace(/https?:\/\/\S+/g,"link"),n=n.replace(/\/\w+(\/\w+)+/g,s=>s.split("/").filter(Boolean).join(" slash ")),n=n.replace(/&/g," and "),n=n.replace(/@/g," at "),n=n.replace(/=>/g," returns "),n=n.replace(/->/g," to "),n=n.replace(/\|/g," or "),n=n.replace(/\be\.g\./gi,"for example"),n=n.replace(/\bi\.e\./gi,"that is"),n=n.replace(/\betc\./gi,"etcetera"),n=n.replace(/\bvs\.?\b/gi,"versus"),n=n.replace(/\n{2,}/g,". "),n=n.replace(/\n/g," "),n=n.replace(/\s+/g," "),n=n.replace(/\.\s*\./g,"."),n=n.replace(/\s+([.,!?])/g,"$1"),n=n.trim().replace(/^[.,:;]+\s*/,""),n.length>e&&(n=n.slice(0,e).replace(/\s+\S*$/,"")+"..."),n}var Us="system",Fs=t=>t.trim().toLowerCase()===Us,Bs="21m00Tcm4TlvDq8ikWAM";function je(t,e,n={},s=Re()){let r=e[t],i=r?.name||t,o=r?.voice,a=Ks(e,n,s).get(t)??null,c=zs(t,o?.system,o?.gender,n,s);return{agentId:t,name:i,provider:o?.provider??n.provider??"system",elevenlabsVoiceId:o?.elevenlabsVoiceId||null,systemVoice:a?.id??null,systemVoiceName:a?fn(a):null,systemByLanguage:c,fallback:(n.fallback??"system")==="system",gender:o?.gender??null,style:o?.style||null,intro:o?.intro||Xs(i,r?.systemPrompt),...o?.rate?{rate:o.rate}:{},...o?.priority?{priority:o.priority}:{}}}var fn=t=>`${t.name}${t.siri?" (Siri)":t.quality==="standard"?"":` (${t.quality[0].toUpperCase()}${t.quality.slice(1)})`} ${t.locale}`;function Ws(t,e,n,s){if(!e||!n.length)return null;let r=Te(e,n,s);return r||O(`${t}:${e}`,`[voice] ${t}: system voice "${e}" is not installed; using the next choice. Run \`agentx voice list\` to see installed voices.`),r}var pn=t=>t.toLowerCase().split(/[-_]/)[0],un=(t,e)=>typeof t=="string"?t:t?.[pn(e)];function Oe(t,e,n,s){if(e!==void 0)return Fs(e)?null:Ws(t,e,n,s)??void 0}var mn=(t,e)=>!t||!t.gender||t.gender==="neutral"||!e||e==="neutral"||t.gender===e;function Hs(t,e,n,s=new Set){let r=e.locale??"en",i=new Map,o=[],a=Oe("voice.system",un(e.system,r),n,r);for(let l of t){let u=Oe(l.id,un(l.system,r),n,r),d=u!==void 0?u:a!==void 0&&mn(a,l.gender)?a:void 0;d!==void 0?i.set(l.id,d):o.push({id:l.id,gender:l.gender??null})}let c=new Set([...s,...[...i.values()].flatMap(l=>l?[l.name]:[])]);for(let[l,u]of qt(o,Z(n.filter(d=>!d.siri),r),c))i.set(l,u);return i}function zs(t,e,n,s,r){if(typeof e=="string")return{};let i={},o=(a,c,l)=>{if(!(!c||typeof c=="string"))for(let[u,d]of Object.entries(c)){let g=Oe(`${a}.${u}`,d,r,u);g!==void 0&&l(g)&&(i[pn(u)]=g)}};return o("voice.system",s.system,a=>mn(a,n)),o(t,e,()=>!0),i}function ma(t,e){let n=e?Q(e):null;if(!n||!(n in t.systemByLanguage))return t;let s=t.systemByLanguage[n];return{...t,systemVoice:s?.id??null,systemVoiceName:s?fn(s):null}}function Ks(t,e={},n=Re()){let s=Object.entries(t).map(([r,i])=>({id:r,system:i.voice?.system,gender:i.voice?.gender}));return Hs(s,e,n)}function Ne(t,e){let n={provider:t.provider,elevenlabs:Gs(e,t.elevenlabsVoiceId),system:t.systemVoice,fallback:t.fallback},s=Object.entries(t.systemByLanguage??{});return s.length&&(n.languages=Object.fromEntries(s.map(([r,i])=>[r,i?.id??null]))),t.rate&&t.rate!==1&&(n.rate=t.rate),t.priority&&t.priority!=="normal"&&(n.priority=t.priority),n}function Gs(t,e){return t||e||process.env.AGENTX_VOICE_ID||Bs}function Xs(t,e){let n=(e??"").split(/(?<=\.)\s/)[0]??"",s=/^You are (.+?)\.?$/i.exec(n.trim());if(!s)return`Hello, this is ${t}.`;let r=s[1].replace(/\s*\([^)]*\)/g,"").trim(),[i,...o]=r.split(/,\s*/),a=o.join(", ");return a&&i.toLowerCase()===t.toLowerCase()?`Hello, this is ${t}, ${a}.`:!/^an? /i.test(r)&&r.toLowerCase().includes(t.toLowerCase())?`Hello, this is ${r}.`:`Hello, this is ${t}, ${r}.`}var qs=8*60*60*1e3,Js=500,dn=class{constructor(e=qs){this.gapMs=e}lastSpoke=new Map;needsIntro(e,n,s=Date.now()){let r=this.lastSpoke.get(gn(e,n));return r===void 0||s-r>this.gapMs}spoke(e,n,s=Date.now()){let r=gn(e,n);this.lastSpoke.delete(r),this.lastSpoke.set(r,s),this.lastSpoke.size>Js&&this.lastSpoke.delete(this.lastSpoke.keys().next().value)}},gn=(t,e)=>`${t}\0${e}`;function hn(t,e){let n=t.style?` Your speaking manner: ${t.style}.`:"";return e?`[VOICE INTRO] This is your first spoken exchange with this person in a while. Open with one short sentence introducing yourself in your own manner, along the lines of "${t.intro}", then answer.${n}`:"[VOICE CASUAL] You have already introduced yourself in this voice conversation. Do not introduce yourself or greet again; talk casually, like a colleague in the same office."+n}function ha(t,e,n,s={}){let r=e[t],i=je(t,e,s),o=(r?.systemPrompt??"").split(/\n\s*\n/)[0].slice(0,600).trim();return{agentId:t,name:i.name,voice:Ne(i),persona:o||`You are ${i.name}.`,introLine:hn(i,n)}}var Ys="[VOICE MODE] This question arrived by voice and your reply will be spoken aloud by a TTS engine. Answer in two or three short sentences. Plain language, no markdown, no code blocks, no bullet points, no URLs. Speak conversationally.";function ya(t){let e=t;if(e?.channel!=="voice"||!e.voice||typeof e.voice!="object")return;let n=i=>typeof i=="string"?i.replace(/\s+/g," ").slice(0,200):"",s=n(e.voice.intro),r={agentId:"",name:"",provider:"system",elevenlabsVoiceId:null,systemVoice:null,systemVoiceName:null,systemByLanguage:{},fallback:!0,gender:null,style:n(e.voice.style)||null,intro:s||"Hello."};return`${Ys}
113
+ ${hn(r,e.voice.introduce===!0&&!!s)}`}import{mkdtemp as Zs,rm as Qs,writeFile as ei}from"fs/promises";import{tmpdir as ti}from"os";import{join as yn}from"path";var ni=1500,ri=64*1024,si=2,Me=0;function Ra(t){return t==="/voice/transcribe"||t==="/voice/speak"}async function Ca(t,e,n,s){return t.method!=="POST"?b(e,405,{error:"POST"}):n==="/voice/transcribe"?ii(t,e,s):li(t,e,s)}async function ii(t,e,n){let s=String(t.headers["content-type"]||""),r=rn(s);if(!r)return b(e,415,{error:"Send the recording as audio (webm, mp4, ogg, mp3 or wav)."});let i=nn(t.headers["x-audio-duration-ms"]);if(i)return t.resume(),b(e,i.status,{error:i.error});let o=await bn(t,C.bytes);if(!o)return b(e,413,{error:di()});if(!o.length)return b(e,400,{error:"The recording is empty."});if(Me>=si)return b(e,429,{error:"This computer is already writing down other recordings. Try again in a moment."});let a=n.stt(),c=n.host(),l=sn(a,c);if(!c.ffmpeg&&!n.allowUnmeasured?.()){let d=n.nodeName?`on ${n.nodeName}`:"on this computer",g=l.length?"":" "+Pe(a,c);return b(e,503,{error:"Voice input isn't set up on this computer.",hint:`Install ffmpeg ${d} for voice input from the phone.${g}`,setup:!1})}if(!l.length)return b(e,503,{error:"Voice input isn't set up on this computer.",hint:Pe(a,c),setup:!1});Me++;let u;try{let d=await Zs(yn(ti(),"agentx-phone-voice-"));try{u=await oi(d,`speech.${r}`,o,s,c,l,n)}finally{await Qs(d,{recursive:!0,force:!0}).catch(()=>{})}}finally{Me--}b(e,u[0],u[1])}async function oi(t,e,n,s,r,i,o){let a=yn(t,e);if(await ei(a,n,{mode:384}),r.ffmpeg){let l=await(o.measure??on)(a,r.ffmpeg);if(l==null)return[422,{error:"This computer couldn't read the recording. Try again."}];if(l*1e3>C.ms+2e3)return[413,{error:Le()}]}let c=[];for(let l of i)try{let u=await ai(l,a,s,r,t,o);return o.log(`[voice] phone recording transcribed with ${l} (${Math.round(n.length/1024)} KB)`),u?[200,{text:u,engine:l}]:[422,{error:"No words were heard. Hold the orb and speak, then let go.",engine:l}]}catch(u){let d=String(u?.message??u).split(`
114
+ `)[0].slice(0,200);c.push(`${l}: ${d}`),o.log(`[voice] phone transcription with ${l} failed: ${d}`)}return[502,{error:"Speech to text failed on this computer.",detail:c.join("; ")}]}function ai(t,e,n,s,r,i){let o=i.engines?.[t];if(o)return o(e,n,s,r);if(t==="elevenlabs")return an(e,n,s.key);let a=t==="mlx-whisper"?s.mlx:s.whisper;return ln(t,a,e,s.ffmpeg,r)}async function li(t,e,n){let s=await bn(t,ri);if(!s)return b(e,413,{error:"request too large"});let r;try{r=JSON.parse(s.toString("utf8")||"{}")}catch{return b(e,400,{error:"expected JSON"})}let i=typeof r?.agent=="string"?r.agent:"",o=typeof r?.peer=="string"&&r.peer?r.peer:void 0;if(!i)return b(e,400,{error:"agent is required"});let a=ci(typeof r?.text=="string"?r.text:"");if(!a)return b(e,422,{error:"Nothing in this answer can be said aloud."});let c=n.voiceOf(i,o);if(!c)return b(e,404,{error:`Unknown agent: ${i}`});let l=(d,g=200)=>b(e,g,{fallback:"browser",reason:d,text:a});if(c.provider!=="elevenlabs")return l("This agent speaks with a system voice, which only plays on the computer.");let u=n.elevenLabsKey();if(!u)return l("No ElevenLabs key is set on this computer.");try{let d=await(n.synth??ui)(u,c,a);e.writeHead(200,{"Content-Type":"audio/mpeg","Content-Length":d.length,"Cache-Control":"no-store","X-Spoken-Chars":String(a.length)}),e.end(d)}catch(d){return n.log(`[voice] phone answer synthesis failed: ${String(d?.message??d).split(`
115
+ `)[0].slice(0,160)}`),l("ElevenLabs could not speak this answer.",502)}}function ci(t){let e=Lt(Xe(t).text).cleanText.replace(/!\[[^\]\n]*\]\([^)\n]*\)/g,"");return cn(e,ni)}async function ui(t,e,n){let s=te(e.rate),r=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(e.elevenlabs)}?output_format=mp3_44100_128`,{method:"POST",headers:{"xi-api-key":t,"Content-Type":"application/json"},body:JSON.stringify({text:n,model_id:"eleven_flash_v2_5",...s?{voice_settings:{speed:s}}:{}}),signal:AbortSignal.timeout(6e4)});if(!r.ok)throw new Error(`ElevenLabs ${r.status}: ${(await r.text().catch(()=>"")).slice(0,160)}`);return Buffer.from(await r.arrayBuffer())}var di=()=>`The recording is larger than ${C.bytes/1024/1024} MB, more than ${C.ms/6e4} minutes of speech.`;function Ta(t,e,n,s){if(e)return s.speakerOn(e,t,!1)?.voice??null;let r=n.agents??{};return r[t]?Ne(je(t,r,n.voice)):null}function bn(t,e){return Number(t.headers["content-length"])>e?(t.resume(),Promise.resolve(null)):new Promise((n,s)=>{let r=[],i=0;t.on("data",o=>{if(!(i>e)){if(i+=o.length,i>e){r.length=0,n(null);return}r.push(o)}}),t.on("end",()=>{i<=e&&n(Buffer.concat(r))}),t.on("error",s)})}function b(t,e,n){t.writeHead(e,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(n))}import{existsSync as x,readFileSync as Be,writeFileSync as We,mkdirSync as ne,readdirSync as Fe,rmSync as gi,statSync as I}from"fs";import{resolve as kn,relative as fi,dirname as He,join as T,extname as F,basename as ze}from"path";var S=200*1024,wn=new Set([".md",".markdown",".txt"]),N=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"]),pi=6,mi=new Set(["CLAUDE.md","SOUL.md","IDENTITY.md","PERSONA.md","AGENT.md","BOOTSTRAP.md"]);function _(t,e){if(!t)throw new Error("Agent workspace is not configured.");let n=kn(t);if(x(n)||ne(n,{recursive:!0}),!e||e.startsWith("/")||e.match(/^[a-zA-Z]:/))throw new Error(`Path must be relative to the workspace: ${e}`);let s=kn(n,e);if(fi(n,s).startsWith(".."))throw new Error(`Path escapes the workspace: ${e}`);return s}function Sn(t){let e=F(t).toLowerCase();if(!wn.has(e))throw new Error(`Only text files (.md, .markdown, .txt) can be edited from the admin panel (got ${e}).`)}function Ve(t,e){let n=t.split(/\r?\n/).find(s=>s.trim().startsWith("#"));return n&&n.replace(/^#+\s*/,"").trim().slice(0,120)||e}function Pa(t){let e=_(t,"."),n=[],s=new Set,r=[];try{r=Fe(e)}catch{}for(let a of mi){let c=T(e,a);if(x(c)&&I(c).isFile()){let l=I(c).size,u=l>0&&l<S?Ue(c):"";n.push({path:a,title:Ve(u,a),size:l,exists:!0}),s.add(a)}else n.push({path:a,title:a,size:0,exists:!1}),s.add(a)}for(let a of r){if(s.has(a))continue;let c=T(e,a);try{let l=I(c);if(!l.isFile()||!wn.has(F(a).toLowerCase()))continue;let u=l.size>0&&l.size<S?Ue(c):"";n.push({path:a,title:Ve(u,a),size:l.size,exists:!0})}catch{}}let i=[],o=T(e,".claude","skills");if(x(o))try{for(let a of Fe(o)){let c=T(o,a),l;try{l=I(c)}catch{continue}if(!l.isDirectory())continue;let u=T(c,"SKILL.md");if(!x(u))continue;let d=I(u),g=d.size<S?Ue(u):"";i.push({slug:a,title:Ve(g,a),size:d.size,path:`.claude/skills/${a}/SKILL.md`})}}catch{}return i.sort((a,c)=>a.slug.localeCompare(c.slug)),{identity:n,skills:i,workspace:e}}function Ue(t){try{return Be(t,"utf-8")}catch{return""}}function Oa(t,e){let n=_(t,e);if(Sn(n),!x(n))return{path:e,content:""};if(I(n).size>S)throw new Error(`File is too large to edit in the admin panel (> ${S/1024} KB).`);return{path:e,content:Be(n,"utf-8")}}function ja(t,e,n){let s=_(t,e);Sn(s);let r=Buffer.from(n,"utf-8");if(r.length>S)throw new Error(`File too large (${r.length} > ${S} bytes).`);return ne(He(s),{recursive:!0}),We(s,r),{path:e,bytes:r.length}}function Na(t,e,n={}){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=_(t,s);if(x(r))throw new Error(`Skill "${e}" already exists.`);ne(He(r),{recursive:!0});let i=n.content?.trim()?n.content:hi(e,n.title);return We(r,i),{slug:e,path:s}}function Ma(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=_(t,`.claude/skills/${e}`);if(!x(n))throw new Error(`Skill "${e}" not found.`);if(!I(n).isDirectory())throw new Error(`Skill path is not a directory: ${e}`);return gi(n,{recursive:!0,force:!0}),{slug:e}}function Va(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=_(t,`.claude/skills/${e}`);if(!x(n))throw new Error(`Skill "${e}" not found.`);let s=[];return r(n,"",0,s),s.sort((i,o)=>i.kind!==o.kind?i.kind==="dir"?-1:1:i.path.localeCompare(o.path)),s;function r(i,o,a,c){if(a>pi)return;let l=[];try{l=Fe(i)}catch{return}for(let u of l){if(u==="node_modules"||u===".git")continue;let d=T(i,u),g=o?`${o}/${u}`:u,f;try{f=I(d)}catch{continue}if(f.isDirectory())c.push({path:`${g}/`,kind:"dir",size:0,editable:!1}),r(d,g,a+1,c);else if(f.isFile()){let p=F(u).toLowerCase(),h=N.has(p)||N.has(u.toLowerCase());c.push({path:g,kind:"file",size:f.size,editable:h&&f.size<S})}}}}function Ua(t,e,n){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);if(!n||n.includes(".."))throw new Error(`Invalid file path: ${n}`);let s=_(t,`.claude/skills/${e}/${n}`);if(!x(s)||!I(s).isFile())throw new Error(`File not found: ${n}`);let r=F(s).toLowerCase(),i=ze(s).toLowerCase();if(!N.has(r)&&!N.has(i))throw new Error(`File type not editable: ${n}`);if(I(s).size>S)throw new Error(`File too large to edit (> ${S/1024} KB): ${n}`);return{path:n,content:Be(s,"utf-8")}}function Fa(t,e,n,s){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);if(!n||n.includes(".."))throw new Error(`Invalid file path: ${n}`);let r=_(t,`.claude/skills/${e}/${n}`),i=F(r).toLowerCase(),o=ze(r).toLowerCase();if(!N.has(i)&&!N.has(o))throw new Error(`File type not editable: ${n}`);let a=Buffer.from(s,"utf-8");if(a.length>S)throw new Error(`File too large (${a.length} > ${S} bytes).`);return ne(He(r),{recursive:!0}),We(r,a),{path:n,bytes:a.length}}function Ba(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=_(t,`.claude/skills/${e}`);if(!x(n))throw new Error(`Skill "${e}" not found.`);let s=r=>x(T(n,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 hi(t,e){return`# ${e?.trim()||t}
116
116
 
117
117
  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.
118
118
 
@@ -125,7 +125,7 @@ Document the arguments, commands, or files the skill expects. Example:
125
125
 
126
126
  \`\`\`bash
127
127
  # Example invocation
128
- claude-code ${He(t)} --arg value
128
+ claude-code ${ze(t)} --arg value
129
129
  \`\`\`
130
- `}In();var Sn={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function xn(t){return{...Sn,...t??{},regions:{...t?.regions??{}},buffer:{...Sn.buffer,...t?.buffer??{}}}}function Wa(t){try{return xn(ze(t).screen)}catch{return xn(void 0)}}var hi=/^[a-z][\w-]*$/,$n=["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 vn(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 Ha(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(!hi.test(i))throw new Error(`region name "${i}" must be lowercase letters, digits, - or _`);o===null?delete r[i]:r[i]=vn(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&&!$n.includes(s)&&!n.regions?.[s])try{vn(s)}catch{throw new Error(`buffer.region "${s}" is not a region \u2014 use ${[...$n,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{rt as a,ki as b,Se as c,Nr as d,Mr as e,vo as f,Io as g,Ao as h,Dt as i,Ro as j,w as k,$i as l,dt as m,Ri as n,gt as o,Ci as p,ft as q,pt as r,M as s,Li as t,Pi as u,ji as v,Oi as w,Ni as x,G as y,Bi as z,Zi as A,Qi as B,Lo as C,Zr as D,Po as E,to as F,no as G,ro as H,so as I,io as J,oo as K,lo as L,co as M,_e as N,Wo as O,Z as P,Ce as Q,As as R,Qo as S,ea as T,ta as U,Yt as V,na as W,C as X,tn as Y,nn as Z,la as _,js as $,ln as aa,Vs as ba,je as ca,gn as da,Ws as ea,Hs as fa,fa as ga,zs as ha,Oe as ia,Ks as ja,Gs as ka,un as la,pn as ma,ma as na,Js as oa,pa,Aa as qa,_a as ra,ui as sa,Ra as ta,yn as ua,q as va,po as wa,Ct as xa,ge as ya,ke as za,xo as Aa,Da as Ba,La as Ca,Pa as Da,ja as Ea,Oa as Fa,Na as Ga,Ma as Ha,Va as Ia,Fa as Ja,Sn as Ka,xn as La,Wa as Ma,$n as Na,Ha as Oa};
131
- //# sourceMappingURL=chunk-S2VETB7B.js.map
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,pt 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,ma 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-EOKOGQZG.js.map